daterange-aggregation.asciidoc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. [[java-aggs-bucket-daterange]]
  2. ==== Date Range Aggregation
  3. Here is how you can use
  4. {ref}/search-aggregations-bucket-daterange-aggregation.html[Date 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. .dateRange("agg")
  13. .field("dateOfBirth")
  14. .format("yyyy")
  15. .addUnboundedTo("1950") // from -infinity to 1950 (excluded)
  16. .addRange("1950", "1960") // from 1950 to 1960 (excluded)
  17. .addUnboundedFrom("1960"); // from 1960 to +infinity
  18. --------------------------------------------------
  19. ===== Use aggregation response
  20. Import Aggregation definition classes:
  21. [source,java]
  22. --------------------------------------------------
  23. import org.elasticsearch.search.aggregations.bucket.range.Range;
  24. --------------------------------------------------
  25. [source,java]
  26. --------------------------------------------------
  27. // sr is here your SearchResponse object
  28. Range agg = sr.getAggregations().get("agg");
  29. // For each entry
  30. for (Range.Bucket entry : agg.getBuckets()) {
  31. String key = entry.getKeyAsString(); // Date range as key
  32. DateTime fromAsDate = (DateTime) entry.getFrom(); // Date bucket from as a Date
  33. DateTime toAsDate = (DateTime) entry.getTo(); // Date bucket to as a Date
  34. long docCount = entry.getDocCount(); // Doc count
  35. logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, fromAsDate, toAsDate, docCount);
  36. }
  37. --------------------------------------------------
  38. This will basically produce:
  39. [source,text]
  40. --------------------------------------------------
  41. key [*-1950], from [null], to [1950-01-01T00:00:00.000Z], doc_count [8]
  42. key [1950-1960], from [1950-01-01T00:00:00.000Z], to [1960-01-01T00:00:00.000Z], doc_count [5]
  43. key [1960-*], from [1960-01-01T00:00:00.000Z], to [null], doc_count [37]
  44. --------------------------------------------------