0
0
Elasticsearchquery~5 mins

Filter aggregation in Elasticsearch

Choose your learning style9 modes available
Introduction

Filter aggregation helps you count or analyze only the data that matches certain rules. It lets you focus on a specific group inside your big data.

You want to count how many documents have a specific value in a field.
You need to find the average price of products only in a certain category.
You want to see how many users are from a particular country.
You want to analyze logs but only for errors with a certain status code.
Syntax
Elasticsearch
{
  "aggs": {
    "NAME": {
      "filter": {
        "TERM_OR_RANGE_QUERY"
      },
      "aggs": {
        "SUB_AGGREGATION": { ... }
      }
    }
  }
}

Replace NAME with a name you choose for this aggregation.

The filter part defines the rule to select documents.

Examples
This counts documents where the status field is exactly "error".
Elasticsearch
{
  "aggs": {
    "only_errors": {
      "filter": { "term": { "status": "error" } }
    }
  }
}
This filters products cheaper than 20 and calculates their average price.
Elasticsearch
{
  "aggs": {
    "cheap_products": {
      "filter": { "range": { "price": { "lt": 20 } } },
      "aggs": {
        "avg_price": { "avg": { "field": "price" } }
      }
    }
  }
}
Sample Program

This query finds users with status "active" and calculates their average age.

Elasticsearch
{
  "size": 0,
  "aggs": {
    "active_users": {
      "filter": {
        "term": { "status": "active" }
      },
      "aggs": {
        "average_age": {
          "avg": { "field": "age" }
        }
      }
    }
  }
}
OutputSuccess
Important Notes

The filter aggregation only counts documents matching the filter.

You can add sub-aggregations inside to calculate sums, averages, or other stats on the filtered data.

Summary

Filter aggregation selects documents matching a rule.

It helps analyze only a part of your data.

You can combine it with other aggregations for detailed insights.