如何正确使用@CompoundIndex与MongoRepository并验证索引有效性
现有代码问题修正
1. 复合索引定义错误
你当前定义的复合索引重复声明了additionalfields.onwebsite字段,缺失了查询用到的sequence字段,无法匹配你的业务查询逻辑,正确写法如下:
@CompoundIndexes({ @CompoundIndex(name = "onwebsite_process_sequence", def = "{'additionalfields.onwebsite': 1, 'additionalfields.process' : 1, 'additionalfields.sequence': 1}") }) public class DdsJson { // 其余逻辑不变 }
如果没有单独查询单个字段的需求,建议删除AdditionalFields类中三个字段上的单独@Indexed注解,避免写入数据时产生额外的索引维护开销。
2. Repository方法定义错误
当前方法名重复声明了两次Sequence查询条件,且缺失了process字段的匹配声明,会导致Spring Data MongoDB生成的查询逻辑和参数不匹配,也无法命中复合索引,正确写法如下:
public interface DdsJsonRepository extends MongoRepository<DdsJson, Integer> { Page<DdsJson> findByAdditionalfields_OnwebsiteAndAdditionalfields_ProcessAndAdditionalfields_Sequence(String onwebsite, int process, int sequence, Pageable pageable); }
索引与MongoRepository适配说明
MongoDB复合索引遵循最左前缀匹配原则,你定义的onwebsite->process->sequence顺序的复合索引,只要查询条件包含最左1个、连续2个或者全部3个字段,都可以命中该索引。你当前的业务查询同时用到三个字段,完全匹配索引顺序,修正后的Repository方法会自动生成符合索引规则的查询语句,正常发挥索引的加速效果。
注意:如果查询带排序规则,需将排序字段按顺序追加到复合索引末尾,避免内存排序开销
索引运行效果验证方法
1. MongoDB层面直接验证
在Mongo Shell中执行带explain的查询语句,示例如下:
db.ddsJson.find( {"additionalfields.onwebsite": "测试值", "additionalfields.process": 1, "additionalfields.sequence": 10} ).explain("executionStats")
- 查看返回结果中
executionStats.executionStages.stage字段,值为IXSCAN说明命中索引,值为COLLSCAN说明走了全表扫描未命中索引 - 对比
totalDocsExamined(扫描文档数)和totalKeysExamined(扫描索引键数),两个数值越接近说明索引效率越高,若扫描文档数远大于扫描索引键数说明索引匹配度低
2. Spring项目日志验证
在项目配置文件中开启MongoDB操作日志:
# application.yml 配置 logging: level: org.springframework.data.mongodb.core.MongoTemplate: DEBUG
# application.properties 配置 logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG
开启后控制台会打印出生成的完整查询语句,你可以对照查询条件和索引规则确认是否匹配,也可以将打印的查询语句复制到Mongo Shell中用上述explain方法验证。
内容的提问来源于stack exchange,提问作者conteh
相关产品推荐
相关产品推荐

