我正在实现一个 Spring Data Repository 并让我的存储库扩展 MongoRepository。我正在寻找一种方法来指定我的 findBy 方法的提示,以便我可以控制。我曾多次看到非最佳索引被选为获胜计划。
这就是我的存储库现在的样子:
public interface AccountRepository extends MongoRepository<Account, ObjectId> {
@Meta(maxExcecutionTime = 60000L, comment = "Comment" )
public List<Account> findByUserIdAndBrandId(Long userId, Long brandId);
}
我研究了很多,发现 Spring Data 的 JPARepository 支持 @QueryHint 注释,但我不相信 MongoDb 支持该注释。我可以在 findBy 方法之上指定类似的注释来指定提示吗?
MongoTemplate 允许指定提示,但是,我有大量的 findBy 方法,我不想在下面添加一个实现来指定提示。
从 spring-data-mongo 4.1 开始,您现在可以使用新的
@Hint
注释为存储库方法指定索引提示。
参考文档这里。
您的代码如下所示:
public interface AccountRepository extends MongoRepository<Account, ObjectId> {
@Hint("my_custom_index_1")
public List<Account> findByUserIdAndBrandId(Long userId, Long brandId);
}
请注意,Mongo 默认情况下会自动选择适当的索引来执行存储库方法(就像使用本机 mongosh
.find(...)
命令一样),因此,如果有特殊原因需要 Mongo,则应该仅使用 @Hint
注释使用与其自动选择的索引不同的索引。