Mongo Index not created using @Indexed in Spring Boot

2.7k views Asked by At

I know there are similar questions like this one: Spring boot / mongo wont create index with the index annotation

Also issues in Github like 'spring.data.mongodb.auto-index-creation=true' not working

And also I've tried this Baeldung guide: Spring Data MongoDB – Indexes, Annotations and Converters

So the problem is I'm trying to add an index to an existing collection using @Indexed anotation like this:

@CreatedDate
@Indexed(name="timestamp_index", expireAfterSeconds=100))
private Date timestamp;

The field is a timestamp which is created automatically when an element is inserted into the DB.

Also the class has @Document tag.

So, what have I tried?

Following other answers first thing I did is to add spring.data.mongodb.auto-index-creation: true in this way:

spring:
  data:
    mongodb:
      uri: ${env.mongo-database.url}
      auto-index-creation: true

This not works... but I've also read that the problem can be if I have a AbstractMongoClientConfiguration class.

Currently the project doesn't have that class, but exists a MongoConfiguration class with the @Configuration tag. I don't know if this can interfere or something.

The class is like this:

@Configuration
public class MongoConfiguration { /*creates some beans*/ }

This class create a @Bean named mongodb so I've tried to add manually auto-index to true here:

@Primary
@Bean(name = "mongodb")
@ConfigurationProperties(prefix = "spring.data.mongodb")
public MongoProperties getMongodbProperties() {
    MongoProperties mongoProperties = new MongoProperties();
    mongoProperties.setAutoIndexCreation(true);
    return mongoProperties;
}

But this doesn't work either. The index is not created.

Also this class doesn't extends from AbstractMongoClientConfiguration so I can't override the method autoIndexCreation

Also I can create the index programantically with this code:

mongoTemplate
    .indexOps(PagoDto.class)
    .ensureIndex(new Index().on("timestamp", Sort.Direction.ASC).expire(100));

But for clearer implementation I'd like to do using only annotations in the model.

So the point is: Neither use auto-index-creation in application properties nor trying to add the value into properties works.

Maybe the configuration class doesn't allow to create automatically? It interferes in any way?

I'm not supposed to be authorized to modify the configuration class, if is a little change like call setAutoIndexCreation method there is no problem but I can't change the logic and extends from AbstractMongoClientConfiguration. So the ideal scenario is to get it to work with the annotation @Indexed.

Thanks in advance

0

There are 0 answers