首页 > 解决方案 > 如何使用 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"

标签: python-3.xelasticsearchdsl

解决方案


我不确定您正在运行哪个版本的 ES,但只知道很久以前在版本 5中filtered已将其替换。因此您的查询可以这样重写:bool

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')])

推荐阅读