0
0
ElasticsearchHow-ToBeginner · 3 min read

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.
  • term or 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 query instead of filter inside the aggregation, which is invalid.
  • Not using keyword fields for exact matches, causing no results.
  • Expecting filter aggregation 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

PartDescription
filterDefines the condition to select documents
termExact match condition inside filter
aggsSub-aggregations on filtered documents
doc_countNumber 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.