﻿---
title: Filter aggregation
description: A single bucket aggregation that narrows the set of documents to those that match a query. Example: The previous example calculates the average price...
url: https://www.elastic.co/elastic/docs-builder/docs/3016/reference/aggregations/search-aggregations-bucket-filter-aggregation
products:
  - Elasticsearch
---

# Filter aggregation
A single bucket aggregation that narrows the set of documents to those that match a [query](https://www.elastic.co/elastic/docs-builder/docs/3016/reference/query-languages/querydsl).
Example:

```json

{
  "aggs": {
    "avg_price": { "avg": { "field": "price" } },
    "t_shirts": {
      "filter": { "term": { "type": "t-shirt" } },
      "aggs": {
        "avg_price": { "avg": { "field": "price" } }
      }
    }
  }
}
```

The previous example calculates the average price of all sales as well as the average price of all T-shirt sales.
Response:
```json
{
  "aggregations": {
    "avg_price": { "value": 140.71428571428572 },
    "t_shirts": {
      "doc_count": 3,
      "avg_price": { "value": 128.33333333333334 }
    }
  }
}
```


## Use a top-level `query` to limit all aggregations

To limit the documents on which all aggregations in a search run, use a top-level `query`. This is faster than a single `filter` aggregation with sub-aggregations.
For example, use this:

```json

{
  "query": { "term": { "type": "t-shirt" } },
  "aggs": {
    "avg_price": { "avg": { "field": "price" } }
  }
}
```

Instead of this:

```json

{
  "aggs": {
    "t_shirts": {
      "filter": { "term": { "type": "t-shirt" } },
      "aggs": {
        "avg_price": { "avg": { "field": "price" } }
      }
    }
  }
}
```


## Use the `filters` aggregation for multiple filters

To group documents using multiple filters, use the [`filters` aggregation](https://www.elastic.co/elastic/docs-builder/docs/3016/reference/aggregations/search-aggregations-bucket-filters-aggregation). This is faster than multiple `filter` aggregations.
For example, use this:

```json

{
  "aggs": {
    "f": {
      "filters": {
        "filters": {
          "hats": { "term": { "type": "hat" } },
          "t_shirts": { "term": { "type": "t-shirt" } }
        }
      },
      "aggs": {
        "avg_price": { "avg": { "field": "price" } }
      }
    }
  }
}
```

Instead of this:

```json

{
  "aggs": {
    "hats": {
      "filter": { "term": { "type": "hat" } },
      "aggs": {
        "avg_price": { "avg": { "field": "price" } }
      }
    },
    "t_shirts": {
      "filter": { "term": { "type": "t-shirt" } },
      "aggs": {
        "avg_price": { "avg": { "field": "price" } }
      }
    }
  }
}
```