MongoDB 搜索
MongoDB 让用户能够使用专用的搜索索引进行关键词或词法搜索,以及向量搜索数据。
向量搜索
MongoDB 向量搜索使用 $vectorSearch 聚合阶段,对专用索引运行查询。关于 vectorSearch 索引的要求与限制,请参阅 MongoDB 文档了解更多信息。
管理向量索引
由 MongoTemplate 实现的 SearchIndexOperationsProvider 是 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);
A vector index may cover multiple vector embeddings that can be added via the
addVectormethod.Vector indexes can contain additional fields to narrow down search results when running queries.
Obtain
SearchIndexOperationsbound to theMovietype which is used for field name mapping.
db.movie.createSearchIndex("movie", "vector_index",
{
"fields": [
{
"type": "vector",
"numDimensions": 1536,
"path": "plot_embedding", // <1>
"similarity": "cosine"
},
{
"type": "filter",
"path": "year"
}
]
}
)
Field name
plotEmbeddinggot mapped toplot_embeddingconsidering a@Field(name = "…")annotation.
向量索引创建后并不会立即可用,尽管 exists 检查返回 true。搜索索引的实际状态可通过 SearchIndexOperations#status(…) 获取。READY 状态表示索引已准备好接受查询。
查询向量索引
可以通过 MongoOperations 发起一个使用 VectorSearchOperation 的聚合来查询向量索引,如下例所示
- 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);
Provide the name of the vector index to query since a collection may hold multiple ones.
The name of the path used for comparison.
Optionally add the search score with given name to the result document.
db.embedded_movies.aggregate([
{
"$vectorSearch": {
"index": "vector_index",
"path": "plot_embedding", // <1>
"queryVector": [ ... ],
"numCandidates": 150,
"limit": 10
}
},
{
"$addFields": {
"score": { $meta: "vectorSearchScore" }
}
}
])
Field name
plotEmbeddinggot mapped toplot_embeddingconsidering a@Field(name = "…")annotation.