Search code examples
javaspringmongodbspring-dataspring-data-mongodb

Effect of disabling auto-index-creation but retaining @Indexed annotations


Per https://github.com/spring-projects/spring-data-mongodb/issues/3049 the automatic creation of indexes in Spring Data MongoDb is now deprecated and disabled by default. However, we would like to retain the @Indexed annotations in the code for documentation purposes only.

If we were to skip removing all the @Indexed and @CompoundIndexes annotations from our @Document-annotated classes (I.e. just leave them), meanwhile allowing the default disabled automatic index creation behavior (or explicitly setting spring.data.mongodb.auto-index-creation = false) would this have the same effect as removing all the @Indexed and @CompoundIndexes annotations from the code entirely?

I'm concerned that leaving those annotations in the code might continue to have side affects and/or cause errors unrelated to automatic index creation. Or are these annotations exclusively to support automatic index creation?


Solution

  • The following applies for Spring Boot 2.5.2 and Spring Data Mongo 3.2.2.

    TL;DR;

    If spring.data.mongodb.auto-index-creation=false is set, no indices are created automatically and annotations like @Indexed will have no impact on your mongo collections. On the other hand, they will still allow gathering those index informations from the entity using MongoPersistentEntityIndexResolver at runtime in a programmatic way.

    Detailed walkthrough

    When setting spring.data.mongodb.auto-index-creation=false

    • the setting will propagate from MongoProperties via MongoDataConfiguration into the MongoMappingContext bean, where it's available as MongoMappingContext#isAutoIndexCreation
    • this is then evaluated in the constructor of MongoTemplate (and ReactiveMongoTemplate) to determine, whether the newly created (Reactive)MongoTemplate should have an instance of MongoPersistentEntityIndexCreator assigned or not
    • if an instance of MongoPersistentEntityIndexCreator is created during the construction of MongoTemplate, the index creation logic will kick-in on object creation (constructor) of MongoPersistentEntityIndexCreator

    References

    • org.springframework.boot.autoconfigure.mongo.MongoProperties#isAutoIndexCreation
    • org.springframework.boot.autoconfigure.data.mongo.MongoDataConfiguration#mongoMappingContext
    • org.springframework.data.mongodb.core.mapping.MongoMappingContext#isAutoIndexCreation
    • org.springframework.data.mongodb.core.MongoTemplate#MongoTemplate
    • org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator#MongoPersistentEntityIndexCreator