如何使用elasticsearch-dsl-py创建“或”条件过滤器?

问题描述

下面的查询是我想使用elasticsearch-dsl-py构造的,但是我不知道该怎么做。

GET /my_index/_search
{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
           "or": {
            "filters": [
            {
              "term": {
                "status": "a"
              },"term": {
                "x_status": "a"
              },}
          ]
         }
        }
      }
    }
  }
}

我只想以sql格式执行如下查询

select * from my_index where status = "a" or x_status="a"

解决方法

我不确定您正在运行哪个版本的ES,但很早以前就知道filtered has been replaced by bool在版本5中。因此,您的查询可以这样重写:

GET /my_index/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "status": "a"
          }
        },{
          "term": {
            "x_status": "a"
          }
        }
      ]
    }
  }
}

使用elasticsearch-dsl-py表示:

s = Search()
s = s.query('bool',should=[Q('term',status='a'),Q('term',x_status='a')])