【Elasticsearch】使用游标遍历所有数据

通过使用Elasticsearch 的内置游标方式,遍历所有数据

部分代码需要参考本专题的前面几个章节内容

复制代码
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Result;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchAllQuery;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonData;


private ElasticsearchClient esClient;

public  void scrollAllData(EsDocReq req, Function<List<? extends Hit<? extends Map>>, Boolean> processHits) {
        String indexName = req.getIndexLib();
        log.info("遍历数据开始" + indexName);

        final String timeout = "5m";
        try {
            SearchRequest searchRequest = SearchRequest.of(i ->
                    {
                        i.index(indexName)
                                .scroll(s -> s.time(timeout))
                                .query(MatchAllQuery.of(q -> q)._toQuery())
                                .size(100);
                        if(null != req.getColumns()){
                            i.source(src -> src.filter(f -> f.includes(req.getColumns())));
                        }
                        return i;
                    }
            );

            Map<String, Object> dataMap = new HashMap<>();
            SearchResponse<? extends Map> searchResponse = esClient.search(searchRequest, dataMap.getClass());

            Map<String, String> scollMap = new HashMap<>();
            String key = "scroll";
            scollMap.put(key, searchResponse.scrollId());

            List<? extends Hit<? extends Map>> hits = searchResponse.hits().hits();

            processHits.apply(hits);

            while (!hits.isEmpty()) {
                ScrollRequest scrollRequest = ScrollRequest.of(i -> i
                        .scrollId(scollMap.get(key))
                        .scroll(s -> s.time(timeout))
                );

                ScrollResponse<? extends Map> scrollResponse = esClient.scroll(scrollRequest, dataMap.getClass());

                scollMap.put(key, scrollResponse.scrollId());
                hits = scrollResponse.hits().hits();

                processHits.apply(hits);
            }

            ClearScrollRequest clearScrollRequest = ClearScrollRequest.of(i -> i.scrollId(scollMap.get(key)));
            ClearScrollResponse clearScrollResponse = esClient.clearScroll(clearScrollRequest);
            if (clearScrollResponse.succeeded()) {
                log.info("遍历数据结束");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1、EsDocReq 为自定义的请求对象

2、Function<List<? extends Hit<? extends Map>>, Boolean> processHits 用于实际遍历中处理读取的数据。【根据需要自定义函数,并以参数传递

3、timeout = "5m"; 表示超时时间5分钟

4、 i.source 表示需要返回的指定字段

5、结尾需要清理游标 ClearScrollRequest

以下是 调用函数说明示例:

复制代码
EsDocReq req = new EsDocReq();

scrollAllData(req, fn -> {
            for (Hit<? extends Map> hit : fn) {
                try {
                    String esIndex = hit.id(); 
                    // TODO 实际业务
                    
                } catch (Exception e) { 
                    log.error(e.getMessage(), e);
                }
            }
            return true;
        });
相关推荐
A__tao1 小时前
Elasticsearch Mapping 一键生成 Proto 文件(支持嵌套 + 注释过滤)
大数据·elasticsearch·jenkins
Devin~Y2 小时前
高并发电商与AI智能客服场景下的Java面试实战:从Spring Boot到RAG与向量数据库落地
java·spring boot·redis·elasticsearch·spring cloud·kafka·rag
Elastic 中国社区官方博客5 小时前
使用 Jina-VLM 小型多语言视觉语言模型来和图片对话
大数据·人工智能·elasticsearch·语言模型·自然语言处理·jina
LDG_AGI5 小时前
【搜索引擎】Elasticsearch(二):基于function_score的搜索排序
数据库·人工智能·深度学习·elasticsearch·机器学习·搜索引擎·推荐算法
历程里程碑6 小时前
Protobuf总结
大数据·数据结构·elasticsearch·链表·搜索引擎
ACGkaka_7 小时前
ES 学习(七)性能陷阱
大数据·学习·elasticsearch
LDG_AGI8 小时前
【搜索引擎】Elasticsearch(三):基于script_score的自定义搜索排序
大数据·人工智能·深度学习·elasticsearch·机器学习·搜索引擎·推荐算法
Elastic 中国社区官方博客8 小时前
如何使用 Mastra 和 Elasticsearch 构建具备代理能力的 AI 应用
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
LDG_AGI8 小时前
【搜索引擎】Elasticsearch(一):索引创建、数据插入、请求示例
人工智能·深度学习·算法·elasticsearch·机器学习·搜索引擎·推荐算法
历程里程碑8 小时前
Protobuf vs JSON vs XML:小白该怎么选?
xml·大数据·数据结构·elasticsearch·链表·搜索引擎·json