9
votes

I'm a newbie in elasticsearch, so my question is:

There are 3 sections in bool filter:

must
    All of these clauses must match. The equivalent of AND. 
must_not
    All of these clauses must not match. The equivalent of NOT. 
should
    At least one of these clauses must match. The equivalent of OR. 

How do I perform a "should_not" query?

Thanks in advance :)

4
please explain your definition of 'should_not'Richa

4 Answers

21
votes

In order to get something like "should_not" please try the following query:

GET /bank/account/_search
{
   "size": 2000,
   "query": {
      "bool": {
          "must": {
             "match_all": {}
          }, 
         "should": {
            "bool": {
               "must_not": {
                  "match": {
                     "city": "XYZ"
                  }
               }
            }
         }
      }
   }
}

In this case the clause "must" is required to retrieve the all results (the result with the city "XYZ" too) but with decreased score for this specific one.

7
votes

That depends on how exactly you are wishing a "should_not" to function.

Since should is roughly equivalent to a boolean OR (i.e. return documents where A or B or C is true), then one way to think of "should_not" would be roughly equivalent to NOT (A OR B OR C). In boolean logic, this is the same as NOT A AND NOT B AND NOT C. In this case, "should_not" behavior would be accomplished by simply adding all your clauses to the must_not section of the bool filter.

2
votes

This query similar to sql where categoryId= "category123" AND (localeId != "de_DE" OR productId != "productMediatest-productid01")

{
  "query": {
   "bool": {
  "must": [
    {
      "term": {
        "categoryId": "category123"
      }
    },
    {
      "bool": {
        "should": [
          {
            "bool": {
              "must_not": {
                "term": {
                  "localeId": "de_DE"
                }
              }
            }
          },
          {
            "bool": {
              "must_not": {
                "term": {
                  "productId": "productMediatest-productid01"
                }
              }
            }
          }
        ]
      }
    }
  ]
}
}
}
0
votes

You could apply a not filter and then a should filter for should_not operation.

  "filter": {
       "not": {
          "filter": {
              "bool": {
                  "should": [
                     {}
                  ]
              }
          }
       }
   }