Compound Queries
Compound queries combine multiple queries using boolean logic or modify their scoring behavior.
Bool Query
The most important compound query that combines multiple leaf or compound queries using boolean logic. Allows complex search criteria by defining what must, should, or must not match.
{
"query": {
"bool": {
"must": [
{"term": {"status": "published"}},
{"range": {"age": {"gte": 18}}}
],
"must_not": [
{"term": {"category": "spam"}}
],
"should": [
{"match": {"title": "important"}},
{"match": {"tags": "featured"}}
],
"filter": [
{"range": {"@timestamp": {"gte": "2024-01-01"}}}
],
"minimum_should_match": 1
}
}
}
Bool query clauses:
must- Documents MUST match these queries (contributes to scoring)filter- Documents MUST match these queries (no scoring, cached)should- Documents MAY match these queries (contributes to scoring)must_not- Documents MUST NOT match these queries
Parameters:
minimum_should_match- Minimum number of should clauses that must matchboost- ⚠️ Accepted but ignored
Performance Tips
- Use filters over queries when you don't need scoring
- Combine filters in bool queries for better caching
- Structure bool queries with filter context when possible
Common Pattern
{
"query": {
"bool": {
"filter": [
{"range": {"@timestamp": {"gte": "now-1h"}}},
{"term": {"environment": "production"}}
],
"must": [
{"match": {"message": "error"}}
]
}
}
}