首页 > 解决方案 > Elasticsearch Delete By Query API:Curl 正在工作,但无法使用 Python(请求)实现相同功能?

问题描述

我正在使用 Delete By Query API 来删除一堆文档。下面的卷曲工作完美:

POST /tom-access/doc/_delete_by_query
{
  "query": {
    "terms": {
      "_id": [
        "xxxxx",
        "yyyyy"
      ]
    }
  }
}

现在,我想利用requestsPython 中的库来实现同样的目的。

import requests,json

url = "http://elastic.tool.com:80/tom-access/doc/_delete_by_query"
headers = {"Content-type": "application/json", "Accept": "application/json", "Authorization": "Basic asdadsasdasdasd"}

data = {
        'query':{
                'terms':{
                        '_id':[
                                'xxxxx',
                                'yyyyy'
                        ]
                }
        }
}

try:
    r = requests.post(url,
                 headers=headers,
                 data=data,
                 verify=False)
except blablaaa

response_dict = r.json()
print(response_dict)

我收到以下错误:

{'error': {'root_cause': [{'type': 'json_parse_exception', 'reason': "Unrecognized token 'query': was expected ('true', 'false' or 'null')\n at [来源:org.elasticsearch.transport.netty4.ByteBufStreamInput@bc04803;行:1,列:7]"}],'类型':'json_parse_exception','原因':"无法识别的令牌'查询':期待('真', 'false' 或 'null')\n 在 [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@bc04803; line: 1, column: 7]"}, 'status': 500}

我究竟做错了什么?

标签: elasticsearch

解决方案


我认为您应该尝试""data变量中使用双引号 () 而不是单引号 ( '')。此外,使用json.dumps(). 这是来自https://marcobonzanini.com/2015/02/02/how-to-query-elasticsearch-with-python/
的示例,其中显示了该库的使用:requests

def search(uri, term):
    """Simple Elasticsearch Query"""
    query = json.dumps({
        "query": {
            "match": {
                "content": term
            }
        }
    })
    response = requests.get(uri, data=query)
    results = json.loads(response.text)
    return results

还有用于 python elasticsearch-py的官方 elasticsearch 客户端。


推荐阅读