项目一开始使用scan做全量查询:
documents = es.scan({"query": {"match_all": {}}}, size=500, raise_on_error=False,index="index")
for docs in documents:
yield [doc.get("_source") for doc in docs]
后来发现使用scroll查询会快很多:
page = es.search(index=index, scroll='5m', body={"query":{"match_all":{}}}, size=1000)
total = page['hits']['total']
scroll_id = page['_scroll_id']
for _ in range(int(total / 1000) + 1):
if page['hits']['hits']:
for item in page['hits']['hits']:
if '_source' in item:
yield item['_source']
page = get_es_user().es.scroll(scroll_id=scroll_id, scroll='5m')
scroll_id = page['_scroll_id']
后来查询资料发现scroll支持slice
现在新增了一个:Sliced Scroll 类型
用过 Scroll 接口吧,很慢?如果你数据量很大,用 Scroll 遍历数据那确实是接受不了,现在 Scroll 接口可以并发来进行数据遍历了。每个 Scroll 请求,可以分成多个 Slice 请求,可以理解为切片,各 Slice 独立并行,利用 Scroll 重建或者遍历要快很多倍。
看看这个 demo,可以看到两个 scroll 请求,id 分别是 0 和 1,max 是最大可支持的并行任务,可以各自独立进行数据的遍历获取
GET index/_search?scroll=1m
{
"query": {
"match_all": {}
},
"slice": {
"id": 0,
"max": 2
}
}
大大提高效率
参考资料:
https://www.elastic.co/guide/en/elasticsearch/reference/5.4/breaking_50_search_changes.html
使用方式:https://www.jianshu.com/p/32f4d276d433
es优化点:https://www.infoq.cn/article/2016/08/Elasticsearch-5-0-Elastic/