java - Mongodb 在使用 spring 数据 jpa 插入时强制索引存在

标签 java spring mongodb spring-data-mongodb

我有一个 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/

相关文章:

java - 方法参数返回后 intellij 代码格式无法正确缩进(kotlin 和 Java)

spring - @Secured 注释有效,但带有 PermissionEvaluator 的 @PostAuthorize 无效

node.js - 哈希然后存储token,需要多少成本?

ruby-on-rails - mongoid db 中的 pluck vs distinct。哪个更快?

java - 通过 Java 执行 Mongo like Query (JSON)

java - 用于执行一种方法的 JUnit 套件运行程序

java - 泛型返回类型有什么用

Spring Cloud Stream 不创建队列

java - 无法设置运行java文件的值

spring - 更新对多关联