【问题标题】:How to load elastic data in python using scroll?如何使用滚动在python中加载弹性数据?
【发布时间】:2021-10-26 14:40:09
【问题描述】:

我在弹性搜索中有一个包含大量数据的索引。我正在尝试在 python 中加载它的一些数据(超过 10000 条记录)以进行进一步处理。根据文档和网络搜索,使用了 scroll,但它只能获取少量记录。一段时间后发生此异常,

 errorNotFoundError(404, 'search_phase_execution_exception', 'No search context found for id [101781]')

我的代码如下:

from elasticsearch import Elasticsearch

##########elastic configuration
host='localhost'
port=9200
user=''
pasw=''
el_index_name = 'test'


es = Elasticsearch([{'host':host , 'port': port}], http_auth=(user,pasw))
res = es.search(index=el_index_name, body={"query": {"match_all": {}}},scroll='10m')

rows=[]
while True:
    try:
        rows.append(es.scroll(scroll_id=res['_scroll_id'])['hits']['hits'])
    except Exception as esl:
        print ('error{}'.format(esl))
        break

##deleting scroll
es.clear_scroll(scroll_id=res['_scroll_id'])

我更改了 scroll='10m' 的值,但仍然出现此异常。

【问题讨论】:

    标签: python elasticsearch elastic-stack


    【解决方案1】:

    您需要将滚动请求行更改为:

    rows.append(es.scroll(scroll_id=res['_scroll_id'], body={"scroll": "10m","scroll_id": res['_scroll_id']})['hits']['hits'])
    

    作为建议,最好增加检索帖子的数量。在每个请求中仅检索 1 个帖子会对您的性能产​​生负面影响,并且也会对您的集群产生开销。例如:

    {
      "query": {
        "match_all": {}
      },"size":100
    }
    

    我添加了以下部分来回答 cmets 中的问题。它不会停止,因为您已将 While True 放入您的代码中。您需要将其更改为:

    res = es.search(index=el_index_name, body={"query": {"match_all": {}}}, scroll='10m')
    scroll_id = res['_scroll_id']
    query = {
        "scroll": "10m",
        "scroll_id": scroll_id
    }
    
    rows = []
    while len(res['hits']['hits']):
        for item in res['hits']['hits']:
            rows.append(item)
    
        res = es.scroll(scroll_id=scroll_id, body=query)
    
    

    如果有任何问题,请告诉我。

    【讨论】:

    • while循环不停,一共有12619条记录,res['hits']['total']['value']=12619。但它并没有停止,它正在读取永无止境的记录数。
    • 您好,我添加了一个完整的代码来解决您的问题。请检查并让我知道它是否有效。谢谢!
    • 我使用扫描仪加载所有数据。
    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2018-01-16
    • 2020-01-15
    相关资源
    最近更新 更多