Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Kotlin Sync 驱动程序

运行Atlas Vector Search查询

在本指南中,您可以学习;了解如何使用Kotlin Sync驾驶员执行 Atlas Vector Search查询。Aggregates构建者类提供了vectorSearch() 辅助方法,可用于创建 $vectorSearch管道阶段。

重要

功能兼容性

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

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

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

  • path:要搜索的字段

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

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

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

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

此示例运行Atlas 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 search
val fieldSearchPath: FieldSearchPath = fieldPath("plot_embedding")
// Creates the vector search pipeline stage with a limit and numCandidates
val 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())
}
{"title": "Berserk: The Golden Age Arc I - The Egg of the King"}
{"title": "Rollerball"}
{"title": "After Life"}
{"title": "What Women Want"}
{"title": "Truth About Demons"}

提示

查询向量类型

前面的示例创建了一个 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")}")
}
Title: Berserk: The Golden Age Arc I - The Egg of the King, Score: 0.49899211525917053
Title: Rollerball, Score: 0.4976102113723755
Title: After Life, Score: 0.4965665936470032
Title: What Women Want, Score: 0.49622756242752075
Title: Truth About Demons, Score: 0.49614521861076355

提示

Vector Search 教程

要查看更多展示如何运行Atlas Vector Search查询的教程,请参阅MongoDB Atlas文档中的Atlas Vector Search教程

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

后退

Atlas Search

在此页面上