How to Use Filter Aggregation in Elasticsearch
Use
filter aggregation in Elasticsearch to count or aggregate documents that match a specific condition. It applies a filter query and returns aggregated results only for documents that meet that filter.Syntax
The filter aggregation uses a filter query to select documents, then performs sub-aggregations on those filtered documents.
Key parts:
filter: The main aggregation type that applies a filter.termor other query: Defines the condition to filter documents.aggs: Optional sub-aggregations on filtered documents.
json
{
"aggs": {
"filtered_data": {
"filter": {
"term": { "field_name.keyword": "value" }
},
"aggs": {
"sub_aggregation_name": {
"terms": { "field": "another_field.keyword" }
}
}
}
}
}Example
This example counts how many documents have status equal to active and then groups those by category.
json
{
"size": 0,
"aggs": {
"active_filter": {
"filter": {
"term": { "status.keyword": "active" }
},
"aggs": {
"by_category": {
"terms": { "field": "category.keyword" }
}
}
}
}
}Output
{
"aggregations": {
"active_filter": {
"doc_count": 5,
"by_category": {
"buckets": [
{ "key": "books", "doc_count": 3 },
{ "key": "electronics", "doc_count": 2 }
]
}
}
}
}
Common Pitfalls
Common mistakes when using filter aggregation include:
- Using
queryinstead offilterinside the aggregation, which is invalid. - Not using keyword fields for exact matches, causing no results.
- Expecting
filteraggregation to return documents instead of aggregation results.
json
{
"aggs": {
"wrong_filter": {
"query": { "term": { "status": "active" } }
}
}
}
// Correct way:
{
"aggs": {
"correct_filter": {
"filter": { "term": { "status": "active" } }
}
}
}Quick Reference
| Part | Description |
|---|---|
| filter | Defines the condition to select documents |
| term | Exact match condition inside filter |
| aggs | Sub-aggregations on filtered documents |
| doc_count | Number of documents matching the filter |
Key Takeaways
Use filter aggregation to count or aggregate only documents matching a condition.
The filter uses a query like term, range, or bool to select documents.
Sub-aggregations inside filter run only on filtered documents.
Always use keyword fields for exact term matches in filters.
Filter aggregation returns aggregation results, not the documents themselves.