Reputation: 101
I am implementing a Spring Data Repository and having my repository extend the MongoRepository. I am looking for a way to specify a hint on my findBy methods so I can be control. I have seen several times when a non-optimal index would be picked as the winning plan.
This is what my repository looks like right now:
public interface AccountRepository extends MongoRepository<Account, ObjectId> {
@Meta(maxExcecutionTime = 60000L, comment = "Comment" )
public List<Account> findByUserIdAndBrandId(Long userId, Long brandId);
}
I researched a bunch and found that the JPARepository from spring data supports the @QueryHint annotation but I do not believe that annotation is supported for MongoDb. Is there a similar annotation I can specify on top of my findBy method to specify the hint?
MongoTemplate allows to specify a hint, however, I have a ton of findBy methods and I would hate to add an implementation underneath just to specify a hint.
Upvotes: 7
Views: 1181
Reputation: 1678
As of spring-data-mongo 4.1, you can now specify an index hint for repository methods using the new @Hint
annotation.
Reference documentation here.
Your code would look like:
public interface AccountRepository extends MongoRepository<Account, ObjectId> {
@Hint("my_custom_index_1")
public List<Account> findByUserIdAndBrandId(Long userId, Long brandId);
}
Note that Mongo will automatically pick an appropriate index by default for executing repository methods (as it would do with a native mongosh .find(...)
command), so you should only use the @Hint
annotation if there's a particular reason that you need Mongo to use a different index over the one it auto-picks.
Upvotes: 2