A bool query helps you combine many search rules together. It lets you say what must happen, what should happen, and what must not happen in your search.
Bool query in depth in Elasticsearch
{
"bool": {
"must": [ /* queries that must match */ ],
"filter": [ /* queries that filter results but don't affect score */ ],
"should": [ /* queries that should match to boost score */ ],
"must_not": [ /* queries that must NOT match */ ]
}
}must means all these queries have to match.
filter is like must but faster and does not change score.
{
"bool": {
"must": [
{ "match": { "title": "apple" } }
]
}
}{
"bool": {
"must": [
{ "match": { "title": "apple" } }
],
"must_not": [
{ "term": { "status": "sold" } }
]
}
}{
"bool": {
"should": [
{ "match": { "description": "fresh" } },
{ "match": { "description": "organic" } }
],
"minimum_should_match": 1
}
}{
"bool": {
"filter": [
{ "range": { "price": { "gte": 10, "lte": 50 } } }
]
}
}This query finds documents that have "coffee" in the title and "fresh" in the description. It only includes items priced between 5 and 20. It excludes items with status "sold". If the brand is "acme", the document scores higher but it is not required.
{
"query": {
"bool": {
"must": [
{ "match": { "title": "coffee" } },
{ "match": { "description": "fresh" } }
],
"filter": [
{ "range": { "price": { "gte": 5, "lte": 20 } } }
],
"must_not": [
{ "term": { "status": "sold" } }
],
"should": [
{ "match": { "brand": "acme" } }
],
"minimum_should_match": 0
}
}
}You can use minimum_should_match to say how many should queries must match.
filter clauses are cached and faster for repeated queries.
Use must_not to exclude unwanted results.
A bool query combines many queries with rules: must, should, filter, and must_not.
Use must for required matches, filter for fast filtering, should for optional boosts, and must_not to exclude.
Bool queries help build powerful and flexible searches in Elasticsearch.