最新的稳定版请使用 Spring Data MongoDB 4.3.1Spring中文文档

最新的稳定版请使用 Spring Data MongoDB 4.3.1Spring中文文档

Spring Data MongoDB可以自动为标注的实体类型创建索引。 自 3.0 版起,必须显式启用索引创建,以防止对集合寿命和性能造成不良影响。 在应用程序启动时以及在应用程序运行时首次访问实体类型时,会自动为初始实体集创建索引。@DocumentSpring中文文档

我们通常建议为基于应用程序的索引控制创建显式索引,因为 Spring Data 无法自动为在应用程序运行时重新创建的集合创建索引。Spring中文文档

IndexResolver如果要使用 、 和 等批注,则为创建编程索引定义提供了抽象。 可以使用索引定义 来创建索引。 创建索引的良好时间点是在应用程序启动时,特别是在刷新应用程序上下文之后,通过观察 . 此事件保证上下文已完全初始化。 请注意,此时其他组件(尤其是 Bean 工厂)可能有权访问 MongoDB 数据库。@Indexed@GeoSpatialIndexed@TextIndexed@CompoundIndex@WildcardIndexedIndexOperationsContextRefreshedEventSpring中文文档

Map除非注释为 -like 属性,否则会跳过,因为映射键必须是索引定义的一部分。由于映射的目的是使用动态键和值,因此无法从静态映射元数据解析键。IndexResolver@WildcardIndexedSpring中文文档

例 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);
    });
  }
}

或者,如果要确保在任何组件能够从应用程序访问数据库之前存在索引和集合,请在返回对象之前声明一个方法并包含上面的代码。@BeanMongoTemplateMongoTemplateSpring中文文档

要打开自动索引创建请覆盖您的配置。autoIndexCreation()Spring中文文档

@Configuration
public class Config extends AbstractMongoClientConfiguration {

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

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

Map除非注释为 -like 属性,否则会跳过,因为映射键必须是索引定义的一部分。由于映射的目的是使用动态键和值,因此无法从静态映射元数据解析键。IndexResolver@WildcardIndexedSpring中文文档

要打开自动索引创建请覆盖您的配置。autoIndexCreation()Spring中文文档

@Configuration
public class Config extends AbstractMongoClientConfiguration {

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

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

复合指数

还支持复合索引。它们是在类级别定义的,而不是在单个属性上定义的。Spring中文文档

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

下面是一个按升序和降序创建复合索引的示例:lastNameageSpring中文文档

例 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可重复用作其容器。@CompoundIndexesSpring中文文档

@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;

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

@CompoundIndex可重复用作其容器。@CompoundIndexesSpring中文文档

@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中文文档

下面是一个为以下项创建哈希索引的示例:_idSpring中文文档

例 4.哈希索引用法示例
@Document
public class DomainType {

  @HashIndexed @Id String id;

  // ...
}

可以在其他索引定义旁边创建哈希索引,如下所示,在这种情况下,将创建两个索引:Spring中文文档

例 5.示例哈希索引与简单索引的用法
@Document
public class DomainType {

  @Indexed
  @HashIndexed
  String value;

  // ...
}

如果上面的示例过于冗长,复合注释可以减少需要在属性上声明的注释数量:Spring中文文档

例 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 通过 手动设置索引来接管更多控制权。IndexOperationsSpring中文文档

mongoOperations.indexOpsFor(Jedi.class)
  .ensureIndex(HashedIndex.hashed("useTheForce"));
1 可能为元注释的某些属性注册别名。

尽管在许多情况下,通过注释创建索引会派上用场,但 cosider 通过 手动设置索引来接管更多控制权。IndexOperationsSpring中文文档

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

通配符索引

A 是一个索引,可用于包含所有字段或基于给定(通配符)模式的特定字段。 有关详细信息,请参阅 MongoDB 文档WildcardIndexSpring中文文档

可以使用 via 以编程方式设置索引。WildcardIndexIndexOperationsSpring中文文档

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

批注允许声明性索引设置,该设置可以与文档类型或属性一起使用。@WildcardIndexSpring中文文档

如果放置在根级域实体(用 )注释的类型上,则索引解析器将创建一个 它的通配符索引。@DocumentSpring中文文档

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

可用于指定索引中 in-/exclude 的键。wildcardProjectionSpring中文文档

例 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@WildcardIndexedSpring中文文档

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

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

文本索引

默认情况下,MongoDB v.2.4 禁用文本索引功能。

创建文本索引允许将多个字段累积到可搜索的全文索引中。 每个集合只能有一个文本索引,因此所有标有 的字段都将合并到此索引中。 可以对属性进行加权,以影响文档得分,从而对结果进行排名。 文本索引的默认语言是 English.To 更改默认语言,将属性设置为所需的任何语言(例如,)。 使用名为 or 的属性,可以在每个文档库上定义语言覆盖。 以下示例演示如何创建文本索引并将语言设置为西班牙语:@TextIndexedlanguage@Document(language="spanish")language@LanguageSpring中文文档

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

    @TextIndexed String foo;

    @Language String lang;

    Nested nested;
}

class Nested {

    @TextIndexed(weight=5) String bar;
    String roo;
}
默认情况下,MongoDB v.2.4 禁用文本索引功能。