Searching with Query Strings: Bool query

Published on November 12, 2016 by

Now that you have seen how to search all or specific fields, let’s take a look at how we can embed boolean logic into the query string.

Let’s search the name field as we did in the previous article, but this time add parenthesis. Within the parenthesis, we will add the pasta term, followed by a boolean operator. In this example, we will use AND, and we will add the term spaghetti afterwards. This query searches for products that contain both the terms pasta and spaghetti in the name.

GET /ecommerce/product/_search?q=name:(pasta AND spaghetti)

This only yields a single result. If we change the boolean operator to or, then we will get more results.

GET /ecommerce/product/_search?q=name:(pasta OR spaghetti)

It is also possible to make more complex logic by simply adding more boolean operators within the parenthesis. Let’s try another example where we include multiple fields. Say, for instance, that we want to find the active products that contain pasta or spaghetti in their name.

GET /ecommerce/product/_search?q=(name:(pasta OR spaghetti) AND status:active)

As you can see, this allows for quite powerful searches.

You can also use boolean operators within the query string itself for even more control. Prefixing a term with a + sign means that the term must be present, while prefixing a term with a sign means that it must not be present. Any terms without a prefix in such a query are optional. This is similar to how you can do in Google’s search. Let’s take a look at a quick example. We will say that the term pasta must be present, and the term spaghetti must not be present.

GET /ecommerce/_search?q=name:+pasta -spaghetti

Inspecting the search results, we will see that the product named Pasta – Spaghetti is no longer returned.

Featured

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.