Elasticsearch & Lucene (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
How does the Bool Query work with must, filter, should, and must_not clauses?
senior LevelCode ExampleSystem Design
In Simple Words: The Bool query is the primary compound query in Elasticsearch:
must: Clause must appear in matching documents. Contributes to the relevance_score.filter: Clause must appear in matching documents, but does not compute relevance scores and results are automatically cached in memory. Always use for boolean/range/keyword filters!should: Acts as anORcondition. If matching, boosts the document's_score.must_not: Acts as aNOTcondition; documents matching this clause are strictly excluded (cached, no scoring).
json
{
"query": {
"bool": {
"must": [{ "match": { "description": "distributed database" } }],
"filter": [
{ "term": { "category": "engineering" } },
{ "range": { "price": { "lte": 100 } } }
],
"should": [{ "match": { "featured": true } }],
"must_not": [{ "term": { "status": "archived" } }]
}
}
}