Search code examples
python-3.xelasticsearchdslelasticsearch-dsl

How do I create an “In” Condition filter using elasticsearch-dsl-py?


The query below is what I would like to construct using elasticsearch-dsl-py, but I do not know how to do it.

GET /my_index/_search
{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "should": [
            {
              "term": {
                "status": "a"
              },
              "term": {
                "status": "b"
              },
              "term": {
                "status": "c"
              }
            }
          ]
        }
      }
    }
  }
}

I just want to execute a query like below in SQL format

select * from my_index where status in ("a","b","c")

Using elasticsearch-dsl-py, this is as close as I can get, but it is not the same.

class MyIndex(Document):

    status = Keyword() / Text()
    
    

MyIndex.search().filter('should', status=["a","b","c"])

Solution

  • Another way of doing this is by using the terms query with an array as each array element is implicitly ORed. Also, I'm not sure which version of ES you're running, but just know that filtered has been replaced by bool a long time ago in version 5. So your query can be rewritten like this:

    GET /my_index/_search
    {
      "query": {
        "bool": {
          "filter": {
             "terms": {
               "status": ["a", "b", "c"]
             }
          }
        }
      }
    }
    

    Using elasticsearch-dsl-py, this translates to:

    s = Search()
    s = s.filter('terms', status=['a', 'b', 'c'])