0
0
Elasticsearchquery~5 mins

Bool query (must, should, must_not, filter) in Elasticsearch

Choose your learning style9 modes available
Introduction

A bool query helps you combine many search rules in Elasticsearch. It lets you say what must happen, what should happen, what must not happen, and what to filter.

You want to find documents that match several conditions at the same time.
You want to boost results that match some extra conditions but not require them.
You want to exclude documents that have certain values.
You want to filter results without affecting their score.
Syntax
Elasticsearch
{
  "bool": {
    "must": [ { /* conditions that must match */ } ],
    "should": [ { /* conditions that should match */ } ],
    "must_not": [ { /* conditions that must NOT match */ } ],
    "filter": [ { /* conditions to filter without scoring */ } ]
  }
}

Each part (must, should, must_not, filter) takes an array of queries.

Must means all these queries have to match.

Examples
Find documents where the title contains "apple".
Elasticsearch
{
  "bool": {
    "must": [ { "match": { "title": "apple" } } ]
  }
}
Prefer documents with color red or green, but not required.
Elasticsearch
{
  "bool": {
    "should": [ { "term": { "color": "red" } }, { "term": { "color": "green" } } ]
  }
}
Exclude documents where status is sold.
Elasticsearch
{
  "bool": {
    "must_not": [ { "term": { "status": "sold" } } ]
  }
}
Only include documents with price less or equal to 100, without changing score.
Elasticsearch
{
  "bool": {
    "filter": [ { "range": { "price": { "lte": 100 } } } ]
  }
}
Sample Program

This query finds documents that must mention "fresh fruit" in description, should be red or green color, must not be expired, and price must be 50 or less.

Elasticsearch
{
  "query": {
    "bool": {
      "must": [
        { "match": { "description": "fresh fruit" } }
      ],
      "should": [
        { "term": { "color": "red" } },
        { "term": { "color": "green" } }
      ],
      "must_not": [
        { "term": { "status": "expired" } }
      ],
      "filter": [
        { "range": { "price": { "lte": 50 } } }
      ]
    }
  }
}
OutputSuccess
Important Notes

Use must for required matches that affect scoring.

Use filter for conditions that don't affect scoring but limit results.

should clauses boost relevance if matched but are optional unless combined with minimum_should_match.

Summary

Bool query combines multiple conditions with must, should, must_not, and filter.

Must means required, should means optional but preferred, must_not excludes, filter limits without scoring.

This helps build flexible and powerful search queries in Elasticsearch.