首页 > 解决方案 > 正确使用@CompoundIndex 和 MongoRepository

问题描述

我的查询响应速度很慢,所以我想知道我是否正在创建复合 mongo 索引并在 MongoRepository 中有效地使用它,以及如何验证索引是否有效。

@CompoundIndexes({
    @CompoundIndex(name = "onwebsite_process_sequence", def = "{'additionalfields.onwebsite': 1, 'additionalfields.process' : 1, 'additionalfields.onwebsite': 1}")
})

public class DdsJson {
  @JsonInclude(JsonInclude.Include.NON_EMPTY)
  @JsonProperty("additional_fields")
  AdditionalFields additionalfields = new AdditionalFields();
...
}


public class AdditionalFields {

  public static final Logger LOG = LoggerFactory.getLogger(AdditionalFields.class);
  @JsonInclude(JsonInclude.Include.NON_EMPTY)
  @JsonProperty("sequence")
  @Indexed
  private Integer sequence;
  @JsonInclude(JsonInclude.Include.NON_EMPTY)
  @JsonProperty("process")
  @Indexed
  private Integer process;
  @JsonInclude(JsonInclude.Include.NON_EMPTY)
  @JsonProperty("onwebsite")
  @Indexed
  private String onwebsite;
}

public interface DdsJsonRepository extends MongoRepository<DdsJson, Integer> {
         
Page<DdsJson> findByAdditionalfields_OnwebsiteAndAdditionalfields_SequenceAndAdditionalfields_Sequence(String onwebsite,int process, int sequence, Pageable pageable);
        
         
}

问候康泰

标签: javamongodbspring-boot

解决方案


如何验证索引是否有效。

这里有两种方式...

  1. 通过负载测试覆盖您的代码。运行不带索引和带索引的版本。假设在其中插入 1000 万条记录并尝试进行一些读取。按照本指南设置集成测试,然后计时。
  2. 您可以添加索引,然后按照本指南阅读查询计划。它会让你知道你的索引是否会被使用。

所以你去......一个实验和理论解决方案。我建议两者都探索。为您将来解决此类问题提供了良好的背景。


推荐阅读