Skip to the workspace
Pebellslearn by building
Controlling Search Results  ›  Lesson

bool: must and should

must 12 minIn a bool query, must clauses are required and scored, while should clauses are optional bonuses unless there is no must or filter.

elasticsearch / bool: must and should

Explore each scene at your own pace.

01 · The rule

The rule

bool: must and should

A shopper searches "garden" and ticks "fiction". Another just wants garden books, "and ideally ones by Mira Das near the top". One query has two required conditions; the other has one required condition and one nice-to-have. The bool query's must and should clauses express exactly that difference.

The rule

must is required and scored; should is optional and adds score.

A bool query holds lists of other queries in named clauses. This lesson covers the two that affect relevance scores:

  • must — every query listed must match. Each one also adds to the document's _score, so better matches rank higher.
  • should — queries that may match. Each one that does adds to the score, pushing the document up the list.
GET /books/_search
{
  "query": {
    "bool": {
      "must":   [ { "match": { "title": "garden" } } ],
      "should": [ { "term":  { "author": "Mira Das" } } ]
    }
  }
}

Only The Quiet Garden contains the term garden (remember: "gardening" is a different term to the standard analyzer). It matches must, and being by Mira Das, it also collects the should bonus. A garden book by any other author would still appear, just lower down.

One rule changes everything: if a bool has no must or filter clause, at least one should must match. Then should behaves like OR:

{ "query": { "bool": { "should": [
  { "term": { "genre": "fiction" } },
  { "term": { "genre": "tech" } }
] } } }

This returns fiction books and tech books, and nothing else. You can demand more with "minimum_should_match": 2 (at least two should clauses must match).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.