aggs.asciidoc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. [[java-aggs]]
  2. == Aggregations
  3. Elasticsearch provides a full Java API to play with aggregations. See the
  4. {ref}/search-aggregations.html[Aggregations guide].
  5. Use the factory for aggregation builders (`AggregationBuilders`) and add each aggregation
  6. you want to compute when querying and add it to your search request:
  7. [source,java]
  8. --------------------------------------------------
  9. SearchResponse sr = node.client().prepareSearch()
  10. .setQuery( /* your query */ )
  11. .addAggregation( /* add an aggregation */ )
  12. .execute().actionGet();
  13. --------------------------------------------------
  14. Note that you can add more than one aggregation. See
  15. {ref}/search-search.html[Search Java API] for details.
  16. To build aggregation requests, use `AggregationBuilders` helpers. Just import them
  17. in your class:
  18. [source,java]
  19. --------------------------------------------------
  20. import org.elasticsearch.search.aggregations.AggregationBuilders;
  21. --------------------------------------------------
  22. === Structuring aggregations
  23. As explained in the
  24. {ref}/search-aggregations.html[Aggregations guide], you can define
  25. sub aggregations inside an aggregation.
  26. An aggregation could be a metrics aggregation or a bucket aggregation.
  27. For example, here is a 3 levels aggregation composed of:
  28. * Terms aggregation (bucket)
  29. * Date Histogram aggregation (bucket)
  30. * Average aggregation (metric)
  31. [source,java]
  32. --------------------------------------------------
  33. SearchResponse sr = node.client().prepareSearch()
  34. .addAggregation(
  35. AggregationBuilders.terms("by_country").field("country")
  36. .subAggregation(AggregationBuilders.dateHistogram("by_year")
  37. .field("dateOfBirth")
  38. .dateHistogramInterval(DateHistogramInterval.YEAR)
  39. .subAggregation(AggregationBuilders.avg("avg_children").field("children"))
  40. )
  41. )
  42. .execute().actionGet();
  43. --------------------------------------------------
  44. === Metrics aggregations
  45. include::aggregations/metrics.asciidoc[]
  46. === Bucket aggregations
  47. include::aggregations/bucket.asciidoc[]