bool queries and filter context

Elasticsearch Course · lesson 9 of 19 · 6 min read

Combine clauses correctly, and stop paying for scores you are going to ignore.

Open this lesson in the learning hub

Key points

  • must and should run in query context: they match and they contribute to the score.
  • filter and must_not run in filter context - a yes or no test with no score computed.
  • Filter clauses can be cached in the node query cache, sized at 10 percent of heap by default.
  • That cache only holds segments with more than 10000 documents, so a tiny test index never shows a benefit.
  • minimum_should_match defaults to 1 if the bool has no must or filter, and to 0 otherwise.
  • Round dates in filters, since now-1d/d has a stable cache key and now-1d does not.

Example

GET /articles/_search
{
  "query": {
    "bool": {
      "must":     [ { "match": { "title": "elasticsearch" } } ],
      "filter":   [ { "term":  { "status": "published" } },
                    { "range": { "published_at": { "gte": "now-1y/d" } } } ],
      "must_not": [ { "term":  { "archived": true } } ],
      "should":   [ { "term":  { "tags": { "value": "tutorial", "boost": 2 } } } ]
    }
  }
}

Anything that decides membership rather than order belongs in filter, not must.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Elasticsearch Course course, and every lesson in it is listed on the Elasticsearch Course contents page.