How to Use Must in Bool Query in Elasticsearch
In Elasticsearch, the
must clause inside a bool query specifies conditions that documents must satisfy to be included in results. Use must to combine multiple queries where all must match for a document to be returned.Syntax
The must clause is part of the bool query and accepts an array of query objects. Each query inside must must match for a document to be included in the results.
Structure:
bool: The container for boolean logic.must: An array of queries that all must match.- Each query inside
mustcan be any valid Elasticsearch query (e.g.,match,term).
json
{
"query": {
"bool": {
"must": [
{ "match": { "field1": "value1" } },
{ "term": { "field2": "value2" } }
]
}
}
}Example
This example searches for documents where the title field contains "Elasticsearch" and the status field exactly matches "published". Both conditions must be true for a document to appear in results.
json
{
"query": {
"bool": {
"must": [
{ "match": { "title": "Elasticsearch" } },
{ "term": { "status": "published" } }
]
}
}
}Output
{
"hits": {
"total": 2,
"hits": [
{"_id": "1", "_source": {"title": "Learn Elasticsearch", "status": "published"}},
{"_id": "3", "_source": {"title": "Elasticsearch Basics", "status": "published"}}
]
}
}
Common Pitfalls
Common mistakes when using must include:
- Using
mustwith queries that do not match any documents, resulting in empty results. - Confusing
mustwithshould:mustrequires all conditions to match, whileshouldmeans any condition can match. - Not wrapping multiple queries inside an array under
must.
json
{
"query": {
"bool": {
"must": {
"match": { "title": "Elasticsearch" }
}
}
}
}
// Wrong: must expects an array, not a single object
{
"query": {
"bool": {
"must": [
{ "match": { "title": "Elasticsearch" } }
]
}
}
}
// Correct: must is an array of queriesQuick Reference
| Clause | Description | Usage |
|---|---|---|
| must | All queries inside must must match | Use for required conditions |
| should | At least one query should match | Use for optional conditions |
| must_not | Queries must not match | Use to exclude documents |
| filter | Queries that filter without affecting score | Use for filtering |
Key Takeaways
Use the must clause inside bool query to require all conditions to match.
must expects an array of query objects, each must match for documents to be returned.
Do not confuse must with should; must requires all queries to match, should is optional.
Wrap multiple queries inside an array under must to avoid syntax errors.
Use must for combining multiple required search criteria in Elasticsearch.