跳到主要内容
版本:5.1.1

MongoDB 搜索

Doubao 中英对照 MongoDB Search

MongoDB 让用户能够使用专用的搜索索引进行关键词或词法搜索,以及向量搜索数据。

向量搜索​

MongoDB 向量搜索使用 $vectorSearch 聚合阶段,对专用索引运行查询。关于 vectorSearch 索引的要求与限制,请参阅 MongoDB 文档了解更多信息。

管理向量索引​

由 MongoTemplate 实现的 SearchIndexOperationsProvider 是 SearchIndexOperations 的入口点,后者提供了各种用于管理向量索引的方法。

以下代码片段展示了如何为集合创建向量索引

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 addVector method.

  • Vector indexes can contain additional fields to narrow down search results when running queries.

  • Obtain SearchIndexOperations bound to the Movie type which is used for field name mapping.

向量索引创建后并不会立即可用,尽管 exists 检查返回 true。搜索索引的实际状态可通过 SearchIndexOperations#status(…) 获取。READY 状态表示索引已准备好接受查询。

查询向量索引​

可以通过 MongoOperations 发起一个使用 VectorSearchOperation 的聚合来查询向量索引,如下例所示

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.