ElasticSearch bool should_not filter ElasticSearch bool should_not filter elasticsearch elasticsearch

ElasticSearch bool should_not filter


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.


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.


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"                }              }            }          }        ]      }    }  ]}}}