0
0
Elasticsearchquery~5 mins

Why compound queries combine conditions in Elasticsearch

Choose your learning style9 modes available
Introduction

Compound queries let you search using many rules at once. This helps find exactly what you want by mixing conditions.

You want to find documents that match several rules together.
You need to include some results but exclude others.
You want to search for items that match one of many options.
You want to control how multiple conditions affect the search score.
You want to combine filters and queries for better performance.
Syntax
Elasticsearch
{
  "bool": {
    "must": [ { "condition1" }, { "condition2" } ],
    "should": [ { "condition3" } ],
    "must_not": [ { "condition4" } ],
    "filter": [ { "condition5" } ]
  }
}

The bool query is the main way to combine conditions.

must means all these conditions must match.

should means one or more of these should match.

must_not excludes matches.

filter applies conditions without affecting score.

Examples
Find documents where title has 'apple' and price is 10 or more.
Elasticsearch
{
  "bool": {
    "must": [
      { "match": { "title": "apple" } },
      { "range": { "price": { "gte": 10 } } }
    ]
  }
}
Find documents where color is either red or blue.
Elasticsearch
{
  "bool": {
    "should": [
      { "term": { "color": "red" } },
      { "term": { "color": "blue" } }
    ],
    "minimum_should_match": 1
  }
}
Find fruits that are not sold out.
Elasticsearch
{
  "bool": {
    "must": [ { "match": { "category": "fruit" } } ],
    "must_not": [ { "term": { "status": "sold_out" } } ]
  }
}
Sample Program

This query finds items described as fresh, priced 20 or less, not expired, and prefers those with a discount.

Elasticsearch
{
  "query": {
    "bool": {
      "must": [
        { "match": { "description": "fresh" } },
        { "range": { "price": { "lte": 20 } } }
      ],
      "must_not": [
        { "term": { "status": "expired" } }
      ],
      "should": [
        { "term": { "discount": true } }
      ],
      "minimum_should_match": 0
    }
  }
}
OutputSuccess
Important Notes

Compound queries help you mix many search rules easily.

Use filter for conditions that don't affect scoring but speed up search.

Remember to set minimum_should_match when using should clauses to control how many should match.

Summary

Compound queries combine multiple conditions to make searches precise.

The bool query is the main tool to combine must, should, must_not, and filter clauses.

Using compound queries helps find exactly what you want by mixing rules.