Search code examples
elasticsearchelasticsearch-aggregationelasticsearch-mapping

Aggregation of fields inside nested type field


I want to aggregate keyword type field which lies inside a nested type field. The mapping for nested field is as below:

"Nested_field" : {
    "type" : "nested",
    "properties" : {
        "Keyword_field" : {
            "type" : "keyword"
        }
    }
}

And the part of query which I am using to aggregate is as below:

"aggregations": {
    "Nested_field": {
        "aggregations": {
            "Keyword_field": {
                "terms": {
                    "field": "Nested_field.Keyword_field"
                }
            }
        },
        "filter": {
            "bool": {}
        }
    },
}

But this is not returning correct aggregation. Even though there are Keyword_field value existing docs, the query returns 0 buckets. So, there is something wrong in my aggregation query. Can anyone help me to find what's wrong?


Solution

  • I think you need to provide a nested path in there. This worked in ES 5, but it looks like you're using 6 based on the "aggregations" vs "aggs", so let me know if it doesn't work and I'll scrap this answer. Give this a try:

    {
        "aggregations": {
            "nested_level": {
                "nested": {
                    "path": "Nested_field"
                },
                "aggregations": {
                    "keyword_field": {
                        "terms": {
                            "field": "Nested_field.Keyword_field"
                        }
                    }
                }
            }
        }
    }