'Elasticsearch query MUST conditions with MUST NOT

Given a customer purchase order elasticsearch index, I want to query for records under ALL the following criteria

  • purchase_datetime field greater than a specified date.
  • product_name field in a wildcard search.
  • customer_id NOT equal to a list of ids.

Here is an example query that I've tried:

{"query": {
           "bool": {
                    "must": [
                             {"range": {"purchase_datetime": {"gte": "2022-01-01"}}},
                             {"wildcard": {"product_name": {"value": "*iphone*"}}}
                             ],
                    "must_not": [
                                 {"terms": {"customer_id":["id1", "id2"]}}
                                 ]
                    }
           }
}

I've tried variations of the above query and either I get "invalid query" or it doesn't seem to filter out customer_ids specified in the must_not query.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source