Mongo Reactive实现索引不存在时创建索引的方案问询
Reactive方式实现MongoDB索引不存在时创建的需求
要解决索引不存在时创建的问题,核心是先判断索引是否存在,再根据结果执行创建逻辑,避开switchIfEmpty的类型不匹配问题,具体实现如下:
步骤1:判断指定索引是否存在
将查询索引的Flux<IndexInfo>转换为Mono<Boolean>,明确标识索引是否存在:
Mono<Boolean> indexExists = mongoTemplate.indexOps(IncotermLocation.class) .getIndexInfo() .filter(indexInfo -> indexInfo.getName().equals("alternativeLocations")) .hasElements(); // 存在匹配索引返回true,否则返回false
步骤2:条件创建索引
基于索引存在性的结果,仅当索引不存在时执行创建操作:
indexExists .filter(exists -> !exists) // 过滤掉索引已存在的情况,仅保留不存在的分支 .flatMap(ignored -> mongoTemplate.indexOps(IncotermLocation.class) .ensureIndex(new Index().named("alternativeLocations").on("unLocationCodes", Sort.Direction.ASC))) // 根据业务场景处理订阅,比如WebFlux中返回该Mono作为响应,或后台任务中调用subscribe() .subscribe();
可选优化:忽略创建结果
如果不需要关注ensureIndex返回的索引名称,可以用then()将结果转换为Mono<Void>,简化逻辑:
indexExists .filter(exists -> !exists) .flatMap(ignored -> mongoTemplate.indexOps(IncotermLocation.class) .ensureIndex(new Index().named("alternativeLocations").on("unLocationCodes", Sort.Direction.ASC)) .then()) // 转换为无返回值的Mono .subscribe();
这种方式完全遵循Reactive编程范式,通过类型转换和条件过滤解决了原问题中switchIfEmpty的类型不匹配问题,逻辑清晰且易于维护。
内容的提问来源于stack exchange,提问作者Sanchelz
相关产品推荐
相关产品推荐

