datehistogram-aggregation.asciidoc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. [[java-aggs-bucket-datehistogram]]
  2. ==== Date Histogram Aggregation
  3. Here is how you can use
  4. {ref}/search-aggregations-bucket-datehistogram-aggregation.html[Date Histogram 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. .dateHistogram("agg")
  13. .field("dateOfBirth")
  14. .dateHistogramInterval(DateHistogramInterval.YEAR);
  15. --------------------------------------------------
  16. Or if you want to set an interval of 10 days:
  17. [source,java]
  18. --------------------------------------------------
  19. AggregationBuilder aggregation =
  20. AggregationBuilders
  21. .dateHistogram("agg")
  22. .field("dateOfBirth")
  23. .dateHistogramInterval(DateHistogramInterval.days(10));
  24. --------------------------------------------------
  25. ===== Use aggregation response
  26. Import Aggregation definition classes:
  27. [source,java]
  28. --------------------------------------------------
  29. import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
  30. --------------------------------------------------
  31. [source,java]
  32. --------------------------------------------------
  33. // sr is here your SearchResponse object
  34. Histogram agg = sr.getAggregations().get("agg");
  35. // For each entry
  36. for (Histogram.Bucket entry : agg.getBuckets()) {
  37. DateTime key = (DateTime) entry.getKey(); // Key
  38. String keyAsString = entry.getKeyAsString(); // Key as String
  39. long docCount = entry.getDocCount(); // Doc count
  40. logger.info("key [{}], date [{}], doc_count [{}]", keyAsString, key.getYear(), docCount);
  41. }
  42. --------------------------------------------------
  43. This will basically produce for the first example:
  44. [source,text]
  45. --------------------------------------------------
  46. key [1942-01-01T00:00:00.000Z], date [1942], doc_count [1]
  47. key [1945-01-01T00:00:00.000Z], date [1945], doc_count [1]
  48. key [1946-01-01T00:00:00.000Z], date [1946], doc_count [1]
  49. ...
  50. key [2005-01-01T00:00:00.000Z], date [2005], doc_count [1]
  51. key [2007-01-01T00:00:00.000Z], date [2007], doc_count [2]
  52. key [2008-01-01T00:00:00.000Z], date [2008], doc_count [3]
  53. --------------------------------------------------