索引创建

Spring Data MongoDB 可以自动为带有@Document. 从版本 3.0 开始,必须显式启用索引创建,以防止对集合生命周期和性能产生不良影响。在应用程序启动时以及在应用程序运行时首次访问实体类型时,会自动为初始实体集创建索引。spring-doc.cadn.net.cn

我们通常建议为基于应用程序的索引控制显式索引创建,因为 Spring Data 无法为在应用程序运行时重新创建的集合自动创建索引。spring-doc.cadn.net.cn

IndexResolver如果要使用@Indexed注释,例如@GeoSpatialIndexed,@TextIndexed,@CompoundIndex@WildcardIndexed. 您可以将索引定义与IndexOperations以创建索引。创建索引的一个好时间点是在应用程序启动时,特别是在刷新应用程序上下文之后,通过观察触发ContextRefreshedEvent. 此事件保证上下文已完全初始化。请注意,此时其他组件,尤其是 bean 工厂可能可以访问 MongoDB 数据库。spring-doc.cadn.net.cn

Map-like 属性被IndexResolver除非用@WildcardIndexed因为映射键必须是索引定义的一部分。由于映射的目的是使用动态键和值,因此无法从静态映射元数据中解析键。spring-doc.cadn.net.cn

示例 1.为单个域类型创建编程索引
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);
  }
}
示例 2.为所有初始实体创建编程索引
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);
    });
  }
}

或者,如果要确保在任何组件能够从应用程序访问数据库之前存在索引和集合,请声明@Bean方法MongoTemplate并在返回MongoTemplate对象。spring-doc.cadn.net.cn

打开自动索引创建,请覆盖autoIndexCreation()在您的配置中。spring-doc.cadn.net.cn

@Configuration
public class Config extends AbstractMongoClientConfiguration {

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

// ...
}
从 3.0 版开始,默认情况下自动索引创建处于关闭状态

复合指数

还支持复合索引。它们是在类级别定义的,而不是在单个属性上定义的。spring-doc.cadn.net.cn

复合索引对于提高涉及多个字段条件的查询的性能非常重要

下面是一个示例,它创建了lastName按升序排列,并且age按降序排列:spring-doc.cadn.net.cn

示例 3.复合索引用法示例
package com.mycompany.domain;

@Document
@CompoundIndex(name = "age_idx", def = "{'lastName': 1, 'age': -1}")
public class Person {

  @Id
  private ObjectId id;
  private Integer age;
  private String firstName;
  private String lastName;

}

@CompoundIndex使用@CompoundIndexes作为其容器。spring-doc.cadn.net.cn

@Document
@CompoundIndex(name = "cmp-idx-one", def = "{'firstname': 1, 'lastname': -1}")
@CompoundIndex(name = "cmp-idx-two", def = "{'address.city': -1, 'address.street': 1}")
public class Person {

  String firstname;
  String lastname;

  Address address;

  // ...
}

哈希索引

哈希索引允许在分片集群中进行基于哈希的分片。使用哈希字段值对集合进行分片会导致更随机的分布。有关详细信息,请参阅 MongoDB 文档spring-doc.cadn.net.cn

下面是一个示例,用于_id:spring-doc.cadn.net.cn

示例 4.散列索引用法示例
@Document
public class DomainType {

  @HashIndexed @Id String id;

  // ...
}

可以在其他索引定义旁边创建哈希索引,如下所示,在这种情况下,将创建两个索引:spring-doc.cadn.net.cn

示例 5.散列索引与简单索引的使用示例
@Document
public class DomainType {

  @Indexed
  @HashIndexed
  String value;

  // ...
}

如果上面的示例过于冗长,复合注解允许减少需要在属性上声明的注解数量:spring-doc.cadn.net.cn

示例 6.组合哈希索引用法示例
@Document
public class DomainType {

  @IndexAndHash(name = "idx...")                            (1)
  String value;

  // ...
}

@Indexed
@HashIndexed
@Retention(RetentionPolicy.RUNTIME)
public @interface IndexAndHash {

  @AliasFor(annotation = Indexed.class, attribute = "name") (1)
  String name() default "";
}
1 可能为元注释的某些属性注册别名。

尽管通过注释创建索引在许多情况下都派上用场,但 cosider 通过通过IndexOperations.spring-doc.cadn.net.cn

mongoOperations.indexOpsFor(Jedi.class)
  .ensureIndex(HashedIndex.hashed("useTheForce"));

通配符索引

一个WildcardIndex是一个索引,可用于包含所有字段或基于给定(通配符)模式的特定字段。有关详细信息,请参阅 MongoDB 文档spring-doc.cadn.net.cn

可以使用WildcardIndex通过IndexOperations.spring-doc.cadn.net.cn

示例 7.编程通配符索引设置
mongoOperations
    .indexOps(User.class)
    .ensureIndex(new WildcardIndex("userMetadata"));
db.user.createIndex({ "userMetadata.$**" : 1 }, {})

@WildcardIndex注释允许声明性索引设置,该设置可以与文档类型或属性一起使用。spring-doc.cadn.net.cn

如果放置在根级域实体的类型上(一个用@Document) 时,索引解析器将为其创建一个通配符索引。spring-doc.cadn.net.cn

示例 8.域类型的通配符索引
@Document
@WildcardIndexed
public class Product {
	// …
}
db.product.createIndex({ "$**" : 1 },{})

wildcardProjection可用于在索引中指定要 in-/exclude 的键。spring-doc.cadn.net.cn

示例 9.通配符索引wildcardProjection
@Document
@WildcardIndexed(wildcardProjection = "{ 'userMetadata.age' : 0 }")
public class User {
    private @Id String id;
    private UserMetadata userMetadata;
}
db.user.createIndex(
  { "$**" : 1 },
  { "wildcardProjection" :
    { "userMetadata.age" : 0 }
  }
)

通配符索引也可以通过将注释直接添加到字段来表示。请注意wildcardProjection不允许在嵌套路径(如属性)上。对用@WildcardIndexed在索引创建过程中被省略。spring-doc.cadn.net.cn

示例 10.属性上的通配符索引
@Document
public class User {
    private @Id String id;

    @WildcardIndexed
    private UserMetadata userMetadata;
}
db.user.createIndex({ "userMetadata.$**" : 1 }, {})

文本索引

MongoDB v.2.4 默认禁用文本索引功能。

创建文本索引允许将多个字段累积到可搜索的全文索引中。每个集合只能有一个文本索引,因此所有字段都标记为@TextIndexed合并到此索引中。可以对属性进行加权,以影响排名结果的文档分数。文本索引的默认语言是 English.To 更改默认语言,请将language属性为您想要的任何语言(例如,@Document(language="spanish")). 使用名为language@Language允许您在每个文档基础上定义语言覆盖。以下示例演示如何创建文本索引并将语言设置为西班牙语:spring-doc.cadn.net.cn

示例 11.示例文本索引用法
@Document(language = "spanish")
class SomeEntity {

    @TextIndexed String foo;

    @Language String lang;

    Nested nested;
}

class Nested {

    @TextIndexed(weight=5) String bar;
    String roo;
}