Elasticsearch与Python请求:MSSearch请求必须以换行符终止

2024-04-16 15:48:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在对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)

同样的错误


Tags: keytokenjsonurles错误servicequery
2条回答

感谢@wholevinski的回答(在问题评论中)。我需要将json更改为数据并添加标题。此外,我还需要执行\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)

这里有一个想法:

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

Accept: text/plain是一个unnecessary workaround

相关问题 更多 >