ElasticSearch Query vs Filters

Query or Filter

Throughout the ElasticSearch API you will see parameters with query or filter in the name, sometimes it’s confusing when you should use query, when to use filter, or when you want to combine queries with filters.

When to use queries?

  • Full text search
  • Where the search result depends on score

When to use filters?

  • For binary yes/no search
  • For exact match

Depending on the filter type, some are cached by default, some are not. When cached, filters perform much better than plain query search.

When to combine query and filter

Let’s say user wants to search for a music title “ballade No. 1” with author as Chopin

{ "match": { "title": "ballade No. 1" }}

We can then apply the term filter, which only match documents when author is Chopin

{ "term": { "author": "chopin" }}

We can then wrap the query and filter into filtered query:

GET /_search
{
 "query": {
    "filtered": {
         "query": { "match": { "title": "ballade No. 1" }},
         "filter": { "term": { "author": "chopin" }}
     }
  }
}

By the way, queries can be done using only query string parameters in the URL. For example. /_search?q=keyword. Filters cannot be done using a query string, you have to use a request-body

(Visited 31 times, 1 visits today)