What is the difference between must and filter in Query DSL in elasticsearch?
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 results.
You may check this link
Score
The relevance score of each document is represented by a positive floating-point number called the
_score
. The higher the_score
, the more relevant the document.
A query clause generates a _score
for each document.
To know how score is calculated, refer this link
Comments
-
Krash almost 2 years
I am new to elastic search and I am confused between must and filter. I want to perform an and operation between my terms, so I did this
POST /xyz/_search
{ "query": { "bool": { "must": [ { "term": { "city": "city1" } }, { "term": { "saleType": "sale_type1" } } ] } } }
which gave me the required results matching both the terms, and on using filter like this
POST /xyz/_search
{ "query": { "bool": { "must": [ { "term": { "city": "city1" } } ], "filter": { "term": { "saleType": "sale_type1" } } } } }
I get the same result, so when should I use must and when should I use filter? What is the difference?
-
intiha over 5 yearsdoesnt really answer when the must vs filter will be used. As in when is having a score important for anything>?
-
Cardin about 5 years@intiha Use
filter
for faster searches, because there is no score to compute and no ranking to be done. Scoring becomes important when you care about say, the relevance due to no. of occurrences of your search term, the length of your matched document, or if you want to addboost
to your query to uprank matching documents. -
Paul about 5 years@intiha Score is not important if all your queries are boolean. Clauses used in filters may be cached: "Filter clauses are executed in filter context, meaning that scoring is ignored and clauses are considered for caching." Ref: elastic.co/guide/en/elasticsearch/reference/current/…
-
moon about 3 yearsI think it also matters when you have a compound query where the score of inner query is used to calculate overall score. Same for
must_not
.