0
0
Elasticsearchquery~5 mins

Bucket aggregations (terms, histogram) in Elasticsearch

Choose your learning style9 modes available
Introduction

Bucket aggregations group your data into categories or ranges so you can see patterns and counts easily.

You want to count how many documents have the same value in a field.
You want to group data by ranges of numbers, like ages or prices.
You want to see the most common terms in a text field.
You want to create charts that show data distribution by buckets.
You want to analyze data trends by grouping similar items together.
Syntax
Elasticsearch
{
  "aggs": {
    "NAME": {
      "terms": {
        "field": "FIELD_NAME",
        "size": NUMBER
      }
    }
  }
}

{
  "aggs": {
    "NAME": {
      "histogram": {
        "field": "FIELD_NAME",
        "interval": NUMBER
      }
    }
  }
}

Replace NAME with a name you choose for the aggregation.

For terms, size controls how many top terms to return.

Examples
This groups documents by the top 5 colors found in the color.keyword field.
Elasticsearch
{
  "aggs": {
    "popular_colors": {
      "terms": {
        "field": "color.keyword",
        "size": 5
      }
    }
  }
}
This groups documents into price buckets of size 50 (like 0-49, 50-99, etc.).
Elasticsearch
{
  "aggs": {
    "price_ranges": {
      "histogram": {
        "field": "price",
        "interval": 50
      }
    }
  }
}
Sample Program

This query does not return documents (size": 0) but returns two bucket aggregations: top 3 brands by count and age groups in intervals of 10 years.

Elasticsearch
{
  "size": 0,
  "aggs": {
    "top_brands": {
      "terms": {
        "field": "brand.keyword",
        "size": 3
      }
    },
    "age_groups": {
      "histogram": {
        "field": "age",
        "interval": 10
      }
    }
  }
}
OutputSuccess
Important Notes

Use .keyword fields for exact term matching in text fields.

Histogram buckets are numeric ranges starting at multiples of the interval.

Bucket aggregations help summarize large data sets quickly.

Summary

Bucket aggregations group data into categories or ranges.

terms aggregation groups by unique values and counts them.

histogram groups numeric data into fixed-size ranges.