Overview
在本指南中,您可以学习如何使用 Mongoid 运行 MongoDB 向量搜索查询。MongoDB 向量搜索允许您通过使用向量嵌入根据文档的语义含义查询文档。
Mongoid 提供 vector_search 方法,该方法可为您构建并运行 $vectorSearch 聚合阶段。要了解有关 $vectorSearch 聚合阶段的更多信息,请参阅 聚合操作指南。
注意
部署兼容性
要使用 MongoDB 向量搜索,必须连接到 MongoDB Atlas 集群或运行 MongoDB 8.2 或更高版本的自管理部署。
要学习;了解有关MongoDB Vector Search 的更多信息,请参阅Atlas文档中的MongoDB Vector Search 概述。
先决条件
在运行 MongoDB 向量搜索查询之前,必须在模型上定义向量字段和向量搜索索引,然后在集合上创建索引。要了解如何声明和创建向量搜索索引,请参阅索引指南的 MongoDB 向量搜索索引部分。
本指南中的示例使用以下 Movie 模型,该模型映射到 sample_mflix 数据库中的 embedded_movies 集合。plot_embedding 字段存储每部电影情节的向量嵌入。
class Movie include Mongoid::Document store_in collection: "embedded_movies", database: "sample_mflix" field :title, type: String field :plot, type: String field :year, type: Integer field :plot_embedding, type: Array # Declare a vector search index on the `plot_embedding` field. The `_id` # and `year` filter fields enable instance-level and filtered queries. vector_search_index :plot_embedding_index, fields: [ { type: "vector", path: "plot_embedding", numDimensions: 1536, similarity: "cosine" }, { type: "filter", path: "_id" }, { type: "filter", path: "year" } ] end
运行向量搜索查询
要运行 MongoDB 向量搜索查询,请在模型上调用 vector_search 类方法,并将查询向量作为第一个参数传递。查询向量是表示搜索输入的向量嵌入。
以下代码示例在 plot_embedding 字段上运行 MongoDB 向量搜索查询,并打印每个匹配电影的标题。由于 Movie 模型只声明了一个向量搜索索引,因此 Mongoid 会自动选择要使用的索引和向量字段。
# The query vector must have the same number of dimensions as the # vector search index (1536, in this example). query_vector = [ -0.0016261312, -0.028070757, -0.011342932, ..., -0.009710136 ] movies = Movie.vector_search(query_vector, limit: 5) movies.each do |movie| puts movie.title end
vector_search 方法返回 Movie 文档的数组。默认情况下,它返回 10 个最相似的文档。要更改结果数量,请设置 limit 选项。上述示例指定了 5 个结果的限制。
向量搜索分数
vector_search 返回的每个文档都有一个 vector_search_score 属性,该属性描述了文档与查询向量的匹配程度。分数越高,表示匹配程度越高。
以下代码运行与上一示例相同的查询,但打印每个匹配电影的标题和分数:
movies = Movie.vector_search(query_vector, limit: 5) movies.each do |movie| puts "#{movie.title}: #{movie.vector_search_score}" end
搜索类似文档
您还可以在文档实例上调用 vector_search 方法来查找与该文档类似的文档。当您在文档上调用 vector_search 时,Mongoid 会使用文档自身存储的向量作为查询向量,并从结果中排除文档本身。
以下代码可找到与现有 Movie 文档最相似的五部电影:
movie = Movie.find_by(title: "About Time") neighbors = movie.vector_search(limit: 5) neighbors.each do |neighbor| puts neighbor.title end
向量搜索选项
您可以将以下关键字参数传递给 vector_search 方法以自定义查询:
选项 | 类型 | 说明 | 默认值 |
|---|---|---|---|
|
| 要使用的向量搜索索引的名称。仅当模型声明多个向量搜索索引时才需要。 | 从模型推断 |
|
| 包含向量嵌入的字段。仅当无法从索引定义推断向量字段时才需要。 | 从索引推断 |
|
| 要返回的最大文档数。 |
|
|
| 搜索期间要考虑的最近邻数量。 |
|
|
| 在搜索前用于预过滤文档的查询。 | 不过滤 |
|
| 在向量搜索后需要添加的其他聚合阶段。 | 无额外阶段 |
以下代码运行 MongoDB 向量搜索查询,该查询考虑 150 个候选并仅返回在年份 2000 之后发布的电影:
movies = Movie.vector_search( query_vector, limit: 5, num_candidates: 150, filter: { year: { "$gt" => 2000 } } )
To learn more about these options, see the Fields section of the $vectorSearch operator reference in the Atlas documentation.
更多信息
要了解如何声明和创建向量搜索索引,请参阅索引指南的 MongoDB 向量搜索索引部分。
要了解有关本指南中提到的概念的更多信息,请参阅 Atlas 文档中的以下页面:
API 文档
要学习;了解有关本指南中提到的方法的更多信息,请参阅以下API文档: