首页 > 解决方案 > 如何使用滚动在python中加载弹性数据?

问题描述

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

 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'的值,但仍然会发生此异常。

标签: pythonelasticsearchelastic-stack

解决方案


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

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
}

我添加了以下部分来回答评论中的问题。它不会因为您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)

请让我知道这是否有任何问题。


推荐阅读