Medium search elasticsearch

How do you structure a bool query with must, should, filter and must_not?

The 30 second answer

Anything that should affect ranking, like the shopper's words, goes in must or should. Hard yes-or-no conditions such as market, category, size and stock go in filter, because filters skip scoring and can be cached. Exclusions go in must_not. Should clauses are optional boosts unless there is no must or filter, in which case one must match; minimum_should_match makes that explicit.

Could you say this in an interview?

The basic idea. A bool query combines other queries. It has four slots, and each one changes two things: whether a document has to match, and whether the clause adds to the relevance score.

SlotMust match?Adds to score?Cacheable?
mustyesyesno
shouldit depends (see below)yesno
filteryesnoyes, considered for caching
must_notmust not matchnoyes, considered for caching

The docs say filter clauses run in filter context, "meaning that scoring is ignored and clauses are considered for caching", and must_not clauses also run in filter context.

**The should rule that trips people up.** The docs: if the bool query "includes at least one should clause and no must or filter clauses, the default value is 1. Otherwise, the default value is 0." So the same should clause is required in one query and only a ranking boost in another. When an interviewer asks "will this return products that match none of the should clauses?", the answer depends on the other slots. Setting minimum_should_match explicitly removes the doubt.

Badly written. Everything is in must, so Elasticsearch scores the market and stock checks and can't cache them:

GET products/_search
{ "query": { "bool": { "must": [
    { "match": { "name": "black leather boots" } },
    { "term":  { "market": "de" } },
    { "term":  { "in_stock": true } },
    { "range": { "price": { "lte": 15000 } } }
]}}}

Better. Text in must, hard conditions in filter, a brand boost in should, an exclusion in must_not:

GET products/_search
{ "query": { "bool": {
    "must":     [ { "match": { "name": { "query": "black leather boots", "operator": "and" } } } ],
    "filter":   [ { "term": { "market": "de" } },
                  { "term": { "in_stock": true } },
                  { "range": { "price": { "lte": 15000 } } } ],
    "should":   [ { "term": { "brand.raw": { "value": "Dr. Martens", "boost": 2 } } } ],
    "must_not": [ { "term": { "category_id": "kids" } } ]
}}}

Because there is a must and a filter, the should clause is optional here: products from other brands still match, Dr. Martens just ranks higher.

Trade-offs to say out loud.

  • Moving a clause to filter removes it from the score. If a condition should influence ranking (for example "prefer in-stock but still show out-of-stock"), it belongs in should, not filter.
  • minimum_should_match on a list of optional terms is a precision and recall dial: higher means fewer, more precise results.
  • The same structure nests: a should of several bool queries is how you express "match this group of conditions or that one".

Alternate interview scenarios

"A product team added an 'on sale' should clause next to the text match, and now unrelated sale items appear for every search. Why?"

The query had only should clauses and no must or filter, so the default minimum_should_match was 1: a document matching just the sale clause qualifies, even without any of the shopper's words. Move the text match to must so the sale clause becomes a pure ranking boost.

"Shoppers type five words and get almost nothing back with operator and. How do you relax it?"

Use minimum_should_match on the match query, for example "75%" or "3<75%", so most but not all words must match. Then check with a judgment set that precision didn't fall too far.

Sources (3)
  1. Elasticsearch docs: Boolean queryelastic.co
  2. Elasticsearch docs: minimum_should_match parameterelastic.co
  3. Elasticsearch docs: Query and filter contextelastic.co