Edison
Edison

Reputation: 1020

Elasicsearch: How to filter for documents outside a range?

I'm building an app that handles appointments for businesses and what I want to do is: When a customer says they want an appointment between a date range, I want to search for all businesses that don't have any appointments in that date range.

This is my ES index mapping:

settings = {
  "mappings": {
      "business_id": {"type": "text"},
      "appointments": {"type": "date"},
  }
}

This is an example index update:

{
  "business_id": 875787,
  "appointments": ["2022-01-01","2022-01-08","2022-01-12"],
}

This is how I can search for businesses that have any appointments within a date range:

body = {
        "size": 10,
        "from": 0,
        "query": {
                "range": {
                    "appointments": {
                        "lte": "2022-01-12", // end date
                        "gte": "2022-01-01", // start date
                     }
                }
         },
}

But, How can I search for businesses that don't have any appointments within that range? The alternative would be to search all businesses, then search those that have appointments within the range, and then filter out those that don't have appointments within the range but... I don't want to involve that much python due to performance reasons.

Upvotes: 0

Views: 73

Answers (1)

Edison
Edison

Reputation: 1020

I solved this by using the must_not keyword.

body={
      "size": 10,
      "from": 0,
      "query": {
          "bool": {
              "must_not": {
                   "range": {
                       "appointments": {
                            "lte": "2022-01-12",
                            "gte": "2022-01-01",
                        }
                    },
               },
           },
      },
}

Upvotes: 1

Related Questions