【问题标题】:How do I create an “In” Condition filter using elasticsearch-dsl-py?如何使用 elasticsearch-dsl-py 创建“In”条件过滤器?
【发布时间】:2020-12-04 05:48:10
【问题描述】:

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

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

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

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

使用elasticsearch-dsl-py,这是我能得到的最接近的,但它不一样。

class MyIndex(Document):

    status = Keyword() / Text()
    
    

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

【问题讨论】:

    标签: python-3.x elasticsearch dsl elasticsearch-dsl


    【解决方案1】:

    执行此操作的另一种方法是使用带有数组的terms 查询,因为每个数组元素都是隐式或运算的。另外,我不确定您运行的是哪个版本的 ES,但只知道 filtered has been replaced by bool 很久以前在版本 5 中。所以您的查询可以这样重写:

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

    使用elasticsearch-dsl-py,转换为:

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

    【讨论】:

    • 这个答案对我有用,但我看不出与{"query": {"terms": {"status": ["a", "b", "c"]}}} 的区别,你能告诉我吗?
    • @ciurlaro 不确定你的意思
    • 你写的查询和我写的查询有逻辑上的区别吗?我想知道你为什么还要放bool和filter
    • 不同之处在于,如果没有bool/filter,就会开始计分,而当你像这个问题一样进行精确匹配时,它是没用的,而且会不必要地增加响应时间
    • 这是一个聪明的观察。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多