0
0
ElasticsearchHow-ToBeginner · 3 min read

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 must can 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 must with queries that do not match any documents, resulting in empty results.
  • Confusing must with should: must requires all conditions to match, while should means 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 queries
📊

Quick Reference

ClauseDescriptionUsage
mustAll queries inside must must matchUse for required conditions
shouldAt least one query should matchUse for optional conditions
must_notQueries must not matchUse to exclude documents
filterQueries that filter without affecting scoreUse 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.