Ahffan kondeth
Ahffan kondeth

Reputation: 63

Not able to aggregate on nested fields in elasticsearch

I have set a field to nested and now i am not able to aggregate on it. Sample document -

{
"attributes" : [
{ "name" : "snake" , "type" : "reptile" },
{ "name" : "cow" , "type" : "mamal" }
]
}

attributes field is nested. Following terms query is not working on this

{ 
"aggs" : {
"terms" : { "field" : "attributes.name" }
}
}

How can I do the aggregation in elasticsearch?

Upvotes: 2

Views: 253

Answers (1)

Sloan Ahrens
Sloan Ahrens

Reputation: 8718

Use a nested aggregation.

As a simple example, I created an index with a nested property matching what you posted:

PUT /test_index
{
   "mappings": {
      "doc": {
         "properties": {
            "attributes": {
               "type": "nested",
               "properties": {
                  "name": {
                     "type": "string"
                  },
                  "type": {
                     "type": "string"
                  }
               }
            }
         }
      }
   }
}

Then added your document:

PUT /test_index/doc/1
{
   "attributes": [
      { "name": "snake", "type": "reptile" },
      { "name": "cow", "type": "mammal" }
   ]
}

Now I can get "attribute.name" terms as follows:

POST /test_index/_search?search_type=count
{
   "aggs": {
      "nested_attributes": {
         "nested": {
            "path": "attributes"
         },
         "aggs": {
            "name_terms": {
               "terms": {
                  "field": "attributes.name"
               }
            }
         }
      }
   }
}
...
{
   "took": 7,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "nested_attributes": {
         "doc_count": 2,
         "name_terms": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
               {
                  "key": "cow",
                  "doc_count": 1
               },
               {
                  "key": "snake",
                  "doc_count": 1
               }
            ]
         }
      }
   }
}

Here's the code I used:

http://sense.qbox.io/gist/0e3ed9c700f240e523be08a27551707d4448a9df

Upvotes: 3

Related Questions