索引创建
Spring Data MongoDB 可以自动为带有@Document
. 从版本 3.0 开始,必须显式启用索引创建,以防止对集合生命周期和性能产生不良影响。在应用程序启动时以及在应用程序运行时首次访问实体类型时,会自动为初始实体集创建索引。
我们通常建议为基于应用程序的索引控制显式索引创建,因为 Spring Data 无法为在应用程序运行时重新创建的集合自动创建索引。
IndexResolver
如果要使用@Indexed
注释,例如@GeoSpatialIndexed
,@TextIndexed
,@CompoundIndex
和@WildcardIndexed
. 您可以将索引定义与IndexOperations
以创建索引。创建索引的一个好时间点是在应用程序启动时,特别是在刷新应用程序上下文之后,通过观察触发ContextRefreshedEvent
. 此事件保证上下文已完全初始化。请注意,此时其他组件,尤其是 bean 工厂可能可以访问 MongoDB 数据库。
|
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);
}
}
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
对象。
要打开自动索引创建,请覆盖
|
从 3.0 版开始,默认情况下自动索引创建处于关闭状态。 |
复合指数
还支持复合索引。它们是在类级别定义的,而不是在单个属性上定义的。
复合索引对于提高涉及多个字段条件的查询的性能非常重要 |
下面是一个示例,它创建了lastName
按升序排列,并且age
按降序排列:
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;
}
|
哈希索引
哈希索引允许在分片集群中进行基于哈希的分片。使用哈希字段值对集合进行分片会导致更随机的分布。有关详细信息,请参阅 MongoDB 文档。
下面是一个示例,用于_id
:
@Document
public class DomainType {
@HashIndexed @Id String id;
// ...
}
可以在其他索引定义旁边创建哈希索引,如下所示,在这种情况下,将创建两个索引:
@Document
public class DomainType {
@Indexed
@HashIndexed
String value;
// ...
}
如果上面的示例过于冗长,复合注解允许减少需要在属性上声明的注解数量:
@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 通过通过
|
通配符索引
一个WildcardIndex
是一个索引,可用于包含所有字段或基于给定(通配符)模式的特定字段。有关详细信息,请参阅 MongoDB 文档。
可以使用WildcardIndex
通过IndexOperations
.
mongoOperations
.indexOps(User.class)
.ensureIndex(new WildcardIndex("userMetadata"));
db.user.createIndex({ "userMetadata.$**" : 1 }, {})
这@WildcardIndex
注释允许声明性索引设置,该设置可以与文档类型或属性一起使用。
如果放置在根级域实体的类型上(一个用@Document
) 时,索引解析器将为其创建一个通配符索引。
@Document
@WildcardIndexed
public class Product {
// …
}
db.product.createIndex({ "$**" : 1 },{})
这wildcardProjection
可用于在索引中指定要 in-/exclude 的键。
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
在索引创建过程中被省略。
@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
允许您在每个文档基础上定义语言覆盖。以下示例演示如何创建文本索引并将语言设置为西班牙语:
@Document(language = "spanish")
class SomeEntity {
@TextIndexed String foo;
@Language String lang;
Nested nested;
}
class Nested {
@TextIndexed(weight=5) String bar;
String roo;
}