定义
vectorSearch操作符对指定字段中的向量嵌入执行 近似最近邻 (ANN) 或 精确最近邻 (ENN) 搜索。使用此操作符可在语义搜索的同时添加分析文本功能,例如模糊搜索、短语匹配、位置过滤器、通配符模式匹配等。
语法
vectorSearch 通过以下语法实现:
{ "$search": { "index": "<index name>", // optional, defaults to "default" "vectorSearch": { "exact": true | false, "filter": {<operator-specification>}, "limit": <number-of-results>, "numCandidates": <number-of-candidates>, "path": "<field-to-search>", "queryVector": [<array-of-numbers>], "score": {<options>} } } }
选项
vectorSearch 使用以下字段来构造查询:
字段 | 类型 | 必要性 | 说明 |
|---|---|---|---|
| 布尔 | Optional | 如果已省略 该标志指定是运行精确最近邻 (ENN) 还是近似最近邻 (ANN) 搜索。值可以是以下值之一:
如果省略,则默认值为 MongoDB Vector Search supports ANN search on Atlas clusters running MongoDB v6.0.11, v7.0.2, or later and ENN search on clusters running MongoDB v6.0.16, v7.0.10, v7.3.2, or later. You can also use MongoDB Vector Search with self-managed or local Atlas deployments that you create with the Atlas CLI. |
| 对象 | Optional | MongoDB Search 操作符用于根据元数据或特定搜索条件预筛选文档。 To learn more, see Pre-Filter. |
| Int | 必需 | |
| Int | Optional | 如果 搜索期间要使用的最近邻数量。值必须小于或等于 ( 我们建议您指定一个至少比要返回的文档数( This overrequest pattern is the recommended way to trade off latency and :recall in your ANN searches, and we recommend tuning this parameter based on your specific dataset size and query requirements. |
| 字符串 | 必需 | 要搜索的索引向量类型字段。 |
| 整数或浮点数的数组 | 必需 | Array of numbers of To learn more about generating BSON 数组大小必须与字段的索引定义中指定的向量( 您必须使用用于嵌入数据的同一模型来嵌入查询。 只要向量子类型相同,您就可以使用全保真向量来查询您的嵌入。这仅在 |
| 对象 | Optional | 分配给匹配搜索词结果的分数。使用以下选项之一修改分数:
有关在查询中使用 |
行为
MongoDB搜索索引
必须使用 vectorSearch 操作符索引要搜索的字段。您可以在 MongoDB 搜索索引定义中为以下类型的字段建立索引:
包含向量嵌入的字段。这是您在查询
path选项中指定的字段。用于预过滤器文档的字段。这些是您在查询
filter选项中指定的字段。
预过滤器
您可以对文档进行预筛选,以缩小语义搜索的范围。在 filter字段中使用任何支持的MongoDB Search操作符来查询和过滤文档。
重要
筛选后的查询通常比其他等效的未筛选查询慢。
您必须在 vector 类型的索引定义中为要筛选数据的字段建立索引。
评分
You can include the score of each document in your search results. Specify the $meta expression with the searchScore value in the $project stage. You can also specify the searchScoreDetails value for the scoreDetails field $meta expression for a detailed breakdown of the score.
要了解更多信息,请参阅结果中的文档进行评分和返回得分详情。
vectorSearch 操作符限制
vectorSearch 操作符必须是查询中的顶级操作符。因此,您不能在以下 MongoDB Search 操作符中使用 vectorSearch 操作符:
You can't use the vectorSearch operator to query fields indexed using a vectorSearch type index.
您不能将以下 $search 选项与 vectorSearch 操作符一起使用:
您无法在 MongoDB Search Playground 中使用 vectorSearch 操作符运行$search查询。
示例
The following examples use the sample_mflix.embedded_movies collection from the sample data. If you load the sample data and create the sample index on the collection, you can run the following ANN and ENN queries against the collection after replacing the <connection-string> and <index-name> placeholders in the queries.