Home > Enterprise >  Why Mongo TTL index is not been creating via Spring Data
Why Mongo TTL index is not been creating via Spring Data

Time:05-17

Problem: mongodb ttl index is not been creating via Spring Data

I have a spring-boot application and MongoDB as database.

I have an entity class:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Document(COLLECTION_NAME)
public class PersonEntity {

    public static final String COLLECTION_NAME = "person_info";
    private static final String PERSON_NAME = "person_name";


    @Id
    private PersonId id;

    @Field(name = PERSON_NAME)
    private String personName;

    
    @Indexed(name = "ttl_index", expireAfterSeconds=20)
    private LocalDateTime date;
}

And I persist a new document to MongoDB using this repository:

public interface SellerRequestInfoRepository extends ReactiveMongoRepository<PersonEntityEntity, PersonId> {}

using

personRepository.save(entity);

But the TTL index is not created on MongoDB after insetting the Person document:

screenshot

Please, advice, what I am doing wrong

CodePudding user response:

I cite the documentation:

Spring Data MongoDB can automatically create indexes for entity types annotated with @Document. Index creation must be explicitly enabled since version 3.0 to prevent undesired effects with collection lifecycle and performance impact.

Did you enable automatic index creation? Because if you didn't, that will most likely be the reason why your index was not created.

With Spring Boot you can enable automatic index creation with the following config in your application.yml:

spring:
  data:
    mongodb:
      auto-index-creation: true

Or if you prefer properties:

spring.data.mongodb.auto-index-creation=true
  • Related