此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Data MongoDB 4.5.2! |
MongoDB 搜索
MongoDB 使用户能够使用专用搜索索引进行关键字或词法搜索以及向量搜索数据。
矢量搜索
MongoDB 向量搜索使用$vectorSearch
聚合阶段,用于针对专用索引运行查询。
请参阅 MongoDB 文档以了解有关 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 类型,用于字段名称映射。 |
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)
.withSearchScore("score"); (3)
AggregationResults<MovieWithSearchScore> results = mongoTemplate
.aggregate(newAggregation(Movie.class, search), MovieWithSearchScore.class);
1 | 提供要查询的向量索引的名称,因为一个集合可能包含多个向量索引。 |
2 | 用于比较的路径的名称。 |
3 | (可选)将具有给定名称的搜索分数添加到结果文档中。 |
db.embedded_movies.aggregate([
{
"$vectorSearch": {
"index": "vector_index",
"path": "plot_embedding", (1)
"queryVector": [ ... ],
"numCandidates": 150,
"limit": 10
}
},
{
"$addFields": {
"score": { $meta: "vectorSearchScore" }
}
}
])
1 | 字段名称plotEmbedding 已映射到plot_embedding 考虑@Field(name = "…") 注解。 |