Filtering Results

Published on November 12, 2016 by

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.


Learn Elasticsearch today!

Take an online course and become an Elasticsearch champion!

Here is what you will learn:

  • The architecture of Elasticsearch
  • Mappings and analyzers
  • Many kinds of search queries (simple and advanced alike)
  • Aggregations, stemming, auto-completion, pagination, filters, fuzzy searches, etc.
  • ... and much more!
Elasticsearch logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.