簡體   English   中英

Elasticsearch 的 Python 自動批量請求不起作用“必須由換行符終止”

[英]Python-automated bulk request for Elasticsearch not working "must be terminated by a newline"

我正在嘗試通過 Python 自動執行對 Elasticsearch 的批量請求。

因此,我正在為請求正文准備如下數據(作為單獨的行保存在列表中):

data = [{"index":{"_id": ID}}, {"tag": {"input": [tag], "weight":count}}]

然后我將使用請求進行 Api 調用:

r = requests.put(端點,json = 數據,auth = auth)

這給了我錯誤:b'{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"The bulk request must be terminated by a newline [\\n]"} ],"type":"illegal_argument_exception","reason":"批量請求必須由換行符終止 [\\n]"},"status":400}'

我知道我需要在請求末尾換行,這就是我的問題:我如何 append 換行到給定的數據結構? 我最后嘗試將 append '\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())

PS:您可能需要考慮官方 py 客戶端中的bulk helper

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM