0
0
Elasticsearchquery~5 mins

Range buckets in Elasticsearch

Choose your learning style9 modes available
Introduction

Range buckets help group data into ranges so you can see how many items fall into each range.

When you want to count how many products fall into different price ranges.
When you want to see how many users are in different age groups.
When you want to analyze data by time periods, like visits in different hours.
When you want to group measurements like temperature into ranges.
When you want to summarize data by ranges instead of exact values.
Syntax
Elasticsearch
{
  "aggs": {
    "range_name": {
      "range": {
        "field": "field_name",
        "ranges": [
          { "to": value1 },
          { "from": value1, "to": value2 },
          { "from": value2 }
        ]
      }
    }
  }
}

The field is the data you want to group by ranges.

Each range can have a from (start) and/or to (end) value.

Examples
This example groups products by price: less than 50, between 50 and 100, and more than 100.
Elasticsearch
{
  "aggs": {
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "to": 50 },
          { "from": 50, "to": 100 },
          { "from": 100 }
        ]
      }
    }
  }
}
This example groups users by age ranges: under 18, 18-30, 30-50, and over 50.
Elasticsearch
{
  "aggs": {
    "age_groups": {
      "range": {
        "field": "age",
        "ranges": [
          { "to": 18 },
          { "from": 18, "to": 30 },
          { "from": 30, "to": 50 },
          { "from": 50 }
        ]
      }
    }
  }
}
Sample Program

This query counts how many documents have a price less than 50, between 50 and 100, and greater than 100.

Elasticsearch
{
  "size": 0,
  "aggs": {
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "to": 50 },
          { "from": 50, "to": 100 },
          { "from": 100 }
        ]
      }
    }
  }
}
OutputSuccess
Important Notes

Ranges are inclusive of from and exclusive of to values.

If you omit from, the range starts from the smallest value.

If you omit to, the range goes up to the largest value.

Summary

Range buckets group data into number or date ranges.

Use from and to to define each range.

They help summarize data by showing counts in each range.