Save 50% on my Elasticsearch course

Filtering Results

This entry is part 31 of 35 in the series Complete Guide to Elasticsearch

This article explains how to filter results.

Remember that there are two query contexts; the query context and filter context. Queries that are in query context affect the relevance scores of documents depending on how well they match, while queries in a filter context do not affect relevance scores. Therefore, filter queries can be used to exclude documents from the results if they do not satisfy the filter queries. For the documents that will be excluded, it doesn’t make sense to calculate a relevance score, so Elasticsearch automatically detects this and optimizes the execution of the query to avoid this.

As always, let’s go through an example. I will show a query that matches the term pasta for the name field as we have done before, only this time I will add a filter query that filters out products with a quantity that is not between 10 and 15.

GET /ecommerce/product/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "name": "pasta" } }
      ],
      "filter": [
        {
          "range": {
            "quantity": {
              "gte": 10,
              "lte": 15
            }
          }
        }
      ]
    }
  }
}

In this example, I used a range query as a filter query, but I could just as well have used another query type. If I run this query, you can see that only documents with a quantity of between 10 and 15 match.

Now that you know how to filter out documents, it’s time to move on to changing the number of documents that are returned for a given query.

Series Navigation<< BoostingChanging the Size of Result Sets >>

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *