| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 | [[java-aggs]]== AggregationsElasticsearch provides a full Java API to play with aggregations. See the{ref}/search-aggregations.html[Aggregations guide].Use the factory for aggregation builders (`AggregationBuilders`) and add each aggregationyou want to compute when querying and add it to your search request:[source,java]--------------------------------------------------SearchResponse sr = node.client().prepareSearch()        .setQuery( /* your query */ )        .addAggregation( /* add an aggregation */ )        .execute().actionGet();--------------------------------------------------Note that you can add more than one aggregation. See{ref}/search-search.html[Search Java API] for details.To build aggregation requests, use `AggregationBuilders` helpers. Just import themin your class:[source,java]--------------------------------------------------import org.elasticsearch.search.aggregations.AggregationBuilders;--------------------------------------------------=== Structuring aggregationsAs explained in the{ref}/search-aggregations.html[Aggregations guide], you can definesub 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)[source,java]--------------------------------------------------SearchResponse sr = node.client().prepareSearch()    .addAggregation(        AggregationBuilders.terms("by_country").field("country")        .subAggregation(AggregationBuilders.dateHistogram("by_year")            .field("dateOfBirth")            .interval((DateHistogramInterval.YEAR)            .subAggregation(AggregationBuilders.avg("avg_children").field("children"))        )    )    .execute().actionGet();--------------------------------------------------=== Metrics aggregationsinclude::aggregations/metrics.asciidoc[]=== Bucket aggregationsinclude::aggregations/bucket.asciidoc[]
 |