【问题标题】:Spring Boot 2.3.0 - MongoDB Library does not create indexes automaticallySpring Boot 2.3.0 - MongoDB 库不会自动创建索引
【发布时间】:2020-09-24 06:26:23
【问题描述】:

我提供了一个示例项目来说明这个问题:https://github.com/nmarquesantos/spring-mongodb-reactive-indexes

根据spring mongo db文档(https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping-usage):

the @Indexed annotation tells the mapping framework to call createIndex(…) on that property of your document, making searches faster. Automatic index creation is only done for types annotated with @Document.

在我的 Player 类中,我们可以观察到 @Document 和 @Indexed 注解:

@Document
public class Player {

@Id
private String id;

private String playerName;

@Indexed(name = "player_nickname_index", unique = true)
private String nickname;


public Player(String playerName, String nickname) {
    this.id = UUID.randomUUID().toString();
    this.playerName = playerName;
    this.nickname = nickname;
}

public String getPlayerName() {
    return playerName;
}

public void setPlayerName(String playerName) {
    this.playerName = playerName;
}

public String getNickname() {
    return nickname;
}

public void setNickname(String nickname) {
    this.nickname = nickname;
}
}`

在我的应用程序类中,我插入一个元素来检查数据库是否填充成功:

@PostConstruct
public void seedData() {
    var player = new Player("Cristiano Ronaldo", "CR7");

    playerRepository.save(player).subscribe();

}

如果我在运行我的应用程序后检查 MongoDb,我可以看到成功创建的集合和元素。

未创建昵称的唯一索引。我只能看到为 @Id 属性创建的索引。我错过了什么吗?我是否误解了文档?

【问题讨论】:

  • 您是否尝试设置索引名称? @Indexed(name = "nick_name_index")。您是否还尝试将重复项保存到测试索引?
  • 是的,重复项已保存,是的,我已尝试使用名称,没有区别。同样的问题。每次我重新启动应用程序时,都会添加一个具有相同值的新条目。
  • 我已经更新了我的样本,并在索引中添加了一个名称。

标签: spring-boot spring-data-mongodb spring-mongodb


【解决方案1】:

Spring Boot 2.3.0.RELEASE 附带的 Spring Data MongoDB 版本是 3.0.0.RELEASE。从 Spring Data MongoDB 3.0 开始,the auto-index creation is disabled by default.

要启用自动索引创建,请设置 spring.data.mongodb.auto-index-creation = true,或者如果您有自定义 Mongo 配置,请设置 override the method autoIndexCreation

@Configuration
public class CustomMongoConfig extends AbstractMongoClientConfiguration {

  @Override
  public boolean autoIndexCreation() {
    return true;
  }

  // your other configuration
}

【讨论】:

    【解决方案2】:

    我在将 spring boot 版本升级到 2.3.x 并在 config 类上覆盖此方法时遇到了这个问题(上面@yejianfengblue 说的)

      @Override
      public boolean autoIndexCreation() {
        return true;
      }
    

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 2016-06-25
      • 2019-03-31
      • 2020-09-13
      • 2021-09-15
      • 2017-12-17
      • 2016-09-14
      • 2018-12-30
      • 1970-01-01
      相关资源
      最近更新 更多