Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Kotlin Sync ドライバー

Atlas ベクトル検索クエリの実行

このガイドでは、 Kotlin Syncドライバーを使用して Atlas ベクトル検索クエリを実行する方法を説明します。AggregatesビルダークラスはvectorSearch()ヘルパーメソッドを提供し、これを使用して$vectorSearchパイプラインステージを作成できます。

重要

機能の互換性

この機能をサポートするMongoDB Atlasのどのバージョンについては、 MongoDB Atlasドキュメントの「 制限 」を参照してください。

Atlas ベクトル検索クエリを実行する前に、コレクションに Atlas ベクトル検索インデックスを作成する必要があります。

次に、集計パイプラインで vectorSearch() メソッドを使用して Atlas ベクトル検索クエリを実行できます。 このメソッドは次のパラメーターを受け入れます:

  • path: 検索するフィールド

  • queryVector:検索クエリーを表すベクトル埋め込み

  • indexName: 使用する Atlas ベクトル検索インデックスの名前

  • limit: 返される結果の最大数

  • options: (任意)ベクトル検索クエリーを構成するために使用できるオプションのセット

この例では、次のアクションを実行する Atlas ベクトル検索クエリを実行します。

  • 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"}

Tip

クエリ ベクトル型

上記の例では、クエリベクトルとして機能するために 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

Tip

ベクトル検索チュートリアル

Atlas ベクトル検索クエリの実行方法を示すその他のチュートリアルについては、 MongoDB AtlasドキュメントのAtlas ベクトル検索チュートリアルを参照してください。

このガイドで言及されているメソッドとタイプの詳細については、次のAPIドキュメントを参照してください。

戻る

Atlas Search

項目一覧