【问题标题】:How to use msearch() with "q" in Python ElasticSearch?如何在 Python ElasticSearch 中使用带有“q”的 msearch()?
【发布时间】:2022-06-21 23:17:59
【问题描述】:

我一直在使用标准 Python ElasticSearch client 以以下格式发出单个请求:

es.search(index='my_index', q=query, size=5, search_type='dfs_query_then_fetch')

我现在想批量查询多个字符串q

我看到this question 解释如何使用msearch() 功能进行批量查询。但是,msearch 需要每个请求的完整 json 格式的请求正文。我不确定查询 API 中的哪些参数仅对应于来自 search()sizesearch_typeq 参数,这似乎是特定于单个示例 search() 的 API 快捷方式。

如何使用msearch 但指定qsizesearch_type

【问题讨论】:

    标签: python elasticsearch


    【解决方案1】:

    我通读了 API 并弄清楚了如何批量处理简单的搜索查询:

    from typing import List
    
    from elasticsearch import Elasticsearch
    
    import json
    
    def msearch(
            es: Elasticsearch,
            max_hits: int,
            query_strings: List[str],
            index: str
        ):
        search_arr = []
        
        for q in query_strings:
            search_arr.append({'index': index })
            search_arr.append(
                {
                    "query": {
                        "query_string": {
                            "query": "butch cassidy"
                        }
                },
                'size': max_hits 
            })
        
        request = ''
        request = ' \n'.join([json.dumps(x) for x in search_arr])
    
        # 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)
        return resp
    
    msearch(es, query_strings=['query 1', 'query 2'], max_hits=1, index='my_index')
    

    【讨论】:

      猜你喜欢
      • 2017-03-29
      • 2022-08-21
      • 2015-04-17
      • 2018-03-03
      • 1970-01-01
      • 2018-02-26
      • 2022-03-08
      • 2017-08-25
      • 2015-01-27
      相关资源
      最近更新 更多