Structuring aggregations

As explained in the Aggregations guide, you can define sub aggregations inside an aggregation.

An aggregation could be a metrics aggregation or a bucket aggregation.

For example, here is a 3 levels aggregation composed of:

  • Terms aggregation (bucket)
  • Date Histogram aggregation (bucket)
  • Average aggregation (metric)
SearchResponse sr = node.client().prepareSearch()
    .addAggregation(
        AggregationBuilders.terms("by_country").field("country")
        .subAggregation(AggregationBuilders.dateHistogram("by_year")
            .field("dateOfBirth")
            .interval((DateHistogram.Interval.YEAR)
            .subAggregation(AggregationBuilders.avg("avg_children").field("children"))
        )
    )
    .execute().actionGet();