How to get an Elasticsearch aggregation with multiple fields How to get an Elasticsearch aggregation with multiple fields elasticsearch elasticsearch

How to get an Elasticsearch aggregation with multiple fields


By the looks of it, your tags is not nested.For this aggregation to work, you need it nested so that there is an association between an id and a name. Without nested the list of ids is just an array and the list of names is another array:

    "item": {      "properties": {        "meta": {          "properties": {            "tags": {              "type": "nested",           <-- nested field              "include_in_parent": true,  <-- to, also, keep the flat array-like structure              "properties": {                "id": {                  "type": "integer"                },                "name": {                  "type": "string"                }              }            }          }        }      }    }

Also, note that I've added to the mapping this line "include_in_parent": true which means that your nested tags will, also, behave like a "flat" array-like structure.

So, everything you had so far in your queries will still work without any changes to the queries.

But, for this particular query of yours, the aggregation needs to change to something like this:

{  "aggs": {    "baked_goods": {      "nested": {        "path": "item.meta.tags"      },      "aggs": {        "name": {          "terms": {            "field": "item.meta.tags.id"          },          "aggs": {            "name": {              "terms": {                "field": "item.meta.tags.name"              }            }          }        }      }    }  }}

And the result is like this:

   "aggregations": {      "baked_goods": {         "doc_count": 9,         "name": {            "doc_count_error_upper_bound": 0,            "sum_other_doc_count": 0,            "buckets": [               {                  "key": 123,                  "doc_count": 3,                  "name": {                     "doc_count_error_upper_bound": 0,                     "sum_other_doc_count": 0,                     "buckets": [                        {                           "key": "biscuits",                           "doc_count": 3                        }                     ]                  }               },               {                  "key": 456,                  "doc_count": 2,                  "name": {                     "doc_count_error_upper_bound": 0,                     "sum_other_doc_count": 0,                     "buckets": [                        {                           "key": "cakes",                           "doc_count": 2                        }                     ]                  }               },               .....