[[java-aggs-bucket-daterange]] ==== Date Range Aggregation Here is how you can use {ref}/search-aggregations-bucket-daterange-aggregation.html[Date Range Aggregation] with Java API. ===== Prepare aggregation request Here is an example on how to create the aggregation request: [source,java] -------------------------------------------------- AggregationBuilder aggregation = AggregationBuilders .dateRange("agg") .field("dateOfBirth") .format("yyyy") .addUnboundedTo("1950") // from -infinity to 1950 (excluded) .addRange("1950", "1960") // from 1950 to 1960 (excluded) .addUnboundedFrom("1960"); // from 1960 to +infinity -------------------------------------------------- ===== Use aggregation response Import Aggregation definition classes: [source,java] -------------------------------------------------- import org.elasticsearch.search.aggregations.bucket.range.date.DateRange; -------------------------------------------------- [source,java] -------------------------------------------------- // sr is here your SearchResponse object DateRange agg = sr.getAggregations().get("agg"); // For each entry for (DateRange.Bucket entry : agg.getBuckets()) { String key = entry.getKey(); // Date range as key DateTime fromAsDate = entry.getFromAsDate(); // Date bucket from as a Date DateTime toAsDate = entry.getToAsDate(); // Date bucket to as a Date long docCount = entry.getDocCount(); // Doc count logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, fromAsDate, toAsDate, docCount); } -------------------------------------------------- This will basically produce: [source,text] -------------------------------------------------- key [*-1950], from [null], to [1950-01-01T00:00:00.000Z], doc_count [8] key [1950-1960], from [1950-01-01T00:00:00.000Z], to [1960-01-01T00:00:00.000Z], doc_count [5] key [1960-*], from [1960-01-01T00:00:00.000Z], to [null], doc_count [37] --------------------------------------------------