首页  编辑  

SpringBoot/MongoDB @CompoundIndex 定义的索引没有自动创建

Tags: /超级猛料/Database.数据库相关/   Date Created:
Java, SpringBoot, MongoDB,用 @Indexed 和 @CompoundIndex 定义的索引,没有自动创建?

在Spring MongoDB driver 3.0之后,不会自动创建索引,必须显示指定自动创建索引,配置 application.properties:
spring.data.mongodb.auto-index-creation: true

当然你也可以手动或者自动启动的时候来初始化索引:
Spring Data MongoDB - Reference Documentation

@Configuration public class Config extends AbstractMongoClientConfiguration { @Override public boolean autoIndexCreation() { return true; } // ... }

Example 180. Programmatic Index Creation for a single Domain Type
class MyListener {

  @EventListener(ContextRefreshedEvent.class)
  public void initIndicesAfterStartup() {

    MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext = mongoTemplate
                .getConverter().getMappingContext();

    IndexResolver resolver = new MongoPersistentEntityIndexResolver(mappingContext);

    IndexOperations indexOps = mongoTemplate.indexOps(DomainType.class);
    resolver.resolveIndexFor(DomainType.class).forEach(indexOps::ensureIndex);
  }
}
Example 181. Programmatic Index Creation for all Initial Entities
class MyListener{

  @EventListener(ContextRefreshedEvent.class)
  public void initIndicesAfterStartup() {

    MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext = mongoTemplate
        .getConverter().getMappingContext();

    // consider only entities that are annotated with @Document
    mappingContext.getPersistentEntities()
                            .stream()
                            .filter(it -> it.isAnnotationPresent(Document.class))
                            .forEach(it -> {

    IndexOperations indexOps = mongoTemplate.indexOps(it.getType());
    resolver.resolveIndexFor(it.getType()).forEach(indexOps::ensureIndex);
    });
  }
}