跳到主要内容

索引与集合管理

DeepSeek V3 中英对照 Index and Collection Management

MongoTemplateReactiveMongoTemplate 提供了用于管理索引和集合的方法。这些方法被收集到一个名为 IndexOperationsReactiveIndexOperations 的辅助接口中。你可以通过调用 indexOps 方法并传入集合名称或实体的 java.lang.Class(集合名称从 .class 派生,可以是名称或注解元数据)来访问这些操作。

以下清单展示了 IndexOperations 接口:

public interface IndexOperations {

String ensureIndex(IndexDefinition indexDefinition);

void alterIndex(String name, IndexOptions options);

void dropIndex(String name);

void dropAllIndexes();

List<IndexInfo> getIndexInfo();
}
java

创建索引的方法

你可以使用 MongoTemplate 类在集合上创建索引以提高查询性能,如下例所示:

template.indexOps(Person.class)
.ensureIndex(new Index().on("name",Order.ASCENDING));
java

ensureIndex 确保集合中存在为提供的 IndexDefinition 定义的索引。

你可以使用 IndexDefinitionGeoSpatialIndexTextIndexDefinition 类来创建标准索引、地理空间索引和文本索引。例如,给定前面章节中定义的 Venue 类,你可以声明一个地理空间查询,如下例所示:

template.indexOps(Venue.class)
.ensureIndex(new GeospatialIndex("location"));
java
备注

IndexGeospatialIndex 支持配置 collations

访问索引信息

IndexOperations 接口包含 getIndexInfo 方法,该方法返回一个 IndexInfo 对象列表。此列表包含在集合上定义的所有索引。以下示例在具有 age 属性的 Person 类上定义一个索引:

template.indexOps(Person.class)
.ensureIndex(new Index().on("age", Order.DESCENDING).unique());

List<IndexInfo> indexInfoList = template.indexOps(Person.class)
.getIndexInfo();
java

处理集合的方法

以下示例展示了如何创建一个集合:

MongoCollection<Document> collection = null;
if (!template.getCollectionNames().contains("MyNewCollection")) {
collection = mongoTemplate.createCollection("MyNewCollection");
}
java
备注

集合创建允许使用 CollectionOptions 进行自定义,并支持 collations

与 MongoCollections 交互的方法

  • getCollectionNames:返回一组集合名称。

  • collectionExists:检查是否存在具有给定名称的集合。

  • createCollection:创建一个无上限的集合。

  • dropCollection:删除集合。

  • getCollection:通过名称获取集合,如果不存在则创建它。

时间序列

MongoDB 5.0 引入了时间序列集合,这些集合经过优化,能够高效地存储随时间变化的文档,例如测量数据或事件。这些集合在插入任何数据之前需要以这种方式创建。集合可以通过运行 createCollection 命令、定义时间序列集合选项或从 @TimeSeries 注解中提取选项来创建,如下面的示例所示。

示例 1. 创建一个时间序列集合

template.execute(db -> {

com.mongodb.client.model.CreateCollectionOptions options = new CreateCollectionOptions();
options.timeSeriesOptions(new TimeSeriesOptions("timestamp"));

db.createCollection("weather", options);
return "OK";
});
java
template.createCollection("weather", CollectionOptions.timeSeries("timestamp"));
java
@TimeSeries(collection="weather", timeField = "timestamp")
public class Measurement {

String id;
Instant timestamp;
// ...
}

template.createCollection(Measurement.class);
java

上述代码片段可以轻松转换为响应式 API,提供完全相同的方法。请确保正确 订阅 返回的 publishers。

提示

你可以使用 @TimeSeries#expireAfter 选项让 MongoDB 自动删除过期的桶。该属性支持不同的超时格式,如 10s3h 等,同时也支持表达式(#{@mySpringBean.timeout})和属性占位符(${my.property.timeout})语法。