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?
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
MongoProperties
via MongoDataConfiguration
into the MongoMappingContext
bean, where it's available as MongoMappingContext#isAutoIndexCreation
MongoTemplate
(and ReactiveMongoTemplate
) to determine, whether the newly created (Reactive)MongoTemplate
should have an instance of MongoPersistentEntityIndexCreator
assigned or notMongoPersistentEntityIndexCreator
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