A Boolean, or bool, query combines smaller Elasticsearch queries into one search with compound criteria. Put leaf queries inside four clauses: must for required matches, must_not for exclusions, should for optional matches that improve relevance, and filter for required matches whose score is irrelevant. section 2.5.1 section 11.3
Listing 2.18 Format of a bool query with the expected clauses
GET books/_search
{
"query": {
"bool": { #1
"must": [{ }], #2
"must_not": [{ }], #3
"should": [{ }], #4
"filter": [{ }] #5
}
}
}
Use this skeleton when a search needs more than one condition. Each clause holds an array, so add one or more leaf queries such as match, term, or range queries. section 2.5.1 section 11.3.1
Think of the clauses as search logic. must acts like AND: every enclosed condition must match. must_not acts like NOT: matching documents are excluded. should supplies an optional condition that can raise a document’s relevance. filter also requires a match, but runs without changing relevance scores. section 11.3 section 11.8
Find TVs in a price range
To find TVs costing from 700 through 800, place a match query for the product and a range query for price in must. Both conditions must hold, so only TVs in that range are returned. GET products/_search { "query": { "bool": { "must": [ {"match": {"product": "TV"}}, {"range": {"price": {"gte": 700, "lte": 800}}} ] } } } section 11.3.3
Mix relevance with fixed constraints
A bookstore search can require an author, exclude low ratings, prefer a tag, and restrict publication date. Put the author in must, the rejected rating range in must_not, the preferred tag in should, and the date range in filter. The filter narrows results without altering their score. GET books/_search { "query": { "bool": { "must": [{"match": {"author": "Joshua"}}], "must_not": [{"range": {"amazon_rating": {"lt": 4.7}}}], "should": [{"match": {"tags": "Software"}}], "filter": [{"range": {"release_date": {"gte": "2015-01-01"}}}] } } } section 2.5.5 section 2.5.1
Use bool when one leaf query cannot express the requirement. Clauses can contain multiple term-level or full-text queries, and can also contain another compound query. Start with a single must condition, then add constraints or preferences one at a time and run the search to check the result set. section 8.7.4 section 11.3.1
Choose filter or must_not when scoring is unnecessary. Both execute in filter context; filter-context queries return binary matches rather than scores and can save score-calculation work. Use must and should when a matching condition should improve relevance. section 8.4.2 section 11.3.5
Reuse compound criteria for deletion
Bool logic is not limited to search. A _delete_by_query request can combine a director match, a rating exclusion, and a gross-earnings filter to select documents for deletion. Treat the same clauses carefully when the operation changes data. section 5.5.3
