如何使用 python 在一个弹性搜索查询中进行范围和匹配查询?

How to have Range and Match query in one elastic search query using python?

我必须在某个 "key" 范围内找到具有字符串的匹配文档,例如:"sky"。当我编写单独的匹配和范围查询时,我从 ES 获得输出但合并在一起时抛出异常。

范围查询:

res = es.search(index="dummy",
                body={"from":0, "size":0,"query": {"range":{"key":{"gte":"1000"}}}})

匹配查询:

res = es.search(index="dummy",
                body={"from":0, "size":0,"query": {"match":{"word":"sky"}}})

组合查询:

res = es.search(index="dummy",
                body={
                  "from":0,
                  "size":0,
                  "query": {
                    "range":{
                      "key":{"gte":"1000"}
                    }
                  },
                  "match":{"word":"sky"}
                })

组合查询执行时报错:

raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) elasticsearch.exceptions.RequestError: TransportError(400, u'parsing_exception', u'Unknown key for a START_OBJECT in [match].')

合并这两个查询的正确方法是什么?

您需要使用 bool/must 查询

res = es.search(index="dummy", body={
  "from": 0,
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "key": {
              "gte": "1000"
            }
          }
        },
        {
          "match": {
            "word": "sky"
          }
        }
      ]
    }
  }
})