range-aggregation.asciidoc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. [[java-aggs-bucket-range]]
  2. ==== Range Aggregation
  3. Here is how you can use
  4. {ref}/search-aggregations-bucket-range-aggregation.html[Range Aggregation]
  5. with Java API.
  6. ===== Prepare aggregation request
  7. Here is an example on how to create the aggregation request:
  8. [source,java]
  9. --------------------------------------------------
  10. AggregationBuilder aggregation =
  11. AggregationBuilders
  12. .range("agg")
  13. .field("height")
  14. .addUnboundedTo(1.0f) // from -infinity to 1.0 (excluded)
  15. .addRange(1.0f, 1.5f) // from 1.0 to 1.5 (excluded)
  16. .addUnboundedFrom(1.5f); // from 1.5 to +infinity
  17. --------------------------------------------------
  18. ===== Use aggregation response
  19. Import Aggregation definition classes:
  20. [source,java]
  21. --------------------------------------------------
  22. import org.elasticsearch.search.aggregations.bucket.range.Range;
  23. --------------------------------------------------
  24. [source,java]
  25. --------------------------------------------------
  26. // sr is here your SearchResponse object
  27. Range agg = sr.getAggregations().get("agg");
  28. // For each entry
  29. for (Range.Bucket entry : agg.getBuckets()) {
  30. String key = entry.getKeyAsString(); // Range as key
  31. Number from = (Number) entry.getFrom(); // Bucket from
  32. Number to = (Number) entry.getTo(); // Bucket to
  33. long docCount = entry.getDocCount(); // Doc count
  34. logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, from, to, docCount);
  35. }
  36. --------------------------------------------------
  37. This will basically produce for the first example:
  38. [source,text]
  39. --------------------------------------------------
  40. key [*-1.0], from [-Infinity], to [1.0], doc_count [9]
  41. key [1.0-1.5], from [1.0], to [1.5], doc_count [21]
  42. key [1.5-*], from [1.5], to [Infinity], doc_count [20]
  43. --------------------------------------------------