How to Use Terms Aggregation in Elasticsearch
Use the
terms aggregation in Elasticsearch to group documents by unique values of a field and count how many documents fall into each group. It is defined inside the aggs section of a search query and returns buckets with keys and counts.Syntax
The terms aggregation groups documents by unique values of a specified field. It is placed inside the aggs part of the query. You specify the field to group by and optionally size to limit the number of buckets returned.
- field: The field to group by (e.g.,
user.keyword). - size: Maximum number of unique terms to return.
- order: How to sort buckets (e.g., by count or key).
json
{
"aggs": {
"group_by_field": {
"terms": {
"field": "field_name",
"size": 10,
"order": {"_count": "desc"}
}
}
}
}Example
This example groups documents by the category.keyword field and returns the top 5 categories with their document counts.
json
{
"size": 0,
"aggs": {
"top_categories": {
"terms": {
"field": "category.keyword",
"size": 5
}
}
}
}Output
{
"aggregations": {
"top_categories": {
"buckets": [
{"key": "electronics", "doc_count": 120},
{"key": "books", "doc_count": 80},
{"key": "clothing", "doc_count": 50},
{"key": "toys", "doc_count": 30},
{"key": "furniture", "doc_count": 20}
]
}
}
}
Common Pitfalls
- Not using a keyword or exact field type for
termsaggregation causes unexpected results because text fields are analyzed. - For large cardinality fields,
termsaggregation can be slow or incomplete without tuningsizeor usingcompositeaggregation. - For nested or object fields, you must use nested aggregations properly.
json
{
"aggs": {
"wrong_usage": {
"terms": {
"field": "description"
}
}
}
}
// Correct usage:
{
"aggs": {
"correct_usage": {
"terms": {
"field": "description.keyword"
}
}
}
}Quick Reference
| Parameter | Description | Example |
|---|---|---|
| field | Field to group by | "category.keyword" |
| size | Max number of buckets | 5 |
| order | Sort buckets by count or key | {"_count": "desc"} |
| min_doc_count | Minimum documents per bucket | 1 |
Key Takeaways
Use
terms aggregation to group documents by unique field values and count them.Always use keyword or exact fields for
terms aggregation to avoid analyzed text issues.Limit bucket size with
size to control result size and performance.Check for nested fields and use nested aggregations if needed.
Sort buckets using
order to get meaningful results.