1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- [[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.Range;
- --------------------------------------------------
- [source,java]
- --------------------------------------------------
- // sr is here your SearchResponse object
- Range agg = sr.getAggregations().get("agg");
- // For each entry
- for (Range.Bucket entry : agg.getBuckets()) {
- String key = entry.getKeyAsString(); // Date range as key
- DateTime fromAsDate = (DateTime) entry.getFrom(); // Date bucket from as a Date
- DateTime toAsDate = (DateTime) entry.getTo(); // 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]
- --------------------------------------------------
|