Compound queries let you search using many rules at once. This helps find exactly what you want by mixing conditions.
Why compound queries combine conditions in 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.
{
"bool": {
"must": [
{ "match": { "title": "apple" } },
{ "range": { "price": { "gte": 10 } } }
]
}
}{
"bool": {
"should": [
{ "term": { "color": "red" } },
{ "term": { "color": "blue" } }
],
"minimum_should_match": 1
}
}{
"bool": {
"must": [ { "match": { "category": "fruit" } } ],
"must_not": [ { "term": { "status": "sold_out" } } ]
}
}This query finds items described as fresh, priced 20 or less, not expired, and prefers those with a discount.
{
"query": {
"bool": {
"must": [
{ "match": { "description": "fresh" } },
{ "range": { "price": { "lte": 20 } } }
],
"must_not": [
{ "term": { "status": "expired" } }
],
"should": [
{ "term": { "discount": true } }
],
"minimum_should_match": 0
}
}
}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.
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.