Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb enforce index presence on insert with spring data jpa

I have a mongodb collection that needs to be cleaned before a certain process starts, i do this by using mongoTemplate.dropCollection() method becouse it is much faster than using the deleteAll() method on the repository.

The problem arises when i introduced indexes, my model is annotated as follows:

@Document
public class TestModel {
    @Indexed
    private String testField;
}

and repository

public interface TestModelRepository extends MongoRepository<TestModel, String> {
}

This makes sure that the index is created at application start time

i noticed that by using the repository's deleteAll() method instead of dropping the collection preserves the index, but i was wondering if there is a way with spring-data to make sure that indexes are in place when i make an insert.

also any method to re-create indexes based on the annotated model after drop would be appreciated.

something like

mongoTemplate.createIndexes( TestModel.class );

How can i achieve this?

like image 316
davide bubz Avatar asked Dec 07 '25 02:12

davide bubz


1 Answers

There is no method like this

mongoTemplate.createIndexes( TestModel.class );

Before deleting, just get the indexInfo and after dropping collection, Recreate the indexes.

List<IndexInfo> indexInfo = mongoTemplate.indexOps(TestModel.class).getIndexInfo();

mongoTemplate.dropCollection(TestModel.class);


indexInfo.forEach(index -> {
  DBObject indexOptions = new BasicDBObject();

  if(! index.getName().equals("_id_"))
  {
    indexOptions.put(index.getName(), 1);
    CompoundIndexDefinition indexDefinition = new CompoundIndexDefinition(indexOptions);
    indexDefinition.named(index.getName());
    mongoTemplate.indexOps(TestModel.class).ensureIndex(indexDefinition);
  }
});
like image 130
pvpkiran Avatar answered Dec 08 '25 15:12

pvpkiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!