Filter aggregation

Filter aggregation

A single bucket aggregation that narrows the set of documents to those that match a query.

Example:

  1. POST /sales/_search?size=0&filter_path=aggregations
  2. {
  3. "aggs": {
  4. "avg_price": { "avg": { "field": "price" } },
  5. "t_shirts": {
  6. "filter": { "term": { "type": "t-shirt" } },
  7. "aggs": {
  8. "avg_price": { "avg": { "field": "price" } }
  9. }
  10. }
  11. }
  12. }

The previous example calculates the average price of all sales as well as the average price of all T-shirt sales.

Response:

  1. {
  2. "aggregations": {
  3. "avg_price": { "value": 140.71428571428572 },
  4. "t_shirts": {
  5. "doc_count": 3,
  6. "avg_price": { "value": 128.33333333333334 }
  7. }
  8. }
  9. }

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:

  1. POST /sales/_search?size=0&filter_path=aggregations
  2. {
  3. "query": { "term": { "type": "t-shirt" } },
  4. "aggs": {
  5. "avg_price": { "avg": { "field": "price" } }
  6. }
  7. }

Instead of this:

  1. POST /sales/_search?size=0&filter_path=aggregations
  2. {
  3. "aggs": {
  4. "t_shirts": {
  5. "filter": { "term": { "type": "t-shirt" } },
  6. "aggs": {
  7. "avg_price": { "avg": { "field": "price" } }
  8. }
  9. }
  10. }
  11. }

Use the filters aggregation for multiple filters

To group documents using multiple filters, use the filters aggregation. This is faster than multiple filter aggregations.

For example, use this:

  1. POST /sales/_search?size=0&filter_path=aggregations
  2. {
  3. "aggs": {
  4. "f": {
  5. "filters": {
  6. "filters": {
  7. "hats": { "term": { "type": "hat" } },
  8. "t_shirts": { "term": { "type": "t-shirt" } }
  9. }
  10. },
  11. "aggs": {
  12. "avg_price": { "avg": { "field": "price" } }
  13. }
  14. }
  15. }
  16. }

Instead of this:

  1. POST /sales/_search?size=0&filter_path=aggregations
  2. {
  3. "aggs": {
  4. "hats": {
  5. "filter": { "term": { "type": "hat" } },
  6. "aggs": {
  7. "avg_price": { "avg": { "field": "price" } }
  8. }
  9. },
  10. "t_shirts": {
  11. "filter": { "term": { "type": "t-shirt" } },
  12. "aggs": {
  13. "avg_price": { "avg": { "field": "price" } }
  14. }
  15. }
  16. }
  17. }