使用Java Rest High Level Client时Elasticsearch ReIndex无法同步执行
问题描述
我有两个索引:source_index和destination_index,二者映射一致。我编写了如下代码用于执行ReIndex和搜索请求:
@Autowired RestHighLevelClient client; public BulkByScrollResponse reIndexElasticResponse(ReindexRequest reindexRequest){ BulkByScrollResponse reindexResponse = null; try{ reindexResponse = client.reindex(reindexRequest,RequestOptions.DEFAULT); } catch (IOException e){ throw new RuntimeException(e); } return reindexResponse; } public SearchResponse searchElasticResponseByScrollAPI(SearchScrollRequest searchScrollRequest) { SearchResponse searchResponse = null; try { searchResponse = client.scroll(searchScrollRequest,RequestOptions.DEFAULT); } catch (IOException e) { throw new RuntimeException(e); } return searchResponse; }
我的应用仅将source_index中的部分选中记录ReIndex到destination_index,且在ReIndex请求后立即对destination_index执行搜索查询。但搜索无法返回正确结果,我认为ReIndex未同步执行;若在ReIndex后添加Thread.sleep(5000);,查询结果就正常:
reIndexElasticResponse(reindexRequest); Thread.sleep(5000); searchElasticResponseByScrollAPI(searchScrollRequest);
我希望程序等待所有记录完成ReIndex后,再对destination_index执行搜索查询。
解决方案
1. 启用ReIndex同步等待
Elasticsearch的ReIndex默认是异步执行的,只需在构建ReIndexRequest时设置waitForCompletion为true,就能让client.reindex()方法阻塞直到所有数据迁移完成:
ReindexRequest reindexRequest = new ReindexRequest(); // 配置源索引、目标索引、筛选条件等 reindexRequest.setWaitForCompletion(true); // 关键配置
调用reIndexElasticResponse(reindexRequest)后,方法会直到ReIndex完全结束才返回,后续直接执行搜索就能拿到正确结果,无需手动休眠。
2. 轮询ReIndex任务状态
如果处理大数据量ReIndex,不想长时间阻塞主线程,可以提交异步任务后,轮询任务状态直到完成:
// 提交异步ReIndex任务 BulkByScrollResponse response = reIndexElasticResponse(reindexRequest); String taskId = response.getTaskId(); // 轮询任务运行状态 GetTaskRequest taskRequest = new GetTaskRequest(taskId); while (true) { GetTaskResponse taskResponse = client.tasks().get(taskRequest, RequestOptions.DEFAULT); if (!taskResponse.getTask().isRunning()) { break; } Thread.sleep(100); // 短间隔轮询,降低ES服务压力 } // 任务完成后执行搜索 searchElasticResponseByScrollAPI(searchScrollRequest);
3. 手动刷新目标索引
ReIndex完成后,手动触发目标索引的刷新操作,让新写入的数据立即对搜索可见:
reIndexElasticResponse(reindexRequest); // 刷新destination_index,使新数据立即可查 RefreshRequest refreshRequest = new RefreshRequest("destination_index"); client.indices().refresh(refreshRequest, RequestOptions.DEFAULT); // 执行搜索 searchElasticResponseByScrollAPI(searchScrollRequest);
注意:频繁刷新会增加ES的资源消耗,仅适合小数据量或实时性要求极高的场景。
内容的提问来源于stack exchange,提问作者Aman Mehta
相关产品推荐
相关产品推荐

