0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Use Range Aggregation in Elasticsearch

Use range aggregation in Elasticsearch to group documents by numeric ranges on a field. Define ranges with from and/or to values inside the aggregation to get counts of documents falling into each range.
📐

Syntax

The range aggregation groups documents based on numeric ranges of a specified field. You define the field and an array of ranges with from and/or to values.

  • field: The numeric field to aggregate on.
  • ranges: Array of objects defining from and/or to values for each range.
json
{
  "aggs": {
    "range_agg": {
      "range": {
        "field": "numeric_field",
        "ranges": [
          { "to": 10 },
          { "from": 10, "to": 20 },
          { "from": 20 }
        ]
      }
    }
  }
}
💻

Example

This example shows how to count documents grouped by price ranges: less than 50, between 50 and 100, and greater than 100.

json
{
  "size": 0,
  "aggs": {
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "to": 50 },
          { "from": 50, "to": 100 },
          { "from": 100 }
        ]
      }
    }
  }
}
Output
{ "aggregations": { "price_ranges": { "buckets": [ { "key": "* - 50.0", "to": 50, "doc_count": 15 }, { "key": "50.0 - 100.0", "from": 50, "to": 100, "doc_count": 30 }, { "key": "100.0 - *", "from": 100, "doc_count": 5 } ] } } }
⚠️

Common Pitfalls

  • Not specifying field correctly causes errors or empty results.
  • Ranges must not overlap unless intentional; overlapping ranges can cause confusing counts.
  • Using non-numeric fields with range aggregation will fail.
  • Missing from or to in ranges is allowed but be clear about open-ended ranges.
json
{
  "aggs": {
    "wrong_range": {
      "range": {
        "field": "price",
        "ranges": [
          { "from": 20, "to": 10 }  
        ]
      }
    }
  }
}

// Corrected:
{
  "aggs": {
    "correct_range": {
      "range": {
        "field": "price",
        "ranges": [
          { "from": 10, "to": 20 }
        ]
      }
    }
  }
}
📊

Quick Reference

ParameterDescription
fieldThe numeric field to aggregate on.
rangesArray of ranges with optional 'from' and 'to' values.
fromLower bound of the range (inclusive).
toUpper bound of the range (exclusive).
keyOptional name for the range bucket.

Key Takeaways

Use range aggregation to group numeric data into defined ranges.
Define ranges with from and/or to to set boundaries.
Ensure the field is numeric and correctly mapped in Elasticsearch.
Avoid overlapping ranges unless you want documents counted in multiple buckets.
Open-ended ranges can be created by omitting from or to.