Elasticsearch Aggregations: How to Aggregate and Analyze Data
Fast recall
Quick revision
Core answer
Whether you understand the aggregation framework as a powerful analytics tool distinct from relational GROUP BY, and can describe the bucket-metric nesting pattern.
Running aggregations on text fields instead of keyword fields. Aggregations on analyzed text fields produce meaningless results because the values are tokenized terms, not the original strings.
Explain sub-aggregations -- nesting a metric aggregation inside a bucket aggregation to compute average price per category in a single request -- and how this compares to SQL GROUP BY with aggregate functions.
Interview-ready guide
Interview answer
Elasticsearch aggregations compute analytics over search results in the same request as the query — you get matching documents and computed metrics or buckets in one round trip.
Bucket aggregations — group documents
termsaggregation groups documents by a field's distinct values —agg: { by_status: { terms: { field: "status" } } }returns counts per status value; similar to SQL'sGROUP BY statusdate_histogramgroups documents into time buckets —{ calendar_interval: "month" }counts documents per month; the foundation of time-series charts and dashboardsrangegroups by a numeric range —{ ranges: [{ to: 100 }, { from: 100, to: 500 }, { from: 500 }] }distributes documents into price bands
Metric aggregations — compute values
avg,sum,min,max,stats(all five in one) compute aggregates over a numeric field —{ avg_price: { avg: { field: "price" } } }gives the mean price across matching documentscardinalityapproximates the number of distinct values using HyperLogLog — not exact, but accurate to within ~5% and far more efficient than fetching all values to count unique onespercentilescomputes the p50, p75, p95, p99 of a numeric field — essential for latency analysis
Sub-aggregations — nest to build complex analytics
- Aggregations can be nested —
date_histogramper month containing anavgmetric gives average price per month; this is how you build multi-dimensional analytics in one query - Each level of nesting runs within the context of its parent bucket — the
avg_pricewithin2024-01computes the average only for January documents
Aggregations run on data in shards without returning all matched documents — which means computing average order value across 100 million orders is fast; you get one number back, not 100 million documents.
Elasticsearch Aggregations: How to Aggregate and Analyze Data
Direct Answer
Elasticsearch aggregations compute analytics over search results in the same request as the query. There are three types: bucket aggregations group documents into buckets (terms, date_histogram, range); metric aggregations compute values over a bucket (avg, sum, min, max, cardinality); and pipeline aggregations compute from the output of other aggregations. Aggregations run over the same filtered dataset as the query, enabling faceted analytics.
Code Example
// Bucket + metric nested aggregation
// Get top 5 categories, with average price and total count in each
POST /products/_search
{
"size": 0,
"query": {
"bool": {
"filter": [{ "range": { "price": { "lte": 500 } } }]
}
},
"aggs": {
"by_category": {
"terms": {
"field": "category",
"size": 5
},
"aggs": {
"avg_price": {
"avg": { "field": "price" }
},
"price_ranges": {
"range": {
"field": "price",
"ranges": [
{ "to": 50 },
{ "from": 50, "to": 200 },
{ "from": 200 }
]
}
}
}
},
"monthly_sales": {
"date_histogram": {
"field": "created_at",
"calendar_interval": "month"
},
"aggs": {
"total_revenue": {
"sum": { "field": "price" }
}
}
}
}
}
// Java with Spring Data Elasticsearch
NativeQuery query = NativeQuery.builder()
.withQuery(q -> q.matchAll(m -> m))
.withAggregation("by_category",
Aggregation.of(a -> a
.terms(t -> t.field("category").size(5))))
.build();
SearchHits<ProductDocument> hits = ops.search(query, ProductDocument.class);
ElasticsearchAggregations aggregations = (ElasticsearchAggregations) hits.getAggregations();
Common Mistakes & Pitfalls
Running aggregations on text fields instead of keyword fields. Aggregations on analyzed text fields produce meaningless results because the values are tokenized terms, not the original strings.
Check your understanding
Answer these without looking back at the article.
- What is the difference between a terms aggregation and a cardinality aggregation?
- How do you compute a moving average over time-series data in Elasticsearch?
- Why does the terms aggregation return approximate counts and how can you improve accuracy?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.