Luk*_*ann 4 python json list elasticsearch python-requests
我正在尝试通过 Python 自动执行对 Elasticsearch 的批量请求。
因此,我正在为请求正文准备数据,如下所示(作为单独的行保存在列表中):
data = [{"index":{"_id": ID}}, {"tag": {"input": [tag], "weight":count}}]
然后我将使用 requests 来进行 Api 调用:
r = requests.put(端点, json = 数据, auth = auth)
这给了我错误: b'{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"批量请求必须由换行符 [\\n]"} 终止],"type":"illegal_argument_exception","reason":"批量请求必须由换行符 [\\n] 终止"},"status":400}'
我知道我需要在请求末尾添加换行符,这就是我的问题:如何将换行符附加到给定的数据结构?我尝试将 '\n' 添加到我的列表末尾,但没有成功。
感谢你们!
有效负载的内容类型必须是,并且还需要指定属性ndjson。index这是一个工作片段:
import requests
import json
endpoint = 'http://localhost:9200/_bulk'
# vvvvvv
data = [{"index": {"_index": "123", "_id": 123}},
{"tag": {"input": ['tag'], "weight":10}}]
# vvv vvv
payload = '\n'.join([json.dumps(line) for line in data]) + '\n'
r = requests.put(endpoint,
# `data` instead of `json`!
data=payload,
headers={
# it's a requirement
'Content-Type': 'application/x-ndjson'
})
print(r.json())
Run Code Online (Sandbox Code Playgroud)
PS:您可能需要考虑官方 py 客户端中的bulk帮助程序。
| 归档时间: |
|
| 查看次数: |
2385 次 |
| 最近记录: |