'Excluding a Range in Elastic Search

I have a valid range and I'm trying to find documents that are outside of this range. The range query in elastic will return values within a certain range. I've tried putting the range query in a must_not, but that doesn't seem to be working for me or I'm using it incorrectly.

I'm prototyping at the moment, so I've set up an index with two records in it, for example:

{
    "name": "Alex",
    "value": 30.0
}

{
    "name": "James",
    "value": 36.5
}

my must_not block looks like this (note its in a bool because I'm checking some other fields in a must match_phrase which works fine):


{
  "query": {
    "bool": {
      "must_not": [
        {
          "range": {
            "value": {
            "lt": 31,
            "gt" : 36.6,
            }
          }
        }
      ]
    }
  }
}

I'd expect it to return nothing because 30 (Alex) is not less than 29 !(30 < 29) and 36.5 (James) is not less than !(36.5 > 36.6) but returns all records 😢

I'm new to Elastic so I might be looking at this the completely wrong way. Any help would be appreciated.



Solution 1:[1]

You cannot have a single range query for disjoint intervals, you need to have two, like this:

{
  "query": {
    "bool": {
      "must_not": [
        {
          "range": {
            "value": {
              "lt": 31
            }
          }
        },
        {
          "range": {
            "value": {
              "gt": 36.6
            }
          }
        }
      ]
    }
  }
}

Solution 2:[2]

try like this

POST i1/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "value": {
              "lt": 31,
              "gt": 36.6
            }
          }
        },
        {
          "match_phrase": {
            "k1": "something"
          }
        }
      ]
    }
  }
}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Val
Solution 2 caster