gpt4 book ai didi

Elasticsearch 的 Python 自动批量请求不起作用 "must be terminated by a newline"

转载 作者:行者123 更新时间:2023-12-03 01:17:25 30 4
gpt4 key购买 nike

我正在尝试通过 Python 自动执行 Elasticsearch 的批量请求。

因此,我正在为请求主体准备如下数据(作为单独的行保存在列表中):

数据=[{“索引”:{“_id”:ID}},{"tag": {"input": [tag], "weight":count}}]

然后我将使用请求进行 Api 调用:

r = requests.put(endpoint, json = data, auth = auth)

这是给我的错误:b'{"error":{"root_cause":[{"type":"illegal_argument_exception","re​​ason":"批量请求必须以换行符终止 [\\n]"}],"type":"illegal_argument_exception","re​​ason":"批量请求必须由换行符终止 [\\n]"},"status":400}'

我知道我需要在请求末尾换行,这就是我的问题:我如何将换行符附加到给定的数据结构?我试图在最后将“\n”附加到我的列表中,但没有成功。

谢谢大家!

最佳答案

payload 的内容类型必须是 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())

P.S.:您可能需要考虑 bulk helper在官方py客户端中。

关于Elasticsearch 的 Python 自动批量请求不起作用 "must be terminated by a newline",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61866140/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com