Elasticsearch Elasticsearch Post Filter

By Opster Team

Updated: Aug 24, 2023

| 1 min read

Quick Links

Introduction 

The Post Filter is primarily used in conjunction with aggregations. Aggregations in Elasticsearch provide a way to group and extract statistics from your data. However, there might be scenarios where you want to filter the search results after the aggregations have been calculated, otherwise the aggregations would be performed on a reduced document set which might not be what you want. This is where the Post Filter comes into play.

Use cases of Elasticsearch Post Filter

1. E-commerce Platforms: On e-commerce platforms, users often filter products based on various attributes like brand, price range, ratings, etc. In such cases, the Post Filter can be used to filter the search results after aggregating the product attributes.

2. Analytics Dashboards: In analytics dashboards, users might want to view aggregated data and then apply filters to the search results. The Post Filter can be used to filter the search results after the aggregations have been computed.

Implementing Elasticsearch Post Filter

Let’s consider an example where we have an e-commerce platform and we want to filter products based on their price range after aggregating the product attributes.

Here is a sample query that uses the Post Filter:

json
GET /products/_search
{
  "aggs": {
    "brands": {
      "terms": {
        "field": "brand.keyword"
      }
    }
  },
  "post_filter": {
    "range": {
      "price": {
        "gte": 50,
        "lte": 200
      }
    }
  }
}

In the above query, we are aggregating the products based on the brand and then using the Post Filter to filter the products whose price is between 50 and 200.

It’s important to note that the Post Filter does not affect the aggregations. The aggregations are computed on the entire search results and then the Post Filter is applied.

Performance considerations

While the Post Filter is a useful tool, it’s important to consider its impact on performance. Since the Post Filter operates after the aggregations have been computed, it can potentially slow down the search performance, especially when dealing with large amounts of data. Therefore, it’s recommended to use the Post Filter judiciously and only when necessary.