Overview
このガイドでは、 Kotlin Syncドライバーを使用して Atlas ベクトル検索クエリを実行する方法を説明します。Aggregates
ビルダークラスはvectorSearch()
ヘルパーメソッドを提供し、これを使用して$vectorSearchパイプラインステージを作成できます。
ベクトル検索の実行
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 ドキュメント
このガイドで言及されているメソッドとタイプの詳細については、次のAPIドキュメントを参照してください。