How to Use Filter in Bool Query in Elasticsearch
In Elasticsearch, use the
filter clause inside a bool query to apply conditions that filter documents without affecting their relevance score. The filter is efficient because it caches results and does not calculate scores, making it ideal for exact matches or range conditions.Syntax
The bool query combines multiple query clauses. The filter clause inside it applies conditions that must be true but do not affect scoring.
- bool: The main container for combining queries.
- filter: An array of conditions that filter documents without scoring.
- Each filter can be a term, range, or other query type.
json
{
"query": {
"bool": {
"filter": [
{ "term": { "field": "value" } },
{ "range": { "field": { "gte": 10, "lte": 20 } } }
]
}
}
}Example
This example filters documents where the status is active and the age is between 30 and 40. It uses filter inside bool to efficiently find matching documents without scoring.
json
{
"query": {
"bool": {
"filter": [
{ "term": { "status": "active" } },
{ "range": { "age": { "gte": 30, "lte": 40 } } }
]
}
}
}Output
{
"hits": {
"total": {"value": 2, "relation": "eq"},
"hits": [
{"_source": {"status": "active", "age": 32}},
{"_source": {"status": "active", "age": 38}}
]
}
}
Common Pitfalls
Common mistakes when using filter in bool queries include:
- Using
mustinstead offilterwhen scoring is not needed, which slows queries. - Placing scoring queries inside
filter, which ignores scores. - Not using arrays for multiple filters, causing syntax errors.
Correct usage ensures fast filtering without scoring overhead.
json
{
"query": {
"bool": {
"must": [
{ "term": { "status": "active" } }
]
}
}
}
// Better to use filter for no scoring:
{
"query": {
"bool": {
"filter": [
{ "term": { "status": "active" } }
]
}
}
}Quick Reference
| Clause | Purpose | Effect on Scoring |
|---|---|---|
| must | Conditions that must match and affect scoring | Yes |
| filter | Conditions that must match but do not affect scoring | No |
| should | Optional conditions that affect scoring if matched | Yes |
| must_not | Conditions that must not match | No |
Key Takeaways
Use the filter clause inside bool queries to apply conditions without affecting scoring.
Filters are cached and faster for exact matches or ranges than must queries.
Always use arrays for multiple filter conditions inside the filter clause.
Avoid putting scoring queries inside filter because scores will be ignored.
Use must for queries where scoring matters, filter when it does not.