andrei albu
andrei albu

Reputation: 1

Aggregation on nested field not working

Im unable to do an aggregation on nested documents. Here are 2 of the sample documents: document 1

{
  "name": "Samuel Lone",
  "assignments": [
    {
      "subject": "data structures",
      "score": 43,
      "dept": "cs"
    },
    {
      "subject": "fluid theory",
      "score": 37,
      "dept": "ec"
    }
  ]
}

document2

{
  "name": "Manya Pious",
  "assignments": [
    {
      "subject": "data structures",
      "score": 43,
      "dept": "cs"
    },
    {
      "subject": "fluid theory",
      "score": 37,
      "dept": "ec"
    }
  ]
}

When i give the following query for aggregation ,it results in no results.

{
  "aggs": {
    "dept_breakdown": {
      "terms": {
        "field": "assignments.dept"
      }
    }
  }
}

How can I get the aggregation on the field "assignments.dept" done?

Upvotes: 0

Views: 382

Answers (2)

Calle
Calle

Reputation: 1800

For nested fields, use nested aggregations:

POST /your_index/_search?search_type=count
{
   "aggs": {
      "nested_assignments": {
         "nested": {
            "path": "assignments"
         },
         "aggs": {
            "dept_terms": {
               "terms": {
                  "field": "assignments.dept"
               }
            }
         }
      }
   }
}

If this doesn't help, please post your mapping of the docs as well.

Upvotes: 1

bittusarkar
bittusarkar

Reputation: 6357

If the field "assignments" is of nested type, then you need to use nested aggregations. Your original query will work fine if "assignments" field is not of nested type.

{
   "aggs": {
      "dept_breakdown": {
         "nested": {
            "path": "assignments"
         },
         "aggs": {
            "departments": {
               "terms": {
                  "field": "assignments.dept"
               }
            }
         }
      }
   }
}

Upvotes: 0

Related Questions