我有一个 mongodb 集合需要在某个进程启动之前清理,我通过使用 mongoTemplate.dropCollection()
方法来执行此操作,因为它比使用 deleteAll() 方法快得多存储库。
当我引入索引时出现问题,我的模型注释如下:
@Document
public class TestModel {
@Indexed
private String testField;
}
和存储库
public interface TestModelRepository extends MongoRepository<TestModel, String> {
}
这确保索引是在应用程序启动时创建的
我注意到通过使用存储库的 deleteAll() 方法而不是删除集合来保留索引,但我想知道是否有一种方法可以使用 spring-data 来确保在我进行插入时索引就位。
还有任何在删除后基于注释模型重新创建索引的方法将不胜感激。
有点像
mongoTemplate.createIndexes( TestModel.class );
我怎样才能做到这一点?
最佳答案
没有这样的方法
mongoTemplate.createIndexes( TestModel.class );
在删除之前,只需获取 indexInfo,在删除集合之后,重新创建索引。
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);
}
});
关于java - Mongodb 在使用 spring 数据 jpa 插入时强制索引存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48580193/