WARNING: Version 2.1 of Elasticsearch has passed its EOL date.
This documentation is no longer being maintained and may be removed. If you are running this version, we strongly advise you to upgrade. For the latest information, see the current release documentation.
Reverse nested Aggregation
editReverse nested Aggregation
editA special single bucket aggregation that enables aggregating on parent docs from nested documents. Effectively this aggregation can break out of the nested block structure and link to other nested structures or the root document, which allows nesting other aggregations that aren’t part of the nested object in a nested aggregation.
The reverse_nested
aggregation must be defined inside a nested
aggregation.
Options:
-
path
- Which defines to what nested object field should be joined back. The default is empty, which means that it joins back to the root / main document level. The path cannot contain a reference to a nested object field that falls outside thenested
aggregation’s nested structure areverse_nested
is in.
For example, lets say we have an index for a ticket system with issues and comments. The comments are inlined into the issue documents as nested documents. The mapping could look like:
{ ... "issue" : { "properties" : { "tags" : { "type" : "string" } "comments" : { "type" : "nested" "properties" : { "username" : { "type" : "string", "index" : "not_analyzed" }, "comment" : { "type" : "string" } } } } } }
The following aggregations will return the top commenters' username that have commented and per top commenter the top tags of the issues the user has commented on:
{ "query": { "match": { "name": "led tv" } }, "aggs": { "comments": { "nested": { "path": "comments" }, "aggs": { "top_usernames": { "terms": { "field": "comments.username" }, "aggs": { "comment_to_issue": { "reverse_nested": {}, "aggs": { "top_tags_per_comment": { "terms": { "field": "tags" } } } } } } } } } }
As you can see above, the the reverse_nested
aggregation is put in to a nested
aggregation as this is the only place
in the dsl where the reversed_nested
aggregation can be used. Its sole purpose is to join back to a parent doc higher
up in the nested structure.
A |
Possible response snippet:
{ "aggregations": { "comments": { "top_usernames": { "buckets": [ { "key": "username_1", "doc_count": 12, "comment_to_issue": { "top_tags_per_comment": { "buckets": [ { "key": "tag1", "doc_count": 9 }, ... ] } } }, ... ] } } } }