[[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()) {
    String key = entry.getKey();            // Range as key
    Number from = entry.getFrom();          // Bucket from
    Number to = entry.getTo();              // Bucket to
    long docCount = entry.getDocCount();    // Doc count

    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]
--------------------------------------------------

