| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 | [[java-aggs-bucket-datehistogram]]==== Date Histogram AggregationHere is how you can use{ref}/search-aggregations-bucket-datehistogram-aggregation.html[Date Histogram Aggregation]with Java API.===== Prepare aggregation requestHere is an example on how to create the aggregation request:[source,java]--------------------------------------------------AggregationBuilder aggregation =        AggregationBuilders                .dateHistogram("agg")                .field("dateOfBirth")                .dateHistogramInterval(DateHistogramInterval.YEAR);--------------------------------------------------Or if you want to set an interval of 10 days:[source,java]--------------------------------------------------AggregationBuilder aggregation =        AggregationBuilders                .dateHistogram("agg")                .field("dateOfBirth")                .dateHistogramInterval(DateHistogramInterval.days(10));--------------------------------------------------===== Use aggregation responseImport Aggregation definition classes:[source,java]--------------------------------------------------import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;--------------------------------------------------[source,java]--------------------------------------------------// sr is here your SearchResponse objectHistogram agg = sr.getAggregations().get("agg");// For each entryfor (Histogram.Bucket entry : agg.getBuckets()) {    DateTime key = (DateTime) entry.getKey();    // Key    String keyAsString = entry.getKeyAsString(); // Key as String    long docCount = entry.getDocCount();         // Doc count    logger.info("key [{}], date [{}], doc_count [{}]", keyAsString, key.getYear(), docCount);}--------------------------------------------------This will basically produce for the first example:[source,text]--------------------------------------------------key [1942-01-01T00:00:00.000Z], date [1942], doc_count [1]key [1945-01-01T00:00:00.000Z], date [1945], doc_count [1]key [1946-01-01T00:00:00.000Z], date [1946], doc_count [1]...key [2005-01-01T00:00:00.000Z], date [2005], doc_count [1]key [2007-01-01T00:00:00.000Z], date [2007], doc_count [2]key [2008-01-01T00:00:00.000Z], date [2008], doc_count [3]--------------------------------------------------===== OrderSupports the same order functionality as the <<java-aggs-bucket-terms,`Terms Aggregation`>>.
 |