What is the difference between must and filter in Query DSL in elasticsearch?

ElasticsearchFilterQuerydsl

Elasticsearch Problem Overview


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?

Elasticsearch Solutions


Solution 1 - 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKrashView Question on Stackoverflow
Solution 1 - ElasticsearchVijayView Answer on Stackoverflow