How to Use Bool Query in Elasticsearch: Syntax and Examples
Use the
bool query in Elasticsearch to combine multiple queries with logical operators like must (AND), should (OR), must_not (NOT), and filter (filtering without scoring). It lets you build complex search conditions by grouping queries inside these clauses.Syntax
The bool query has four main parts:
- must: Queries that must match (AND logic).
- should: Queries that should match (OR logic, at least one).
- must_not: Queries that must NOT match (NOT logic).
- filter: Queries that filter results without affecting score.
Each part takes an array of queries to combine.
json
{
"query": {
"bool": {
"must": [
{ "match": { "field1": "value1" } }
],
"should": [
{ "term": { "field2": "value2" } },
{ "range": { "field3": { "gte": 10 } } }
],
"must_not": [
{ "term": { "field4": "value3" } }
],
"filter": [
{ "term": { "field5": "value4" } }
]
}
}
}Example
This example searches for documents where title must contain "Elasticsearch", status should be "published" or views greater than 100, excludes documents with author "admin", and filters to only include category "tech".
json
{
"query": {
"bool": {
"must": [
{ "match": { "title": "Elasticsearch" } }
],
"should": [
{ "term": { "status": "published" } },
{ "range": { "views": { "gt": 100 } } }
],
"must_not": [
{ "term": { "author": "admin" } }
],
"filter": [
{ "term": { "category": "tech" } }
]
}
}
}Output
{"hits":{"total":{"value":2,"relation":"eq"},"hits":[{"_id":"1","_source":{"title":"Elasticsearch Basics","status":"published","views":150,"author":"user1","category":"tech"}},{"_id":"3","_source":{"title":"Advanced Elasticsearch","status":"draft","views":200,"author":"user2","category":"tech"}}]}}
Common Pitfalls
Common mistakes when using bool query include:
- Using
shouldwithoutmustor settingminimum_should_match, which may return unexpected results. - Confusing
filterandmust:filterdoes not affect scoring butmustdoes. - Not wrapping queries properly inside arrays.
json
{
"query": {
"bool": {
"should": {
"term": { "status": "published" }
}
}
}
}
// Correct way:
{
"query": {
"bool": {
"should": [
{ "term": { "status": "published" } }
],
"minimum_should_match": 1
}
}
}Quick Reference
| Clause | Purpose | Effect on Scoring |
|---|---|---|
| must | Queries that must match (AND) | Affects scoring |
| should | Queries that should match (OR) | Affects scoring |
| must_not | Queries that must NOT match (NOT) | No scoring |
| filter | Filters results without scoring | No scoring |
Key Takeaways
Use
bool query to combine multiple queries with logical operators.must means AND, should means OR, must_not means NOT, and filter filters without scoring.Always wrap queries inside arrays and set
minimum_should_match when using should alone.filter clauses improve performance by caching and do not affect relevance scores.