此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Data MongoDB 4.4.4! |
MongoDB 搜索
MongoDB 使用户能够使用专用搜索索引进行关键字或词法搜索以及向量搜索数据。
向量搜索
MongoDB Vector Search 使用$vectorSearch
aggregation 阶段对专用索引运行查询。
请参阅 MongoDB 文档以了解有关 的要求和限制的更多信息vectorSearch
指标。
管理向量索引
SearchIndexOperationsProvider
实施者MongoTemplate
是SearchIndexOperations
提供了各种管理向量索引的方法。
以下代码片段显示了如何为集合创建向量索引
创建向量索引
-
Java
-
Mongo Shell
VectorIndex index = new VectorIndex("vector_index")
.addVector("plotEmbedding"), vector -> vector.dimensions(1536).similarity(COSINE)) (1)
.addFilter("year"); (2)
mongoTemplate.searchIndexOps(Movie.class) (3)
.createIndex(index);
1 | 一个向量索引可以涵盖多个向量嵌入向量,这些向量嵌入向量可以通过addVector 方法。 |
2 | 向量索引可以包含其他字段,以便在运行查询时缩小搜索结果的范围。 |
3 | 获得SearchIndexOperations 绑定到Movie type,用于字段名称映射。 |
db.movie.createSearchIndex("movie", "vector_index",
{
"fields": [
{
"type": "vector",
"numDimensions": 1536,
"path": "plot_embedding", (1)
"similarity": "cosine"
},
{
"type": "filter",
"path": "year"
}
]
}
)
1 | 字段名称plotEmbedding 已映射到plot_embedding 考虑@Field(name = "…") 注解。 |
创建后,向量索引不会立即可供使用,尽管exists
检查返回true
.
搜索索引的实际状态可以通过SearchIndexOperations#status(…)
.
这READY
state 指示索引已准备好接受查询。
查询向量索引
可以通过使用VectorSearchOperation
通过MongoOperations
如以下示例所示
查询向量索引
-
Java
-
Mongo Shell
VectorSearchOperation search = VectorSearchOperation.search("vector_index") (1)
.path("plotEmbedding") (2)
.vector( ... )
.numCandidates(150)
.limit(10)
.quantization(SCALAR)
.withSearchScore("score"); (3)
AggregationResults<MovieWithSearchScore> results = mongoTemplate
.aggregate(newAggregation(Movie.class, search), MovieWithSearchScore.class);
1 | 提供要查询的向量索引的名称,因为一个集合可能包含多个索引。 |
2 | 用于比较的路径的名称。 |
3 | (可选)将具有 given name 的搜索分数添加到结果文档。 |
db.embedded_movies.aggregate([
{
"$vectorSearch": {
"index": "vector_index",
"path": "plot_embedding", (1)
"queryVector": [ ... ],
"numCandidates": 150,
"limit": 10,
"quantization": "scalar"
}
},
{
"$addFields": {
"score": { $meta: "vectorSearchScore" }
}
}
])
1 | 字段名称plotEmbedding 已映射到plot_embedding 考虑@Field(name = "…") 注解。 |