gpt4 book ai didi

python - 如何为 Python Elasticsearch mSearch 创建请求主体

转载 作者:太空狗 更新时间:2023-10-29 20:37:07 25 4
gpt4 key购买 nike

我正在尝试运行 a multi search request在 Elasticsearch Python 客户端上。我可以正确运行单一搜索,但无法弄清楚如何格式化 msearch 请求。根据文档,请求的正文需要格式化为:

The request definitions (metadata-search request definition pairs), as either a newline separated string, or a sequence of dicts to serialize (one per row).

创建此请求正文的最佳方法是什么?我一直在寻找示例,但似乎找不到任何示例。

最佳答案

如果您按照 official doc 的演示进行操作(甚至认为它是针对 BulkAPI 的),您会发现如何使用 Elasticsearch 客户端在 python 中构造您的请求:

这里是换行分隔字符串的方式:

def msearch():
es = get_es_instance()

search_arr = []
# req_head
search_arr.append({'index': 'my_test_index', 'type': 'doc_type_1'})
# req_body
search_arr.append({"query": {"term" : {"text" : "bag"}}, 'from': 0, 'size': 2})

# req_head
search_arr.append({'index': 'my_test_index', 'type': 'doc_type_2'})
# req_body
search_arr.append({"query": {"match_all" : {}}, 'from': 0, 'size': 2})

request = ''
for each in search_arr:
request += '%s \n' %json.dumps(each)

# as you can see, you just need to feed the <body> parameter,
# and don't need to specify the <index> and <doc_type> as usual
resp = es.msearch(body = request)

可以看到,final-request是由几个req_unit构成的。每个 req_unit 结构如下所示:

request_header(search control about index_name, optional mapping-types, search-types etc.)\n
reqeust_body(which involves query detail about this request)\n

sequence of dicts to serialize 方法和前面的几乎一样,只是不需要将其转换为字符串:

def msearch():
es = get_es_instance()

request = []

req_head = {'index': 'my_test_index', 'type': 'doc_type_1'}
req_body = {
'query': {'term': {'text' : 'bag'}},
'from' : 0, 'size': 2 }
request.extend([req_head, req_body])

req_head = {'index': 'my_test_index', 'type': 'doc_type_2'}
req_body = {
'query': {'range': {'price': {'gte': 100, 'lt': 300}}},
'from' : 0, 'size': 2 }
request.extend([req_head, req_body])

resp = es.msearch(body = request)

Here is它返回的结构。阅读更多关于 msearch 的信息.

关于python - 如何为 Python Elasticsearch mSearch 创建请求主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28546253/

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