Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.

Reverse Nested Aggregation

More info about reverse nested aggregation is in the official elasticsearch docs

A special single bucket aggregation that enables aggregating on parent docs from nested documents.

Simple example

{
  "aggregations": {
    "agg_comments": {
      "nested": {
        "path": "comments"
      },
      "aggregations": {
        "agg_top_usernames": {
          "terms": {
            "field": "comments.username"
          },
          "aggregations": {
            "agg_comment_to_issue": {
              "reverse_nested": {},
              "aggregations": {
                "top_tags_per_comment": {
                  "terms": {
                    "field": "tags"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

And now the query via DSL:

$tagsTermsAggregations = new TermsAggregation('top_tags_per_comment', 'tags');

$reverseNestedAggregation = new ReverseNestedAggregation('comment_to_issue');
$reverseNestedAggregation->addAggregation($tagsTermsAggregations);

$usernameTermsAggregation = new TermsAggregation('top_usernames', 'comments.username');
$usernameTermsAggregation->addAggregation($reverseNestedAggregation);

$nestedAggregation = new NestedAggregation('comments', 'comments');
$nestedAggregation->addAggregation($usernameTermsAggregation);

$search = new Search();
$search->addAggregation($nestedAggregation);

$queryArray = $search->toArray();