使用Python请求的ElasticSearch:msearch请求必须用换行符终止

j2datikz  于 2023-03-12  发布在  ElasticSearch
关注(0)|答案(3)|浏览(322)

我在Python请求中使用msearch,得到了以下错误:

  • msearch请求必须以换行符终止[\n]*

我已经看过很多其他相关的问题/答案,但它们要么使用cURL,一个带有查询的文本文件,要么使用Python es API。我需要使用请求,我的查询是以列表/字典的形式生成的。

url  = <host>+"/" +  'books/_msearch' # books is the index
region = <region>
service = 'es'
credentials = boto3.Session().get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)

payload = [{}, 
           {"query": {"bool": {"filter": [{"terms": {"user_id": [504401]}}]}}, "size": 0},
          {}, 
          {"query": {"bool": {"filter": [{"terms": {"user_id": [504401]}}]}}, "size": 0}
]
                   
r = requests.post(url, auth=awsauth, json=payload)

query_results = json.loads(r.text)

我也试过:

payload = json.dumps(payload) + "\n"

同样的错误。
我也试过:

r = ""
    for d in payload:
        r += json.dumps(d) + "\n"

    r = requests.post(url, auth=awsauth, json=r)

同样的错误。

llmtgqce

llmtgqce1#

感谢@wholevinski给出的答案(在问题注解中),我需要将json改为data并添加头文件,还需要执行\n循环。

payload = [{}, 
           {"query": {"bool": {"filter": [{"terms": {"user_id": [504401]}}]}}, "size": 0},
          {}, 
          {"query": {"bool": {"filter": [{"terms": {"user_id": [504401]}}]}}, "size": 0}
] # same as in question

data_as_str = ""
for d in payload:
    data_as_str += json.dumps(d) + "\n"                 
    
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
# "Accept: text/plain" may not be necessary

r = requests.post(url, headers=headers, auth=awsauth, data=data_as_str)

query_results = json.loads(r.text)
iswrvxsc

iswrvxsc2#

我有个想法:

r = requests.post(url,
                  data="\n".join(
                      [json.dumps(elem) for elem in payload]
                  )+"\n",
                  headers={'Content-Type': 'application/x-ndjson'})

Accept: text/plain是不必要的解决方法。

uelo1irk

uelo1irk3#

如果有人遇到这个2年多后,改变了这个问题,我是在内容类型:

{ headers: { 'Content-Type': 'application/json' } }

=〉

{ headers: { 'Content-Type': 'application/x-ndjson' } }

ndjson =“换行符分隔的JSON”

相关问题