Explain Bool Query in ElasticSearch.
A query that matches documents matching boolean combinations of other queries is called Bool Query. It is built using one or more boolean clauses, each clause with a typed occurrence.
- must: The clause (query) must appear in matching documents and will contribute to the score.
- filter: The clause (query) must appear in matching documents. However unlike must the score of the query will be ignored. Filter clauses are executed in filter context, meaning that scoring is ignored and clauses are considered for caching.
- should: The clause (query) should appear in the matching document.
- must_not: The clause (query) must not appear in the matching documents. Clauses are executed in filter context meaning that scoring is ignored and clauses are considered for caching. Because scoring is ignored, a score of 0 for all documents is returned.
What is the difference between MUST and SHOULD bool query?
must means: The clause (query) must appear in matching documents. These clauses must match, like logical AND.
should means: At least one of these clauses must match, like logical OR.
In other words, results will have to be matched by all the queries present in the must clause or match at least one of the should clauses if there is no must clause.
What is the difference between MUST and FILTER bool query?
The must contributes to the score. In filter, the score of the query is ignored.
In both must and filter, the clause(query) must appear in matching documents. This is the reason for getting same result.
Examples:
To get list of all the bank accounts, execute:
GET bank/account/_search
To get all the bank acconuts from California (State will be CA):
GET bank/account/_search
{
"query": {
"match": {"state": "CA"}
}
}
To get all the bank acconuts of Techade from California (State will be CA)
GET bank/account/_search
{
"query": {
"bool": {
"must": [
{ "match": {"state": "CA"} },
{ "match": {"employer": "Techade"}}
]
}
}
}
To get all the bank acconuts not from Techade and outside California (State will be CA)
GET bank/account/_search
{
"query": {
"bool": {
"must_not": [
{ "match": {"state": "CA"} },
{ "match": {"employer": "Techade"}}
]
}
}
}
-K Himaanshu Shuklaa..