2014-05-15 06:36:05 -04:00
|
|
|
[[java-aggs-bucket-range]]
|
|
|
|
==== Range Aggregation
|
|
|
|
|
|
|
|
Here is how you can use
|
|
|
|
{ref}/search-aggregations-bucket-range-aggregation.html[Range Aggregation]
|
|
|
|
with Java API.
|
|
|
|
|
|
|
|
|
|
|
|
===== Prepare aggregation request
|
|
|
|
|
|
|
|
Here is an example on how to create the aggregation request:
|
|
|
|
|
|
|
|
[source,java]
|
|
|
|
--------------------------------------------------
|
|
|
|
AggregationBuilder aggregation =
|
|
|
|
AggregationBuilders
|
|
|
|
.range("agg")
|
|
|
|
.field("height")
|
|
|
|
.addUnboundedTo(1.0f) // from -infinity to 1.0 (excluded)
|
|
|
|
.addRange(1.0f, 1.5f) // from 1.0 to 1.5 (excluded)
|
|
|
|
.addUnboundedFrom(1.5f); // from 1.5 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()) {
|
2015-06-03 11:08:32 -04:00
|
|
|
String key = entry.getKeyAsString(); // Range as key
|
2015-03-05 05:56:13 -05:00
|
|
|
Number from = (Number) entry.getFrom(); // Bucket from
|
|
|
|
Number to = (Number) entry.getTo(); // Bucket to
|
2015-06-03 11:08:32 -04:00
|
|
|
long docCount = entry.getDocCount(); // Doc count
|
2014-05-15 06:36:05 -04:00
|
|
|
|
|
|
|
logger.info("key [{}], from [{}], to [{}], doc_count [{}]", key, from, to, docCount);
|
|
|
|
}
|
|
|
|
--------------------------------------------------
|
|
|
|
|
|
|
|
This will basically produce for the first example:
|
|
|
|
|
|
|
|
[source,text]
|
|
|
|
--------------------------------------------------
|
|
|
|
key [*-1.0], from [-Infinity], to [1.0], doc_count [9]
|
|
|
|
key [1.0-1.5], from [1.0], to [1.5], doc_count [21]
|
|
|
|
key [1.5-*], from [1.5], to [Infinity], doc_count [20]
|
|
|
|
--------------------------------------------------
|
|
|
|
|