Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elasticsearch range filter for array field

I have a field containing an array of integers eg:

_source: {
  ...
  prices: [
    20001,
    30001
  ]
}

I'd like to filter the results such that prices contains at least one of a list of values which are between eg: [20002,30000] # would not return the above document because no value is between 20002 and 30000 but [10000,20002] would return above document because 20001 in the prices field of above document is between 10000 and 20002

like image 933
Robin Avatar asked Feb 09 '23 16:02

Robin


1 Answers

Elasticsearch always considers that a field can contain a list of values so, a range filter should work. If any of the values matches the range it will be filtered in.

You can use that filter as part of a filtered query:

{
  "query": {
    "filtered": {
      "filter": {
        "range": {
          "prices": {
            "gte": 10000,
            "lte": 20002
          }
        }
      }
    }
  }
}

However, filtered query is deprecated in 2.0, so, if you are using 2.0 you can better use a bool query with a filter:

{
  "query": {
    "bool": {
      "must": {
        "match_all": {}   
      },  
      "filter": {
        "range": {
          "prices": {
            "gte": 10000,
            "lte": 20002
          }
        }
      }
    }
  }
}

Note that I'm using a filter in my examples because you asked for a filter :)

like image 190
moliware Avatar answered Feb 12 '23 16:02

moliware