使用Java High Level Rest Client调用Rollover API无法自动创建索引求助
问题原因
- Rollover API调用顺序错误。你在写入测试数据之前就调用了Rollover接口,此时初始索引
test_log-1的文档数为0,完全不满足你设置的1条文档的触发条件,所以没有触发滚动。后续你写入2条数据后再也没有调用过Rollover接口,自然不会生成新索引。
注意:ES的Rollover API本身是主动触发接口,不会自动后台运行,除非你配置了ILM(索引生命周期管理)策略,由ES后台定期检查触发。 - 初始索引的命名不符合默认滚动规则最佳实践。你使用的
test_log-1后缀格式虽然可以被识别,但更推荐使用test_log-000001这类6位补零的命名格式,避免ES自动生成索引后缀时出现解析异常。 - 没有显式设置别名的写权限属性。给初始索引绑定别名时,建议显式设置
is_write_index: true,确保滚动后别名会自动切换到新的索引作为写入口。
修正方案
方案1:手动调用Rollover(适合按需触发场景)
调整代码执行顺序,写入数据后再调用Rollover接口即可,修正后代码示例:
final RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); boolean isIndexTemplateCreated = createIndexTemplate(client); System.out.println(isIndexTemplateCreated); // 1. 创建初始索引,使用补零后缀,显式设置为写别名 CreateIndexRequest request = new CreateIndexRequest("test_log-000001"); request.alias(new Alias("temp_alias_new").writeIndex(true)); client.indices().create(request, RequestOptions.DEFAULT); // 2. 写入测试数据 Map<String,Object> map = new HashMap<>(); map.put("fullLog","Hi"); client.index(new IndexRequest("temp_alias_new").source(map), RequestOptions.DEFAULT); map.put("fullLog","hello"); client.index(new IndexRequest("temp_alias_new").source(map), RequestOptions.DEFAULT); // 3. 写入完成后调用Rollover接口检查触发条件 RolloverRequest roll_req = new RolloverRequest("temp_alias_new",null); roll_req.addMaxIndexAgeCondition(new TimeValue(7, TimeUnit.DAYS)); roll_req.addMaxIndexDocsCondition(1); roll_req.addMaxIndexSizeCondition(new ByteSizeValue(5, ByteSizeUnit.GB)); RolloverResponse rolloverResponse = client.indices().rollover(roll_req, RequestOptions.DEFAULT); // 可打印返回结果确认滚动状态 System.out.println("是否触发滚动:" + rolloverResponse.isRolledOver()); System.out.println("新索引名称:" + rolloverResponse.getNewIndex());
方案2:配置ILM自动触发(适合生产环境)
如果需要ES自动后台触发滚动,不需要手动调用接口,按以下步骤配置即可:
- 先创建ILM策略,在策略中设置对应的滚动触发条件
- 在你现有索引模板的settings中新增以下配置:
"index.lifecycle.name": "你的ILM策略名称", "index.lifecycle.rollover_alias": "temp_alias_new"
配置完成后ES会默认每10分钟检查一次索引条件,满足要求时自动触发滚动。
内容的提问来源于stack exchange,提问作者Ajay Venkatesh
相关产品推荐
相关产品推荐

