对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

运行MongoDB Vector Search 查询

在本指南中,您可以学习如何使用 Kotlin 同步驱动程序执行 MongoDB Vector Search 搜索查询。Aggregates构建者类提供了 vectorSearch() 辅助程序,可用于创建 $vectorSearch 管道阶段。

重要

功能兼容性

要学习;了解哪些版本的MongoDB Atlas支持此功能,请参阅MongoDB Atlas文档中的限制。

在执行MongoDB Vector Search 查询之前,您必须在集合上创建MongoDB Vector Search索引。要学习如何以编程方式创建向量搜索索引,请参阅MongoDB 搜索和向量搜索索引指南。

然后,您可以在聚合管道中使用 vectorSearch() 方法运行MongoDB Vector Search查询。此方法接受以下参数:

  • path:要搜索的字段

  • queryVector:表示搜索查询的向量嵌入

  • indexName:要使用的MongoDB Vector Search索引的名称

  • limit:要返回的最大结果数

  • options:(可选)可用于配置向量搜索查询的一设立选项

此示例运行执行以下操作的MongoDB Vector Search查询:

  • 查询 plot_embedding 向量字段。

  • 将结果限制为 5 个文档。

  • 指定考虑 150 个候选的近似最近邻 (ANN)向量搜索。要学习;了解有关 ANN 搜索的更多信息,请参阅MongoDB Atlas文档中的 ANN 搜索。

val vectorValues = FloatArray(1536) { i -> (i % 10).toFloat() * 0.1f }val queryVector = BinaryVector.floatVector(vectorValues)val indexName = "<vector search index>" // Specifies the path of the field to searchval fieldSearchPath: FieldSearchPath = fieldPath("plot_embedding") // Creates the vector search pipeline stage with a limit and numCandidatesval pipeline: List<Bson> = listOf( vectorSearch( fieldSearchPath, queryVector, indexName, 5L, approximateVectorSearchOptions(150) ), project( Projections.fields( Projections.excludeId(), Projections.include("title") ) )) val results = collection.aggregate(pipeline) results.forEach { doc -> println(doc.toJson())}

提示

查询向量类型

前面的示例创建了一个 BinaryVector实例提供服务查询向量,但您也可以创建 Double 实例的 List。 但是,我们建议您使用 BinaryVector 类型以提高存储效率。

以下示例展示了如何运行与前面的示例相同的向量搜索查询,并打印文档的向量搜索元分数。该分数表示每个文档与查询向量的相关性:

val pipeline: List<Bson> = listOf( vectorSearch( fieldSearchPath, queryVector, indexName, 5L, approximateVectorSearchOptions(150) ), project( Projections.fields( Projections.excludeId(), Projections.include("title"), Projections.metaVectorSearchScore("score") ) )) val results = collection.aggregate(pipeline) results.forEach { doc -> println("Title: ${doc.getString("title")}, Score: ${doc.getDouble("score")}")}

提示

Vector Search 教程

要查看更多演示如何运行MongoDB 向量搜索 搜索查询的教程,请参阅MongoDB Atlas文档中的MongoDB 向量搜索教程。

要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档: