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

标签 python elasticsearch

我正在尝试运行 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/

相关文章:

arrays - 将整数数组传递给ElasticSearch模板

python - easy_install-2.7 的问题

elasticsearch - 备份和还原Elasticsearch索引的一些记录

python - Python 2.4 中的 SHA256 哈希

python - 使用 python-gps 从 gpsd/gpsfake 读取

elasticsearch - 基于第一个字符的 Elasticsearch 字母排序

java - Elasticsearch-忽略持久化的属性

elasticsearch - Elasticsearch-跳过索引为空或空值的文档

python错误太多值无法解包

python - 如何忽略 python 2.6 中的证书?