Java Spring MongoDB @TextIndexed注释不在现有数据库中创建索引

问题描述 投票:0回答:1

我在MongoDB中有集合,我正在尝试使用Spring注释(@TextIndexed)生成文本索引。我没有在应用程序启动时创建数据库,它已经创建了。

问题是 - 索引没有添加到我的数据库中。

注释是否仅在启动应用程序后创建数据库时有效?

谢谢。

春天c。 4.3.2 MongoDB c。 4.0.1

java spring mongodb annotations
1个回答
1
投票

“注释是否仅在启动应用程序后创建数据库时才起作用”?

答案是肯定的。

如果已创建集合,则Spring数据不会初始化索引。我不得不做你想做的事情,我找到的唯一解决方案是使用MongoOperations实例。

  @Autowired
  private MongoOperations mongoOps;

  @PostConstruct
  public void initializeIndexesInDb(){
    mongoOps.indexOps(YourDocumentClass.class).ensureIndex(new Index().on("fieldName", Direction.ASC));
  }
© www.soinside.com 2019 - 2024. All rights reserved.