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).
The shortcut
Sort each condition in the request into "deal-breaker" or "bonus". Deal-breakers go in must; bonuses go in should. If there are no deal-breakers at all, should becomes "match at least one".
Deal-breaker
"about code" →
must: matchtitlewithcode.
Drills
Answer fast — trust the rule.
A bool has one must and two should clauses. A document matches the must but neither should. Is it returned?
A bool contains only two should clauses. What must a document do to be returned?
Which clause both requires a match and adds to the score?
You want recent books to rank higher without hiding older ones. Where does the date range go?
Remember
- must is required and scored; should is optional and adds score.
- Deal-breakers → must; bonuses → should.
- With no must or filter, at least one should must match.
