22
votes

To create an index for a collection (as documented here https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/) one can use something like the following:

mongoTemplate.indexOps(Person.class).ensureIndex(new Index().on("name",Order.ASCENDING));

But where in the program should I place this code snippet?

In the relevant repository's constructor? I've did it like that now and it works, but I somehow feel like it is bad design.

Somewhere in Mongo configuration? I haven't found a suitable method to override for that here https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/config/AbstractMongoConfiguration.html

1
Have you tried annotating (@Indexed) the indexed field(name) in the person pojo ? Did that not work you or may be that is not what you are looking for ? - s7vr
@Veeram That's not what I am looking for. I have two similar DB model classes, one of which extends the other, and one of these should have a compound unique index over 2 fields, while the other should only have a simple unique index over 1 field. So I've put the @CompoundIndex annotation for the extending class and have to add the index programmatically for the extended class. - Maxim
@Maxim did you found your answer? I have the same doubt. - Nishant Bhardwaz
@NishantBhardwaz I've just placed it in the repository's constructor in absence of a better option. - Maxim

1 Answers

32
votes

If you need to do it in programmatic way, you can just create new Spring's @Configuration and perform such initialization:

@Configuration
@DependsOn("mongoTemplate")
public class CollectionsConfig {

    @Autowired
    private MongoTemplate mongoTemplate;

    @PostConstruct
    public void initIndexes() {
        mongoTemplate.indexOps("collectionName") // collection name string or .class
            .ensureIndex(
                new Index().on("name", Sort.Direction.ASC)
        );
    }
}