Search code examples
elasticsearch

What is the difference between MUST and SHOULD in an Elasticsearch bool query?


What is the difference between must and should in a bool query in Elasticsearch?

If I ONLY want results that contain my terms, should I then use must ?

For example, I have a query that should only contain certain values, and should also have no results that has a date/timestamp lower than today's (time/date - NOW). Also, can I use multiple filters inside a must query like the following code?

"filtered": {
"filter": {
"bool" : {
        "must" : {
            "term" : { "type" : 1 }
            "term" : { "totals" : 14 }
            "term" : { "groupId" : 3 }
            "range" : {
                "expires" : {
                    "gte": "now"
                }
            }
        },

Solution

  • 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.

    Basically they are used like logical operators AND and OR. See this.

    Now in a bool query:

    must means: Clauses that must match for the document to be included.

    should means: If these clauses match, they increase the _score; otherwise, they have no effect. They are simply used to refine the relevance score for each document.


    Yes you can use multiple filters inside must.