【问题标题】:ElasticSearch query to pandas dataframe对熊猫数据框的 ElasticSearch 查询
【发布时间】:2022-01-21 16:06:45
【问题描述】:

我有一个问题:

s = Search(using=client, index='myindex', doc_type='mytype')
s.query = Q('bool', must=[Q('match', BusinessUnit=bunit),
                          Q('range', **dicdate)])

res = s.execute()

返回 627033 行,我想将此字典转换为 627033 行的数据帧

【问题讨论】:

  • 您能否提供有关 ElasticSearch 查询输出的更多信息?如果它只是字典,那么问题应该是将字典转换为数据框。对此有很多答案,例如stackoverflow.com/questions/34589332/…
  • 实际上不是我要搜索的字典格式,但它总是只返回 10 个我想要的所有元素

标签: python pandas elasticsearch


【解决方案1】:

根据您的评论,我认为您正在寻找的是尺寸:

es.search(index="my-index", doc_type="mydocs", body="your search", size="1000")

我不确定这是否适用于 627,033 行——您可能需要滚动。

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html

【讨论】:

    【解决方案2】:

    如果您的请求可能从 Elasticsearch 返回超过 10,000 个文档,则需要使用 Elasticsearch 的滚动功能。这个函数的文档和示例很难找到,所以我将为您提供一个完整的工作示例:

    import pandas as pd
    from elasticsearch import Elasticsearch
    import elasticsearch.helpers
    
    
    es = Elasticsearch('127.0.0.1',
            http_auth=('my_username', 'my_password'),
            port=9200)
    
    body={"query": {"match_all": {}}}
    results = elasticsearch.helpers.scan(es, query=body, index="my_index")
    df = pd.DataFrame.from_dict([document['_source'] for document in results])
    

    只需编辑以“my_”开头的字段以对应您自己的值

    【讨论】:

      【解决方案3】:

      我发现solution by Phil B 是适合我情况的一个很好的模板。但是,所有结果都作为列表返回,而不是原子数据类型。为了解决这个问题,我添加了以下帮助函数和代码:

      def flat_data(val):
        if isinstance(val):
          return val[0]
        else:
          return val
      
      df = pd.DataFrame.from_dict([{k:flat_data(v) for (k,v) in document(['fields'].items()} 
                                  for document in results])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-25
        • 2021-10-25
        • 2020-11-10
        • 2020-03-12
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 2021-11-09
        相关资源
        最近更新 更多