How to Use must_not in Bool Query in Elasticsearch
In Elasticsearch, use the
must_not clause inside a bool query to exclude documents that match certain criteria. It works by filtering out documents that meet the conditions specified in must_not, while other clauses like must or should include documents.Syntax
The must_not clause is part of the bool query in Elasticsearch. It specifies conditions that documents must NOT match to be included in the results.
The main parts are:
bool: Combines multiple query clauses.must_not: Contains one or more queries that exclude matching documents.- Other clauses like
mustandshouldcan be used alongside.
json
{
"query": {
"bool": {
"must_not": [
{ "term": { "field": "value_to_exclude" } }
]
}
}
}Example
This example shows how to find documents where the field status is NOT inactive. It excludes all documents with status equal to inactive.
json
{
"query": {
"bool": {
"must_not": [
{ "term": { "status": "inactive" } }
]
}
}
}Output
{
"hits": {
"total": 3,
"hits": [
{"_source": {"status": "active", "name": "Alice"}},
{"_source": {"status": "pending", "name": "Bob"}},
{"_source": {"status": "active", "name": "Carol"}}
]
}
}
Common Pitfalls
Common mistakes when using must_not include:
- Using
must_notalone without other clauses may return all documents except those excluded, which might be unexpected. - Not wrapping multiple conditions inside an array in
must_not. - Confusing
must_notwithfilterormustclauses.
Always remember must_not excludes documents matching its queries.
json
{
"query": {
"bool": {
"must_not": {
"term": { "status": "inactive" }
}
}
}
}
// Correct usage with array:
{
"query": {
"bool": {
"must_not": [
{ "term": { "status": "inactive" } }
]
}
}
}Quick Reference
Use must_not inside bool queries to exclude documents matching specific conditions. Combine with must to require conditions and should to boost relevance.
- must: Documents must match these queries.
- must_not: Documents must NOT match these queries.
- should: Documents matching these queries are scored higher.
- filter: Like must but does not affect scoring.
Key Takeaways
Use must_not inside bool queries to exclude documents matching specific criteria.
must_not expects an array of queries to exclude matching documents.
Combine must_not with must and should for precise query control.
Not using an array for must_not queries can cause errors or unexpected results.
must_not filters out documents but does not contribute to scoring.