python - 如何使用滚动在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'的值,但仍然会发生此异常。
解决方案
您需要将滚动请求行更改为:
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)
请让我知道这是否有任何问题。
推荐阅读
- python - python中的熊猫:为什么打印“空数据框”,我该如何停止它?
- javascript - 如何在firebase功能上为flutter push Notification创建Firebase push Notification Payload?
- android - 更新后画质丢失
- c# - 使用 ReferenceOutputAssembly=false 添加对另一个可执行文件的引用不会复制依赖项
- python - 使用排列对随机数组进行排序
- c# - 如何在不使用太多 RAM 的情况下将屏幕截图分配给图片框
- node.js - 护照用户车把模板
- javascript - 使用时区将日期转换为 UTC
- python - Tensorflow:不支持的可调用
- python - 拆分数据集后的过采样 - 文本分类