Docs Menu
Docs Home
/
Atlas
/

ベクトルAtlas Searchのフィールドにインデックスを付ける方法

vectorSearch タイプを使用して、$vectorSearch クエリを実行するためのフィールドにインデックスを作成できます。クエリするベクトル埋め込みのインデックスと、データを事前にフィルタリングするために使用する追加フィールドを定義できます。データをフィルタリングすると、セマンティック検索の範囲が絞り込まれ、マルチテナント環境などで特定のベクトル埋め込みを比較対象から排除するのに役立ちます。

MongoDBmongosh ベクトル検索インデックスを作成するには、 Atlas UI、 Atlas Admin API、Atlas CLI、 、サポートされているMongoDBドライバー を使用できます。

注意

非推奨のknnBeta演算子を使用して、 vectorSearch型のインデックス定義を使用してインデックス付けされたフィールドをクエリすることはできません。

vectorSearch 型のインデックス定義では、単一要素のみを含む配列のインデックスを作成できます。ドキュメントの配列内にフィールドを埋め込み、またはオブジェクトの配列内にフィールドを埋め込むインデックスはできません。ドット表記を使用して、ドキュメント内の埋め込みフィールドにインデックスことができます。同じ埋め込みフィールドを、同じインデックス定義内で複数回インデックスすることはできません。

埋め込みのインデックスを作成する前に、クラスターの効率的なストレージのために、埋め込みをサブタイプ float32int1、または int8 を持つ BSON ベクトルに変換することをお勧めします。詳細については、埋め込みをBSONベクトルに変換する方法を参照してください。

MongoDB ベクトル検索インデックスを使用すると、Atlas クラスターのアイドルノードでリソース消費が上昇する可能性があります。これは、 MongoDB ベクトル検索のさまざまな重要な操作を実行する基礎の mongot プロセスによるものです。アイドルノードでの CPU 使用率は、インデックスの数、複雑さ、サイズによって異なる場合があります。

インデックスのサイズに関する考慮事項について詳しくは、「ベクトルのインデックス作成におけるメモリ要件」を参照してください。

MongoDB ベクトル検索インデックスを定義したコレクションに変更を加えた場合、クエリですぐに最新データを使用できない場合があります。ただし、mongot は変更ストリームをモニターし、保存されたデータのコピーをアップデートするため、 MongoDB ベクトル検索インデックスは結果一貫性を確保します。Atlas UIでインデックス作成された Documents の数を表示して、コレクションへの変更がインデックスに反映されていることを確認できます。

あるいは、コレクションに新しいドキュメントを追加した後に新しいインデックスを作成し、インデックスがクエリ可能になるまで待つこともできます。また、次のようなポーリング ロジックを実装して、インデックスの使用を試みる前にインデックスの準備ができていることを確認することもできます。

console.log("Polling to check if the index is ready. This may take up to a minute.")
let isQueryable = false;
while (!isQueryable) {
const cursor = collection.listSearchIndexes();
for await (const index of cursor) {
if (index.name === result) {
if (index.queryable) {
console.log(`${result} is ready for querying.`);
isQueryable = true;
} else {
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
}
}

MongoDB ベクトル検索インデックスは、 Atlas UI、 、Atlas CLI、 Atlasmongosh 管理API、および次のMongoDBドライバー を使用して作成、管理できます。

MongoDB ドライバー
バージョン

1.28.0 以上

3.11.0 以上

3.1.0 以上

1.16.0 以上

5.2.0 以上

5.2.0 以上

6.6.0 以上

1.20.0 以上

4.7 以上

3.1.0 以上

5.2.0 以上

次の構文は、 vectorSearchインデックス タイプを定義します。

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": "<field-to-index>",
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary",
9 "hnswOptions": {
10 "maxEdges": <number-of-connected-neighbors>,
11 "numEdgeCandidates": <number-of-nearest-neighbors>
12 }
13 },
14 {
15 "type": "filter",
16 "path": "<field-to-index>"
17 },
18 ...
19 ]
20}

MongoDB ベクトル検索インデックス定義には次のフィールドがあります。

オプション
タイプ
必要性
目的

fields

フィールド定義ドキュメントの配列

必須

インデックスへのベクトルフィールドとフィルター フィールドの定義。ドキュメントごとに 1 つの定義。各フィールド定義ドキュメントは、インデックスを作成するフィールドの typepathなどの構成オプションを指定します。

fields 配列には少なくとも 1 つの vector タイプのフィールド定義が含まれている必要があります。配列に追加の filter タイプのフィールド定義を追加して、データを事前にフィルタリングできます。

fields.
type

文字列

必須

$vectorSearchのフィールドをインデックス化するために使用するフィールドタイプ。 次のいずれかの値を指定できます。

  • vector - ベクトル埋め込みを含むフィールドの場合。

  • filter - フィルタリングする追加のフィールド用。ブール値、date、objectId、numeric、string、UUID の値(これらの型の配列を含む)をフィルタリングできます。

詳しくは、「 型についてvector 」と「 filter型について 」を参照してください。

fields.
path

文字列

必須

インデックスを作成するフィールドの名前。ネストされたフィールドの場合は、ドット表記を使用して埋め込みフィールドへのパスを指定します。

fields.
numDimensions

Int

必須

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。このフィールドはvector タイプのフィールドにのみ設定できます。8192 以下の値を指定する必要があります。

量子化ベクトルまたは BinData のインデックス作成には、次のいずれかの値を指定できます。

  • 1 取り込み用の int8 ベクトルの場合は 8192

  • 取り込み用の int1 ベクトルに対する 8 の複数形。

  • 1 自動スカラー量子化の場合は binData(float32) ベクトルは 8192 に、array(float32) ベクトルは

  • 自動バイナリ量子化用の binData(float32) ベクトルと array(float32) ベクトルの 8 の倍数。

選択した埋め込みモデルによってベクトル埋め込みの次元数が決まります。出力の次元数に関して複数のオプションを持つモデルもあります。詳細については、「埋め込みを作成する方法の選択」を参照してください。

fields.
similarity

文字列

必須

上位 K 近傍の検索に使用するベクトル類似度関数。このフィールドはvector タイプのフィールドにのみ設定できます。

次のいずれかの値を指定できます。

  • euclidean - ベクトルの端点間の距離を測定します。

  • cosine - ベクトル間の角度に基づいて類似性を測定します。

  • dotProduct - は cosine と同様の類似性を測定しますが、ベクトルの大きさを考慮します。

詳細については、「 類似性関数について 」を参照してください。

fields.
quantization

文字列

任意

ベクトルの自動ベクトル量子化のタイプ。埋め込みが float または double ベクトルである場合にのみ、この設定を使用してください。

次のいずれかの値を指定できます。

  • none -ベクトル埋め込みの自動量子化がないことを示します。 取り込み用に事前に量子化されたベクトルがある場合は、この設定を使用します。 省略した場合、これはデフォルト値になります。

  • scalar - 値を 1 バイト整数に変換するスカラー量子化を示します。

  • binary - 値を単一ビットに変換する バイナリ量子化を示します。この値を使用するには、numDimensions は 8 の倍数である必要があります。

    精度が重要な場合は、binary の代わりに none または scalar を選択します。

詳細については、「 ベクトル量子化 」を参照してください。

fields.
hnswOptions

オブジェクト

任意

Hierarchical Navigable Small Worldsグラフの構築に使用するパラメーター。省略した場合、は maxEdges パラメーターと numEdgeCandidates パラメーターにデフォルト値を使用します。

重要: これはプレビュー機能として利用できます。デフォルト値を変更すると、 MongoDB ベクトル検索インデックスとクエリに悪影響を影響可能性があります。

fields.
hnswOptions.
maxEdges

Int

任意

Hierarchical Navigable Small Worldsグラフでノードが持つことができるエッジ(または接続)の最大数。値は、両端を含む 16 から 64 までです。省略した場合、デフォルトは 16 になります。例、 の値が 16 の場合、各ノードはHierarchical Navigable Small Worldsグラフのレイヤーに最大 60 個の出力エッジを持つことができます。

数値が大きいほど、グラフの接続がより適切になるため、再現率(検索結果の精度)が向上します。ただし、グラフノードごとに評価する近傍の数であるため、クエリ速度は低下し、各ノードがより多くの接続を保存するためHierarchical Navigable Small Worldsグラフのメモリが増加し、 MongoDB ベクトル検索 がより多くの近傍を評価し、 を調整するためインデックス作成が遅くなります。グラフに追加されたすべての新しいノード。

fields.
hnswOptions.
numEdgeCandidates

Int

任意

クエリ時の numCandidates と同様に、このパラメータは、新しいノードに接続する上で最も近い隣接ノードを見つけるため、評価するノードの最大数を制御します。値は、100 から 3200 の範囲で、両端を含みます。省略した場合、デフォルトは 100 になります。

数値が大きいほど、高品質な接続を持つグラフが提供され、検索品質(リコール)が向上しますが、クエリのレイテンシに悪影響を与える可能性もあります。

インデックス定義の vector フィールドには、次のいずれかのタイプの数値の配列が含まれている必要があります。

  • BSON double

  • BSON BinData vector サブタイプ float32

  • BSON BinData vector サブタイプ int1

  • BSON BinData vector サブタイプ int8

注意

データ用にサブタイプfloat32 int1 またはint8 を持つ BSON BinData ベクトルの生成の詳細については、「事前に量子化されたベクトルを取り込む方法」をご覧ください。

ベクトル フィールドは、fields 配列内の vector タイプとしてインデックスする必要があります。

次の構文は、 vectorフィールド型を定義します。

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": <field-to-index>,
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary",
9 "hnswOptions": {
10 "maxEdges": <number-of-connected-neighbors>,
11 "numEdgeCandidates": <number-of-nearest-neighbors>
12 }
13 },
14 ...
15 ]
16}

MongoDB ベクトル検索 は次の類似性関数をサポートしています。

  • euclidean - ベクトルの端点間の距離を測定します。この値により、さまざまな次元に基づいて類似性を測定できます。詳しくは、「Euclidean」を参照してください。

  • cosine - ベクトル間の角度に基づいて類似性を測定します。 この値により、大きさでスケーリングされない類似性を測定できます。 cosine では絶対値ゼロのベクトルは使用できません。 コサイン類似度を測定するには、ベクトルを正規化し、代わりに dotProduct を使用することをお勧めします。

  • dotProduct - cosineと同様の類似性を測定しますが、ベクトルの大きさを考慮します。 大きさを正規化すると、類似性の測定においてcosinedotProductはほぼ同じになります。

    dotProduct を使用するには、インデックス作成時とクエリ時にベクトルを単位の長さで正規化する必要があります。

次の表は、さまざまなタイプの類似性関数を示しています。

ベクトル埋め込みタイプ
euclidean
cosine
dotProduct

binData(int1)

binData(int8)

binData(float32)

array(float32)

ベクトル取り込み用。

自動スカラーまたはバイナリ定量化用。

最高のパフォーマンスを得るには、埋め込みモデルをチェックして、どの類似度関数が埋め込みモデルの訓練プロセスと一致するかを判断します。 ガイダンスがない場合は、dotProduct から開始してください。 fields.similaritydotProduct の値に設定すると、角度と大きさの両方に基づいて類似性を効率的に測定できます。 dotProductcosine よりも計算リソースの消費量が少なく、ベクトルが単位の長さの場合に効率的です。 ただし、ベクトルが正規化されていない場合は、サンプルクエリの結果の類似性スコアを euclidean 距離と cosine 類似性について評価して、どれが妥当な結果に対応しているかを判断してください。

データを事前にフィルタリングするために追加フィールドにインデックスを作成することもオプションで可能です。ブール値、date、objectId、numeric、string、UUID の値(これらの型の配列を含む)をフィルタリングできます。データをフィルタリングすると、セマンティック検索の範囲が絞り込まれ、すべてのベクトルが比較対象とならないように徹底するのに役立ちます。類似性比較の実行対象となるドキュメント数が減るため、クエリのレイテンシの短縮と検索結果の精度向上を図ることができます。

fields 配列内で filter タイプを使用して、フィルタリングするフィールドをインデックス必要があります。

次の構文は、 filterフィールド型を定義します。

1{
2 "fields":[
3 {
4 "type": "vector",
5 ...
6 },
7 {
8 "type": "filter",
9 "path": "<field-to-index>"
10 },
11 ...
12 ]
13}

注意

データを事前にフィルタリングしても、 MongoDB ベクトル検索 が クエリに$vectorSearchScore $vectorSearchを使用して返すスコアには影響しません。

Atlas UI、 Atlas 管理API 、 Atlas CLI を使用して、クラスター上の任意の種類のデータに対して、長さが 8192 次元以下のベクトル埋め込みを含むすべてのコレクションに対するMongoDB ベクトル検索インデックスを作成できます。mongosh、またはサポートされているMongoDBドライバー。

MongoDB ベクトル検索インデックスを作成するには、次の前提条件を持つクラスターが必要です。

  • MongoDB バージョン6.0.117.0.2 、または 以上

  • MongoDB ベクトル検索インデックスの作成対象のコレクション

注意

mongosh コマンドまたはドライバーヘルパーメソッドを使用して、すべての Atlas クラスター階層にMongoDB ベクトル検索インデックスを作成できます。サポートされているドライバー バージョンのリストについては、 サポートされているクライアント を参照してください。

Project Data Access AdminMongoDB ベクトル検索インデックスを作成および管理するには、 以上のロールが必要です。

インデックス作成数の上限は以下のとおりです。

  • M0クラスターの3インデックス (タイプに関係なく、searchまたはvector)。

  • Flex クラスターで 10 インデックス。

単一の M10+ クラスターには、2,500 以下の検索インデックスを作成することを推奨します。


➤ [言語を選択 ] ドロップダウン メニューを使用して、インデックスの作成に使用するクライアントを選択します。


注意

この手順には、sample_mflixデータベース内の embedded_moviesコレクションのインデックス定義の例が含まれています。サンプルデータを クラスターにロードし、このコレクションの例MongoDB ベクトル検索インデックスを作成すると、このコレクションに対してサンプル$vectorSearch クエリを実行できます。実行できるサンプルクエリの詳細については、$vectorSearch の例 を参照してください。

Atlas APIを使用してコレクションのMongoDB ベクトル検索インデックスを作成するには、必要なパラメータを指定してMongoDB Search indexes エンドポイントに POSTリクエストを送信します。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "<name-of-database>",
9 "collectionName": "<name-of-collection>",
10 "type": "vectorSearch",
11 "name": "<index-name>",
12 "definition": {
13 "fields":[
14 {
15 "type": "vector",
16 "path": <field-to-index>,
17 "numDimensions": <number-of-dimensions>,
18 "similarity": "euclidean | cosine | dotProduct"
19 },
20 {
21 "type": "filter",
22 "path": "<field-to-index>"
23 },
24 ...
25 }
26 ]
27 }'

エンドポイントの構文とパラメータの詳細については、 MongoDB Search インデックスを 1 つ作成する を参照してください。

次のインデックス定義は「plot_embedding_voyage_3_large」フィールドを vector タイプとしてインデックスします。「plot_embedding_voyage_3_large」フィールドには、Voyage AI の voyage-3-large 埋め込みモデルを使用して作成された 2048次元ベクトル埋め込みが含まれています。インデックスは dotProduct 関数を使用して類似性を測定します。

次のインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールドのみをインデックスします。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "sample_mflix",
9 "collectionName": "embedded_movies",
10 "type": "vectorSearch",
11 "name": "vector_index",
12 "definition: {
13 "fields":[
14 {
15 "type": "vector",
16 "path": "plot_embedding_voyage_3_large",
17 "numDimensions": 2048,
18 "similarity": "dotProduct"
19 }
20 ]
21 }
22 }'

このインデックス定義は、次のフィールドをインデックスします。

  • データを事前にフィルタリングするためのstringフィールド(genres)と数値フィールド(year)。

  • 事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド( plot_embedding_voyage_3_large )。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "sample_mflix",
9 "collectionName": "embedded_movies",
10 "type": "vectorSearch",
11 "name": "vector_index",
12 "definition: {
13 "fields":[
14 {
15 "type": "vector",
16 "path": "plot_embedding_voyage_3_large",
17 "numDimensions": 2048,
18 "similarity": "dotProduct"
19 },
20 {
21 "type": "filter",
22 "path": "genres"
23 },
24 {
25 "type": "filter",
26 "path": "year"
27 }
28 ]
29 }
30 }'

Atlas CLI v1.14.3 以降を使用してコレクションのMongoDB ベクトル検索インデックスを作成するには、次の手順を実行します。

1

インデックス定義は、次の形式のようになります。

1{
2 "database": "<name-of-database>",
3 "collectionName": "<name-of-collection>",
4 "type": "vectorSearch",
5 "name": "<index-name>",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "<field-to-index>",
10 "numDimensions": <number-of-dimensions>,
11 "similarity": "euclidean | cosine | dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "<field-to-index>"
16 },
17 ...
18 ]
19}

vector-index.jsonという名前のファイルを作成します。

2

<name-of-database>

インデックスを作成するコレクションを含むデータベース。

<name-of-collection>

インデックスを作成するコレクション。

<index-name>

インデックスの名前。インデックス名を省略すると、 MongoDB ベクトル検索 はインデックスに vector_index という名前を付けます。

<number-of-dimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<field-to-index>

インデックスするベクトル フィールドとフィルター フィールド。

次のインデックス定義をコピーして、vector-index.jsonファイルに貼り付けます。次のインデックス定義は、 MongoDB ベクトル検索インデックスで、plot_embedding_voyage_3_largeフィールドをvector タイプとしてインデックス化し、genres フィールドと year フィールドを filter タイプとしてインデックス化します。plot_embedding_voyage_3_largeフィールドには、Voyage AI の voyage-3-large 埋め込みモデルを使用して作成された 2048ベクトル次元埋め込みが含まれています。インデックスは、dotProduct 関数を使用して類似性測定を指定します。

次のインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールドのみをインデックスします。

1{
2 "database": "sample_mflix",
3 "collectionName": "embedded_movies",
4 "type": "vectorSearch",
5 "name": "vector_index",
6 "fields": [
7 {
8 "type": "vector",
9 "path": "plot_embedding_voyage_3_large",
10 "numDimensions": 2048,
11 "similarity": "dotProduct"
12 }
13 ]
14}

このインデックス定義は、次のフィールドをインデックスします。

  • データを事前にフィルタリングするためのstringフィールド(genres)と数値フィールド(year)。

  • 事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド( plot_embedding_voyage_3_large )。

1{
2 "database": "sample_mflix",
3 "collectionName": "embedded_movies",
4 "type": "vectorSearch",
5 "name": "vector_index",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "plot_embedding_voyage_3_large",
10 "numDimensions": 2048,
11 "similarity": "dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "genres"
16 },
17 {
18 "type": "filter",
19 "path": "year"
20 }
21 ]
22}
3
atlas clusters search indexes create --clusterName [cluster_name] --file [vector_index].json

コマンドで、次のプレースホルダー値を置き換えます。

  • cluster_name は、インデックスを作成するコレクションを含むクラスターの名前です。

  • vector_index は、 MongoDB ベクトル検索インデックスのインデックス定義を含むJSONファイルの名前です。

atlas clusters search indexes create --clusterName [cluster_name] --file vector-index.json

コマンド構文とパラメーターについて詳しくは、Atlas CLI ドキュメントのAtlas クラスター検索インデックス作成コマンド を参照してください。

1

MongoDB Search ページには、Search & Vector Search オプションまたは Data Explorer から移動できます。

2
3

ページで次の選択を行い、Next をクリックしてください。

Search Type

Vector Search のインデックスタイプを選択します。

Index Name and Data Source

以下の情報を指定してください。

  • Index Name: vector_index はデフォルトのインデックス名です。インデックス名は、インデックスの種類に関係なく、名前空間内で一意である必要があります。このコレクションに vector_index という名前のインデックスがすでに存在する場合は、別の名前を入力してください。

  • Database and Collection:

    • インデックスを作成するデータベースを選択してください。例: sample_mflix

    • インデックスを作成するコレクションを選択してください。例: embedded_movies

Configuration Method

For a guided experience, select Visual Editor.

To edit the raw index definition, select JSON Editor.

重要:

MongoDB Searchインデックスの名前はデフォルトで default です。この名前を維持する場合、インデックスは、演算子に別の index オプションを指定していないMongoDB Search クエリのデフォルトの検索インデックスになります。複数のインデックスを作成する場合は、インデックス間で一貫した記述的な命名規則を維持することをお勧めします。

4

Atlas は、ベクトル埋め込みを含むフィールドとその対応する次元を自動的に検出し、最大 3 つのベクトルフィールドを事前に入力します。インデックスを設定するには、次の操作を行う必要があります。

  1. 必要に応じて、[Path] ドロップダウンからインデックスを作成するベクトルフィールドを選択してください。

    [Add Another Field] を選択して、追加フィールドにインデックスを作成します。

  2. [Similarity Method] ドロップダウンメニューで、各インデックスフィールドの類似度メソッドを指定してください。

  3. (任意)[Advanced] をクリックし、ドロップダウンメニューから [Scalar] または [Binary] の量子化を選択して、フィールド内の埋め込みを自動的に量子化します。

  4. (任意)コレクション内の他のフィールドを指定して、「Filter Field」セクションでデータをフィルタリングします。

MongoDB ベクトル検索インデックス設定の詳細については、「ベクトル検索のフィールドにインデックスを作成する方法」を参照してください。

embedded_movies コレクションでは、plot_embedding_voyage_3_large フィールドが表示されます。

インデックスを構成するには、Similarity Method ドロップダウンから Dot Product を選択します。

このインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールド(plot_embedding_voyage_3_large)のみをインデックスします。

embedded_movies コレクションでは、plot_embedding_voyage_3_large フィールドが表示されます。

インデックスを設定するには、次の操作を行う必要があります。

  1. Similarity MethodドロップダウンからDot Productを選択します。

  2. [Advanced] をクリックして、ドロップダウンメニューから Scalar 量子化を選択します。

  3. Filter Field セクションで、genres フィールドと year フィールドを指定してデータをフィルタリングします。

このインデックス定義は、次のフィールドをインデックスします。

  • データを事前にフィルタリングするためのstringフィールド(genres)と数値フィールド(year)。

  • 事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド( plot_embedding_voyage_3_large )。

また、埋め込みの効率的な処理のために自動量子化(scalar)を有効にします。

MongoDB ベクトル検索インデックスは次の例のようになります。

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": <field-to-index>,
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary"
9 },
10 {
11 "type": "filter",
12 "path": "<field-to-index>"
13 },
14 ...
15 ]
16}

インデックス内のフィールドの詳細については、 「ベクトル検索のフィールドにインデックスを作成する方法」 を参照してください。

次のインデックス定義は「plot_embedding_voyage_3_large」フィールドを vector タイプとしてインデックスします。「plot_embedding_voyage_3_large」フィールドには、Voyage AI の voyage-3-large 埋め込みモデルを使用して作成された 2048次元ベクトル埋め込みが含まれています。インデックスは dotProduct 関数を使用して類似性を測定します。

次のインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールドのみをインデックスします。

1{
2 "fields": [{
3 "type": "vector",
4 "path": "plot_embedding_voyage_3_large",
5 "numDimensions": 2048,
6 "similarity": "dotProduct"
7 }]
8}

このインデックス定義は、次のフィールドをインデックスします。

  • データを事前にフィルタリングするためのstringフィールド(genres)と数値フィールド(year)。

  • 事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド( plot_embedding_voyage_3_large )。

また、埋め込みの効率的な処理のために自動量子化(scalar)を有効にします。

1{
2 "fields": [{
3 "type": "vector",
4 "path": "plot_embedding_voyage_3_large",
5 "numDimensions": 2048,
6 "similarity": "dotProduct",
7 "quantization": "scalar"
8 },
9 {
10 "type": "filter",
11 "path": "genres"
12 },
13 {
14 "type": "filter",
15 "path": "year"
16 }]
17}
5
6

Atlas は、インデックスが作成中であることを知らせるモーダル ウィンドウを表示します。

7
8

新しく作成したインデックスは Atlas Search タブに表示されます。インデックスを作成する間、Status フィールドには Build in Progress と表示されます。インデックスの作成が完了すると、Status フィールドの表示は Active になります。

注意

コレクションが大きいほど、インデックスの作成に時間がかかります。インデックスの作成が完了すると、メール通知が届きます。

mongosh v2.1.2 以降を使用してコレクションのMongoDB ベクトル検索インデックスを作成するには、次の手順を実行します。

1

詳細については、「mongosh経由でクラスターに接続する」を参照してください。

2

use sample_mflix
switched to db sample_mflix
3

db.collection.createSearchIndex()メソッドの構文は次のとおりです。

1db.<collectionName>.createSearchIndex(
2 "<index-name>",
3 "vectorSearch", //index type
4 {
5 fields: [
6 {
7 "type": "vector",
8 "numDimensions": <number-of-dimensions>,
9 "path": "<field-to-index>",
10 "similarity": "euclidean | cosine | dotProduct"
11 },
12 {
13 "type": "filter",
14 "path": "<field-to-index>"
15 },
16 ...
17 ]
18 }
19);

次のインデックス定義は「plot_embedding_voyage_3_large」フィールドを vector タイプとしてインデックスします。「plot_embedding_voyage_3_large」フィールドには、Voyage AI の voyage-3-large 埋め込みモデルを使用して作成された 2048次元ベクトル埋め込みが含まれています。インデックスは dotProduct 関数を使用して類似性を測定します。

次のインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールドのみをインデックスします。

1db.embedded_movies.createSearchIndex(
2 "vector_index",
3 "vectorSearch",
4 {
5 "fields": [
6 {
7 "type": "vector",
8 "path": "plot_embedding_voyage_3_large",
9 "numDimensions": 2048,
10 "similarity": "dotProduct",
11 "quantization": "scalar"
12 }
13 ]
14 }
15);

このインデックス定義は、次のフィールドをインデックスします。

  • データを事前にフィルタリングするためのstringフィールド(genres)と数値フィールド(year)。

  • 事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド( plot_embedding_voyage_3_large )。

1db.embedded_movies.createSearchIndex(
2 "vector_index",
3 "vectorSearch",
4 {
5 "fields": [
6 {
7 "type": "vector",
8 "path": "plot_embedding_voyage_3_large",
9 "numDimensions": 2048,
10 "similarity": "dotProduct"
11 },
12 {
13 "type": "filter",
14 "path": "genres"
15 },
16 {
17 "type": "filter",
18 "path": "year"
19 }
20 ]
21 }
22);

C# ドライバー v3.1.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを作成するには、次の手順を実行します。

1
1using MongoDB.Bson;
2using MongoDB.Driver;
3using System;
4using System.Threading;
5
6// Connect to your Atlas deployment
7private const string MongoConnectionString = "<connectionString>";
8var client = new MongoClient(MongoConnectionString);
9
10// Access your database and collection
11var database = client.GetDatabase("<databaseName>");
12var collection = database.GetCollection<BsonDocument>("<collectionName>");
13
14// Create your index model, then create the search index
15var name = "<indexName>";
16var type = SearchIndexType.VectorSearch;
17
18var definition = new BsonDocument
19{
20 { "fields", new BsonArray
21 {
22 new BsonDocument
23 {
24 { "type", "vector" },
25 { "path", "<fieldToIndex>" },
26 { "numDimensions", <numberOfDimensions> },
27 { "similarity", "euclidean | cosine | dotProduct" }
28 }
29 }
30 }
31};
32
33var model = new CreateSearchIndexModel(name, type, definition);
34
35var searchIndexView = collection.SearchIndexes;
36searchIndexView.CreateOne(model);
37Console.WriteLine($"New search index named {name} is building.");
38
39// Wait for initial sync to complete
40Console.WriteLine("Polling to check if the index is ready. This may take up to a minute.");
41bool queryable = false;
42while (!queryable)
43{
44 var indexes = searchIndexView.List();
45 foreach (var index in indexes.ToEnumerable())
46 {
47 if (index["name"] == name)
48 {
49 queryable = index["queryable"].AsBoolean;
50 }
51 }
52 if (!queryable)
53 {
54 Thread.Sleep(5000);
55 }
56}
57Console.WriteLine($"{name} is ready for querying.");
1using MongoDB.Bson;
2using MongoDB.Driver;
3using System;
4using System.Threading;
5
6// Connect to your Atlas deployment
7private const string MongoConnectionString = "<connectionString>";
8var client = new MongoClient(MongoConnectionString);
9
10// Access your database and collection
11var database = client.GetDatabase("<databaseName>");
12var collection = database.GetCollection<BsonDocument>("<collectionName>");
13
14// Create your index models and add them to an array
15var type = SearchIndexType.VectorSearch;
16
17var definitionOne = new BsonDocument
18{
19 { "fields", new BsonArray
20 {
21 new BsonDocument
22 {
23 { "type", "vector" },
24 { "path", "<fieldToIndex>" },
25 { "numDimensions", <numberOfDimensions> },
26 { "similarity", "euclidean | cosine | dotProduct" }
27 }
28 }
29 }
30};
31var modelOne = new CreateSearchIndexModel("<indexName>", type, definitionOne);
32
33var definitionTwo = new BsonDocument
34{
35 { "fields", new BsonArray
36 {
37 new BsonDocument
38 {
39 { "type", "vector" },
40 { "path", "<fieldToIndex>" },
41 { "numDimensions", <numberOfDimensions> },
42 { "similarity", "euclidean | cosine | dotProduct" }
43 }
44 }
45 }
46};
47var modelTwo = new CreateSearchIndexModel("<indexName>", type, definitionTwo);
48
49var models = new CreateSearchIndexModel[] { modelOne, modelTwo };
50
51// Create the search indexes
52var searchIndexView = collection.SearchIndexes;
53searchIndexView.CreateMany(models);
54
55Console.WriteLine($"New search indexes are building. This may take up to a minute.");

IndexService.csという名前のファイルを作成します。

2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

<numberOfDimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<fieldToIndex>

インデックスするベクトル フィールドとフィルター フィールド。

以下をコピーして IndexService.cs に貼り付け、<connectionString> プレースホルダー値を置き換えます。次のインデックス定義は、 MongoDB ベクトル検索インデックスで、plot_embedding_voyage_3_largeフィールドをvector タイプとしてインデックス化し、genres フィールドと year フィールドを filter タイプとしてインデックス化します。plot_embedding_voyage_3_largeフィールドには、Voyage AI の voyage-3-large 埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義では、2048ベクトル次元を指定し、dotProduct 関数を使用して類似性を測定します。

次のインデックス定義は、ベクトル検索を実行するためにベクトル埋め込みフィールド( plot_embedding_voyage_3_large )のみをインデックスします。

1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5using System;
6using System.Threading;
7
8public class IndexService
9{
10 // Replace the placeholder with your Atlas connection string
11 private const string MongoConnectionString = "<connectionString>";
12 public void CreateVectorIndex()
13 {
14 try
15 {
16 // Connect to your Atlas cluster
17 var client = new MongoClient(MongoConnectionString);
18 var database = client.GetDatabase("sample_mflix");
19 var collection = database.GetCollection<BsonDocument>("embedded_movies");
20
21 var searchIndexView = collection.SearchIndexes;
22 var name = "vector_index";
23 var type = SearchIndexType.VectorSearch;
24
25 var definition = new BsonDocument
26 {
27 { "fields", new BsonArray
28 {
29 new BsonDocument
30 {
31 { "type", "vector" },
32 { "path", "plot_embedding_voyage_3_large" },
33 { "numDimensions", 2048 },
34 { "similarity", "dotProduct" },
35 { "quantization", "scalar" }
36 }
37 }
38 }
39 };
40
41 var model = new CreateSearchIndexModel(name, type, definition);
42
43 searchIndexView.CreateOne(model);
44 Console.WriteLine($"New search index named {name} is building.");
45
46 // Polling for index status
47 Console.WriteLine("Polling to check if the index is ready. This may take up to a minute.");
48 bool queryable = false;
49 while (!queryable)
50 {
51 var indexes = searchIndexView.List();
52 foreach (var index in indexes.ToEnumerable())
53 {
54 if (index["name"] == name)
55 {
56 queryable = index["queryable"].AsBoolean;
57 }
58 }
59 if (!queryable)
60 {
61 Thread.Sleep(5000);
62 }
63 }
64 Console.WriteLine($"{name} is ready for querying.");
65 }
66 catch (Exception e)
67 {
68 Console.WriteLine($"Exception: {e.Message}");
69 }
70 }
71}

このインデックス定義は、次のフィールドをインデックスします。

  • データを事前にフィルタリングするためのstringフィールド(genres)と数値フィールド(year)。

  • 事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド( plot_embedding_voyage_3_large )。

1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5using System;
6using System.Threading;
7
8public class IndexService
9{
10 // Replace the placeholder with your Atlas connection string
11 private const string MongoConnectionString = "<connection-string>";
12 public void CreateVectorIndex()
13 {
14 try
15 {
16 // Connect to your Atlas cluster
17 var client = new MongoClient(MongoConnectionString);
18 var database = client.GetDatabase("sample_mflix");
19 var collection = database.GetCollection<BsonDocument>("embedded_movies");
20
21 var searchIndexView = collection.SearchIndexes;
22 var name = "vector_index";
23 var type = SearchIndexType.VectorSearch;
24
25 var definition = new BsonDocument
26 {
27 { "fields", new BsonArray
28 {
29 new BsonDocument
30 {
31 { "type", "vector" },
32 { "path", "plot_embedding_voyage_3_large" },
33 { "numDimensions", 2048 },
34 { "similarity", "dotProduct" },
35 { "quantization", "scalar"}
36 },
37 new BsonDocument
38 {
39 {"type", "filter"},
40 {"path", "genres"}
41 },
42 new BsonDocument
43 {
44 {"type", "filter"},
45 {"path", "year"}
46 }
47 }
48 }
49 };
50
51 var model = new CreateSearchIndexModel(name, type, definition);
52
53 searchIndexView.CreateOne(model);
54 Console.WriteLine($"New search index named {name} is building.");
55
56 // Polling for index status
57 Console.WriteLine("Polling to check if the index is ready. This may take up to a minute.");
58 bool queryable = false;
59 while (!queryable)
60 {
61 var indexes = searchIndexView.List();
62 foreach (var index in indexes.ToEnumerable())
63 {
64 if (index["name"] == name)
65 {
66 queryable = index["queryable"].AsBoolean;
67 }
68 }
69 if (!queryable)
70 {
71 Thread.Sleep(5000);
72 }
73 }
74 Console.WriteLine($"{name} is ready for querying.");
75 }
76 catch (Exception e)
77 {
78 Console.WriteLine($"Exception: {e.Message}");
79 }
80 }
81}
3
using query_quick_start;
var indexService = new IndexService();
indexService.CreateVectorIndex();
4
dotnet run

MongoDB Goドライバー v2.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを作成するには、次の手順を実行します。

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/bson"
9 "go.mongodb.org/mongo-driver/v2/mongo"
10 "go.mongodb.org/mongo-driver/v2/mongo/options"
11)
12
13func main() {
14 ctx := context.Background()
15
16 // Replace the placeholder with your Atlas connection string
17 const uri = "<connectionString>"
18
19 // Connect to your Atlas cluster
20 clientOptions := options.Client().ApplyURI(uri)
21 client, err := mongo.Connect(clientOptions)
22 if err != nil {
23 log.Fatalf("failed to connect to the server: %v", err)
24 }
25 defer func() { _ = client.Disconnect(ctx) }()
26
27 // Set the namespace
28 coll := client.Database("<databaseName>").Collection("<collectionName>")
29
30 // Define the index details
31 type vectorDefinitionField struct {
32 Type string `bson:"type"`
33 Path string `bson:"path"`
34 NumDimensions int `bson:"numDimensions"`
35 Similarity string `bson:"similarity"`
36 }
37
38 type vectorDefinition struct {
39 Fields []vectorDefinitionField `bson:"fields"`
40 }
41
42 indexName := "<indexName>"
43 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
44
45 indexModel := mongo.SearchIndexModel{
46 Definition: vectorDefinition{
47 Fields: []vectorDefinitionField{{
48 Type: "vector",
49 Path: "<fieldToIndex>",
50 NumDimensions: <numberOfDimensions>,
51 Similarity: "euclidean | cosine | dotProduct"}},
52 },
53 Options: opts,
54 }
55
56 // Create the index
57 log.Println("Creating the index.")
58 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
59 if err != nil {
60 log.Fatalf("failed to create the search index: %v", err)
61 }
62
63 // Await the creation of the index.
64 log.Println("Polling to confirm successful index creation.")
65 log.Println("NOTE: This may take up to a minute.")
66 searchIndexes := coll.SearchIndexes()
67 var doc bson.Raw
68 for doc == nil {
69 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
70 if err != nil {
71 fmt.Errorf("failed to list search indexes: %w", err)
72 }
73
74 if !cursor.Next(ctx) {
75 break
76 }
77
78 name := cursor.Current.Lookup("name").StringValue()
79 queryable := cursor.Current.Lookup("queryable").Boolean()
80 if name == searchIndexName && queryable {
81 doc = cursor.Current
82 } else {
83 time.Sleep(5 * time.Second)
84 }
85 }
86
87 log.Println("Name of Index Created: " + searchIndexName)
88}

注意

プログラムによるインデックス作成

MongoDB Goドライバーは、v1.16.0 以降のプログラムによるMongoDB ベクトル検索インデックス管理をサポートしています。ただし、前のコードは v2.x の構文を示しています。ドライバー。

2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

<numberOfDimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<fieldToIndex>

インデックスするベクトル フィールドとフィルター フィールド。

以下をコピーして create-index.goファイルに貼り付け、<connectionString> プレースホルダー値を置き換えます。次のインデックス定義は、 MongoDB ベクトル検索インデックスで、plot_embedding_voyage_3_large``フィールドをvector タイプとしてインデックス化し、genres フィールドと year フィールドを filter タイプとしてインデックス化します。plot_embedding_voyage_3_large``フィールドには、Voyage AI の voyage-3-large 埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義では、2048ベクトル次元を指定し、dotProduct 関数を使用して類似性を測定します。

次のインデックス定義は、ベクトル検索を実行するためにベクトル埋め込みフィールド( plot_embedding_voyage_3_large`` )のみをインデックスします。

1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7 "time"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("sample_mflix").Collection("embedded_movies")
30
31 // Define the index details
32 type vectorDefinitionField struct {
33 Type string `bson:"type"`
34 Path string `bson:"path"`
35 NumDimensions int `bson:"numDimensions"`
36 Similarity string `bson:"similarity"`
37 Quantization string `bson:"quantization"`
38 }
39
40 type vectorDefinition struct {
41 Fields []vectorDefinitionField `bson:"fields"`
42 }
43
44 indexName := "vector_index"
45 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
46
47 indexModel := mongo.SearchIndexModel{
48 Definition: vectorDefinition{
49 Fields: []vectorDefinitionField{{
50 Type: "vector",
51 Path: "plot_embedding_voyage_3_large",
52 NumDimensions: 2048,
53 Similarity: "dotProduct",
54 Quantization: "scalar"}},
55 },
56 Options: opts,
57 }
58
59 // Create the index
60 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
61 if err != nil {
62 log.Fatalf("failed to create the search index: %v", err)
63 }
64 log.Println("New search index named " + searchIndexName + " is building.")
65
66 // Await the creation of the index.
67 log.Println("Polling to check if the index is ready. This may take up to a minute.")
68 searchIndexes := coll.SearchIndexes()
69 var doc bson.Raw
70 for doc == nil {
71 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
72 if err != nil {
73 fmt.Errorf("failed to list search indexes: %w", err)
74 }
75
76 if !cursor.Next(ctx) {
77 break
78 }
79
80 name := cursor.Current.Lookup("name").StringValue()
81 queryable := cursor.Current.Lookup("queryable").Boolean()
82 if name == searchIndexName && queryable {
83 doc = cursor.Current
84 } else {
85 time.Sleep(5 * time.Second)
86 }
87 }
88
89 log.Println(searchIndexName + " is ready for querying.")
90}

このインデックス定義は、次のフィールドをインデックスします。

  • データを事前にフィルタリングするためのstringフィールド(genres)と数値フィールド(year)。

  • 事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド( plot_embedding_voyage_3_large`` )。

1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7 "time"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("sample_mflix").Collection("embedded_movies")
30 indexName := "vector_index"
31 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
32
33 type vectorDefinitionField struct {
34 Type string `bson:"type"`
35 Path string `bson:"path"`
36 NumDimensions int `bson:"numDimensions"`
37 Similarity string `bson:"similarity"`
38 Quantization string `bson:"quantization"`
39 }
40
41 type filterField struct {
42 Type string `bson:"type"`
43 Path string `bson:"path"`
44 }
45
46 type indexDefinition struct {
47 Fields []vectorDefinitionField `bson:"fields"`
48 }
49
50 vectorDefinition := vectorDefinitionField{
51 Type: "vector",
52 Path: "plot_embedding_voyage_3_large",
53 NumDimensions: 2048,
54 Similarity: "dotProduct",
55 Quantization: "scalar"}
56 genreFilterDefinition := filterField{"filter", "genres"}
57 yearFilterDefinition := filterField{"filter", "year"}
58
59 indexModel := mongo.SearchIndexModel{
60 Definition: bson.D{{Key: "fields", Value: [3]interface{}{
61 vectorDefinition,
62 genreFilterDefinition,
63 yearFilterDefinition}}},
64 Options: opts,
65 }
66
67 // Create the index
68 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
69 if err != nil {
70 log.Fatalf("failed to create the search index: %v", err)
71 }
72 log.Println("New search index named " + searchIndexName + " is building.")
73
74 // Await the creation of the index.
75 log.Println("Polling to check if the index is ready. This may take up to a minute.")
76 searchIndexes := coll.SearchIndexes()
77 var doc bson.Raw
78 for doc == nil {
79 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
80 if err != nil {
81 fmt.Errorf("failed to list search indexes: %w", err)
82 }
83
84 if !cursor.Next(ctx) {
85 break
86 }
87
88 name := cursor.Current.Lookup("name").StringValue()
89 queryable := cursor.Current.Lookup("queryable").Boolean()
90 if name == searchIndexName && queryable {
91 doc = cursor.Current
92 } else {
93 time.Sleep(5 * time.Second)
94 }
95 }
96
97 log.Println(searchIndexName + " is ready for querying.")
98}
3
go run create-index.go

MongoDB Javaドライバー v5.2.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを作成するには、次の手順を実行します。

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.model.SearchIndexModel;
6import com.mongodb.client.model.SearchIndexType;
7import org.bson.Document;
8import org.bson.conversions.Bson;
9
10import java.util.Arrays;
11import java.util.Collections;
12import java.util.List;
13
14public class VectorIndex {
15
16 public static void main(String[] args) {
17
18 // Replace the placeholder with your Atlas connection string
19 String uri = "<connectionString>";
20
21 // Connect to your Atlas cluster
22 try (MongoClient mongoClient = MongoClients.create(uri)) {
23
24 // Set the namespace
25 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
26 MongoCollection<Document> collection = database.getCollection("<collectionName>");
27
28 // Define the index details
29 String indexName = "<indexName>";
30 Bson definition = new Document(
31 "fields",
32 Arrays.asList(
33 new Document("type", "vector")
34 .append("path", "<fieldToIndex>")
35 .append("numDimensions", <numberOfDimensions>)
36 .append("similarity", "euclidean | cosine | dotProduct"),
37 new Document("type", "filter")
38 .append("path", "<fieldToIndex>"),
39 ...));
40
41 // Define the index model
42 SearchIndexModel indexModel = new SearchIndexModel(
43 indexName,
44 definition,
45 SearchIndexType.vectorSearch()
46 );
47
48 // Create the index using the defined model
49 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
50 System.out.println("Successfully created vector index named: " + result.get(0));
51 System.out.println("It may take up to a minute for the index to leave the BUILDING status and become queryable.");
52
53 // Wait for index to build and become queryable
54 System.out.println("Polling to confirm the index has left the BUILDING status.");
55 // No special handling in case of a timeout. Custom handling can be implemented.
56 waitForIndex(collection, indexName);
57 }
58 }
59
60 /**
61 * Polls the collection to check whether the specified index is ready to query.
62 */
63 public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) {
64 long startTime = System.nanoTime();
65 long timeoutNanos = TimeUnit.SECONDS.toNanos(60);
66 while (System.nanoTime() - startTime < timeoutNanos) {
67 Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
68 .filter(index -> indexName.equals(index.getString("name")))
69 .findAny().orElse(null);
70 if (indexRecord != null) {
71 if ("FAILED".equals(indexRecord.getString("status"))) {
72 throw new RuntimeException("Search index has FAILED status.");
73 }
74 if (indexRecord.getBoolean("queryable")) {
75 System.out.println(indexName + " index is ready to query");
76 return true;
77 }
78 }
79 try {
80 Thread.sleep(100); // busy-wait, avoid in production
81 } catch (InterruptedException e) {
82 Thread.currentThread().interrupt();
83 throw new RuntimeException(e);
84 }
85 }
86 return false;
87 }
88}
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

<numberOfDimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<fieldToIndex>

インデックスするベクトル フィールドとフィルター フィールド。

以下の例では、インデックス定義を行います。

  • MongoDB ベクトル検索インデックスで、plot_embedding_voyage_3_largeフィールドを vector タイプとして、genres フィールドと year フィールドを filter タイプとしてインデックス化します。

  • plot_embedding_voyage_3_largeフィールドをベクトル埋め込みフィールドとして指定します。このフィールドには、Voyage AI の voyage-3-large 埋め込みモデルを使用して作成された埋め込みが含まれます。

  • 2048ベクトル次元を指定し、dotProduct 関数を使用して類似性を測定します。

このインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールド(plot_embedding_voyage_3_large)のみをインデックスします。

以下をコピーして作成したファイルに貼り付け、<connectionString> プレースホルダー値を置き換えます。

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.model.SearchIndexModel;
6import com.mongodb.client.model.SearchIndexType;
7import org.bson.Document;
8import org.bson.conversions.Bson;
9
10import java.util.Collections;
11import java.util.List;
12
13public class VectorIndex {
14
15 public static void main(String[] args) {
16
17 // Replace the placeholder with your Atlas connection string
18 String uri = "<connectionString>";
19
20 // Connect to your Atlas cluster
21 try (MongoClient mongoClient = MongoClients.create(uri)) {
22
23 // Set the namespace
24 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
25 MongoCollection<Document> collection = database.getCollection("embedded_movies");
26
27 // Define the index details
28 String indexName = "vector_index";
29 Bson definition = new Document(
30 "fields",
31 Collections.singletonList(
32 new Document("type", "vector")
33 .append("path", "plot_embedding_voyage_3_large")
34 .append("numDimensions", 2048)
35 .append("similarity", "dotProduct")
36 .append("quantization", "scalar")));
37
38 // Define the index model
39 SearchIndexModel indexModel = new SearchIndexModel(
40 indexName,
41 definition,
42 SearchIndexType.vectorSearch());
43
44 // Create the index using the defined model
45 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
46 System.out.println("Successfully created vector index named: " + result.get(0));
47 System.out.println("It may take up to a minute for the index to leave the BUILDING status and become queryable.");
48
49 // Wait for index to build and become queryable
50 System.out.println("Polling to confirm the index has left the BUILDING status.");
51 // No special handling in case of a timeout. Custom handling can be implemented.
52 waitForIndex(collection, indexName);
53 }
54 }
55
56 /**
57 * Polls the collection to check whether the specified index is ready to query.
58 */
59 public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) {
60 long startTime = System.nanoTime();
61 long timeoutNanos = TimeUnit.SECONDS.toNanos(60);
62 while (System.nanoTime() - startTime < timeoutNanos) {
63 Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
64 .filter(index -> indexName.equals(index.getString("name")))
65 .findAny().orElse(null);
66 if (indexRecord != null) {
67 if ("FAILED".equals(indexRecord.getString("status"))) {
68 throw new RuntimeException("Search index has FAILED status.");
69 }
70 if (indexRecord.getBoolean("queryable")) {
71 System.out.println(indexName + " index is ready to query");
72 return true;
73 }
74 }
75 try {
76 Thread.sleep(100); // busy-wait, avoid in production
77 } catch (InterruptedException e) {
78 Thread.currentThread().interrupt();
79 throw new RuntimeException(e);
80 }
81 }
82 return false;
83 }
84}

このインデックス定義は、次のフィールドをインデックスします。

  • データを事前にフィルタリングするためのstringフィールド(genres)と数値フィールド(year)。

  • 事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド( plot_embedding_voyage_3_large )。

以下をコピーして作成したファイルに貼り付け、<connectionString> プレースホルダー値を置き換えます。

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.model.SearchIndexModel;
6import com.mongodb.client.model.SearchIndexType;
7import org.bson.Document;
8import org.bson.conversions.Bson;
9
10import java.util.Arrays;
11import java.util.Collections;
12import java.util.List;
13
14public class VectorIndex {
15
16 public static void main(String[] args) {
17
18 // Replace the placeholder with your Atlas connection string
19 String uri = "<connectionString>";
20
21 // Connect to your Atlas cluster
22 try (MongoClient mongoClient = MongoClients.create(uri)) {
23
24 // Set the namespace
25 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
26 MongoCollection<Document> collection = database.getCollection("embedded_movies");
27
28 // Define the index details with the filter fields
29 String indexName = "vector_index";
30 Bson definition = new Document(
31 "fields",
32 Arrays.asList(
33 new Document("type", "vector")
34 .append("path", "plot_embedding_voyage_3_large")
35 .append("numDimensions", 2048)
36 .append("similarity", "dotProduct")
37 .append("quantization", "scalar"),
38 new Document("type", "filter")
39 .append("path", "genres"),
40 new Document("type", "filter")
41 .append("path", "year")));
42
43 // Define the index model
44 SearchIndexModel indexModel = new SearchIndexModel(
45 indexName,
46 definition,
47 SearchIndexType.vectorSearch());
48
49 // Create the index using the defined model
50 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
51 System.out.println("Successfully created vector index named: " + result.get(0));
52 System.out.println("It may take up to a minute for the index to leave the BUILDING status and become queryable.");
53
54 // Wait for index to build and become queryable
55 System.out.println("Polling to confirm the index has left the BUILDING status.");
56 // No special handling in case of a timeout. Custom handling can be implemented.
57 waitForIndex(collection, indexName);
58 }
59 }
60
61 /**
62 * Polls the collection to check whether the specified index is ready to query.
63 */
64 public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) {
65 long startTime = System.nanoTime();
66 long timeoutNanos = TimeUnit.SECONDS.toNanos(60);
67 while (System.nanoTime() - startTime < timeoutNanos) {
68 Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
69 .filter(index -> indexName.equals(index.getString("name")))
70 .findAny().orElse(null);
71 if (indexRecord != null) {
72 if ("FAILED".equals(indexRecord.getString("status"))) {
73 throw new RuntimeException("Search index has FAILED status.");
74 }
75 if (indexRecord.getBoolean("queryable")) {
76 System.out.println(indexName + " index is ready to query");
77 return true;
78 }
79 }
80 try {
81 Thread.sleep(100); // busy-wait, avoid in production
82 } catch (InterruptedException e) {
83 Thread.currentThread().interrupt();
84 throw new RuntimeException(e);
85 }
86 }
87 return false;
88 }
89}
3

IDE からファイルを実行してインデックスを作成します。

MongoDB Node ドライバー v6.6.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを作成するには、次の手順を実行します。

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // define your MongoDB Vector Search index
14 const index = {
15 name: "<indexName>",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": <numberOfDimensions>,
22 "path": "<fieldToIndex>",
23 "similarity": "euclidean | cosine | dotProduct"
24 },
25 {
26 "type": "filter",
27 "path": "<fieldToIndex>"
28 },
29 ...
30 ]
31 }
32 }
33
34 // run the helper method
35 const result = await collection.createSearchIndex(index);
36 console.log(`New search index named ${result} is building.`);
37 // wait for the index to be ready to query
38 console.log("Polling to check if the index is ready. This may take up to a minute.")
39 let isQueryable = false;
40 while (!isQueryable) {
41 const cursor = collection.listSearchIndexes();
42 for await (const index of cursor) {
43 if (index.name === result) {
44 if (index.queryable) {
45 console.log(`${result} is ready for querying.`);
46 isQueryable = true;
47 } else {
48 await new Promise(resolve => setTimeout(resolve, 5000));
49 }
50 }
51 }
52 }
53 } finally {
54 await client.close();
55 }
56}
57run().catch(console.dir);

vector-index.jsという名前のファイルを作成します。

2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

<numberOfDimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<fieldToIndex>

インデックスするベクトル フィールドとフィルター フィールド。

以下をコピーして vector-index.jsファイルに貼り付け、<connectionString> プレースホルダー値を置き換えます。次のインデックス定義は、 MongoDB ベクトル検索インデックスで、plot_embedding_voyage_3_largeフィールドをvector タイプとしてインデックス化し、genres フィールドと year フィールドを filter タイプとしてインデックス化します。plot_embedding_voyage_3_largeフィールドには、Voyage AI の voyage-3-large 埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義では、2048ベクトル次元を指定し、dotProduct 関数を使用して類似性を測定します。

次のインデックス定義は、ベクトル検索を実行するためにベクトル埋め込みフィールド( plot_embedding_voyage_3_large )のみをインデックスします。

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("embedded_movies");
12
13 // define your MongoDB Vector Search index
14 const index = {
15 name: "vector_index",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": 2048,
22 "path": "plot_embedding_voyage_3_large",
23 "similarity": "dotProduct",
24 "quantization": "scalar"
25 }
26 ]
27 }
28 }
29
30 // run the helper method
31 const result = await collection.createSearchIndex(index);
32 console.log(`New search index named ${result} is building.`);
33
34 // wait for the index to be ready to query
35 console.log("Polling to check if the index is ready. This may take up to a minute.")
36 let isQueryable = false;
37 while (!isQueryable) {
38 const cursor = collection.listSearchIndexes();
39 for await (const index of cursor) {
40 if (index.name === result) {
41 if (index.queryable) {
42 console.log(`${result} is ready for querying.`);
43 isQueryable = true;
44 } else {
45 await new Promise(resolve => setTimeout(resolve, 5000));
46 }
47 }
48 }
49 }
50 } finally {
51 await client.close();
52 }
53}
54run().catch(console.dir);

このインデックス定義は、次のフィールドをインデックスします。

  • データを事前にフィルタリングするためのstringフィールド(genres)と数値フィールド(year)。

  • 事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド( plot_embedding_voyage_3_large )。

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("embedded_movies");
12
13 // define your MongoDB Vector Search index
14 const index = {
15 name: "vector_index",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": 2048,
22 "path": "plot_embedding_voyage_3_large",
23 "similarity": "dotProduct",
24 "quantization": "scalar"
25 },
26 {
27 "type": "filter",
28 "path": "genres"
29 },
30 {
31 "type": "filter",
32 "path": "year"
33 }
34 ]
35 }
36 }
37
38 // run the helper method
39 const result = await collection.createSearchIndex(index);
40 console.log(`New search index named ${result} is building.`);
41
42 // wait for the index to be ready to query
43 console.log("Polling to check if the index is ready. This may take up to a minute.")
44 let isQueryable = false;
45 while (!isQueryable) {
46 const cursor = collection.listSearchIndexes();
47 for await (const index of cursor) {
48 if (index.name === result) {
49 if (index.queryable) {
50 console.log(`${result} is ready for querying.`);
51 isQueryable = true;
52 } else {
53 await new Promise(resolve => setTimeout(resolve, 5000));
54 }
55 }
56 }
57 }
58 } finally {
59 await client.close();
60 }
61}
62run().catch(console.dir);
3
node <file-name>.js

node vector_index.js

この例の実行可能なバージョンを Python エディタとして使用します。

PyMongoドライバー v 以降を使用してコレクションのMongoDB ベクトル検索インデックスを作成するには、次の手順を実行します。4.7

1
1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3import time
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["<databaseName>"]
11collection = database["<collectionName>"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "numDimensions": <numberofDimensions>,
20 "path": "<fieldToIndex>",
21 "similarity": "euclidean | cosine | dotProduct"
22 },
23 {
24 "type": "filter",
25 "path": "<fieldToIndex>"
26 },
27 ...
28 ]
29 },
30 name="<indexName>",
31 type="vectorSearch"
32)
33
34result = collection.create_search_index(model=search_index_model)
35print("New search index named " + result + " is building.")
36
37# Wait for initial sync to complete
38print("Polling to check if the index is ready. This may take up to a minute.")
39predicate=None
40if predicate is None:
41 predicate = lambda index: index.get("queryable") is True
42
43while True:
44 indices = list(collection.list_search_indexes(result))
45 if len(indices) and predicate(indices[0]):
46 break
47 time.sleep(5)
48print(result + " is ready for querying.")
49
50client.close()

詳しくは、create_search_index() メソッド を参照してください。

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3
4def create_indexes():
5 # Connect to your Atlas deployment
6 uri = "<connectionString>"
7 client = MongoClient(uri)
8
9 # Access your database and collection
10 database = client["<databaseName>"]
11 collection = database["<collectionName>"]
12
13 # Create your index models and add them to an array
14 first_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "numDimensions": <numberOfDimensions>,
20 "path": "<fieldToIndex>",
21 "similarity": "euclidean | cosine | dotProduct"
22 },
23 {
24 "type": "filter",
25 "path": "<fieldToIndex>"
26 },
27 ...
28 ]
29 },
30 name="<indexName>",
31 type="vectorSearch"
32 )
33
34 second_model = SearchIndexModel(
35 definition={
36 "fields": [
37 {
38 "type": "vector",
39 "numDimensions": <numberOfDimensions>,
40 "path": "<fieldToIndex>",
41 "similarity": "euclidean | cosine | dotProduct"
42 },
43 {
44 "type": "filter",
45 "path": "<fieldToIndex>"
46 },
47 ...
48 ]
49 },
50 name="<index name>",
51 type="vectorSearch"
52 )
53
54 ...
55
56 idx_models = [first_model, second_model, ...]
57
58 # Create the search indexes
59 result = collection.create_search_indexes(models=idx_models)
60 print(result)
61
62 client.close()

詳しくは、create_search_indexes() メソッドを参照してください。

vector-index.pyという名前のファイルを作成します。

2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

<numberOfDimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<fieldToIndex>

インデックスするベクトル フィールドとフィルター フィールド。

以下をコピーして vector-index.py に貼り付け、<connectionString> プレースホルダー値を置き換えます。次のインデックス定義は、 MongoDB ベクトル検索インデックスで、plot_embedding_voyage_3_largeフィールドをvector タイプとしてインデックス化し、genres フィールドと year フィールドを filter タイプとしてインデックス化します。plot_embedding_voyage_3_largeフィールドには、Voyage AI の voyage-3-large 埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義では、2048ベクトル次元を指定し、dotProduct 関数を使用して類似性を測定します。

この例の実行可能なバージョンを Python エディタとして使用します。

次のインデックス定義は、ベクトル検索を実行するためにベクトル埋め込みフィールド( plot_embedding_voyage_3_large )のみをインデックスします。

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3import time
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["sample_mflix"]
11collection = database["embedded_movies"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "path": "plot_embedding_voyage_3_large",
20 "numDimensions": 2048,
21 "similarity": "dotProduct",
22 "quantization": "scalar"
23 }
24 ]
25 },
26 name="vector_index",
27 type="vectorSearch"
28)
29
30result = collection.create_search_index(model=search_index_model)
31print("New search index named " + result + " is building.")
32
33# Wait for initial sync to complete
34print("Polling to check if the index is ready. This may take up to a minute.")
35predicate=None
36if predicate is None:
37 predicate = lambda index: index.get("queryable") is True
38
39while True:
40 indices = list(collection.list_search_indexes(result))
41 if len(indices) and predicate(indices[0]):
42 break
43 time.sleep(5)
44print(result + " is ready for querying.")
45
46client.close()

この例の実行可能なバージョンを Python エディタとして使用します。

このインデックス定義は、次のフィールドをインデックスします。

  • データを事前にフィルタリングするためのstringフィールド(genres)と数値フィールド(year)。

  • 事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド( plot_embedding_voyage_3_large )。

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3import time
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["sample_mflix"]
11collection = database["embedded_movies"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "path": "plot_embedding_voyage_3_large",
20 "numDimensions": 2048,
21 "similarity": "dotProduct",
22 "quantization": "scalar"
23 },
24 {
25 "type": "filter",
26 "path": "genres"
27 },
28 {
29 "type": "filter",
30 "path": "year"
31 }
32 ]
33 },
34 name="vector_index",
35 type="vectorSearch"
36)
37
38result = collection.create_search_index(model=search_index_model)
39print("New search index named " + result + " is building.")
40
41# Wait for initial sync to complete
42print("Polling to check if the index is ready. This may take up to a minute.")
43predicate=None
44if predicate is None:
45 predicate = lambda index: index.get("queryable") is True
46
47while True:
48 indices = list(collection.list_search_indexes(result))
49 if len(indices) and predicate(indices[0]):
50 break
51 time.sleep(5)
52print(result + " is ready for querying.")
53
54client.close()
3
python <file-name>.py

python vector-index.py

Atlas UI、 Atlas 管理API、 Atlas CLI、 mongosh、またはサポートされているMongoDBドライバーから、すべてのコレクションのMongoDB ベクトル検索インデックスを表示できます。

MongoDB ベクトル検索インデックスを表示するには、Project Search Index Editor 以上のロールが必要です。

注意

mongosh コマンドまたはドライバーヘルパーメソッドを使用して、すべての Atlas クラスター階層のMongoDB ベクトル検索インデックスを検索できます。サポートされているドライバー バージョンのリストについては、 サポートされているクライアント を参照してください。


➤ [言語の選択]ドロップダウン メニューを使用して、このセクション内の例の言語を設定します。


Atlas APIを使用してコレクションのすべてのMongoDB ベクトル検索インデックスを検索するには、データベースとコレクションの名前を指定してMongoDB Search indexes エンドポイントに GETリクエストを送信します。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}"

エンドポイントの構文とパラメータの詳細については、1 つのコレクションのすべてのMongoDB Search インデックスを返す を参照してください。

Atlas APIを使用してコレクションの 1 つのMongoDB ベクトル検索インデックスを検索するには、一意のIDまたはインデックスのインデックス名(4行)を指定してMongoDB Search indexes エンドポイントに GETリクエストを送信します。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}"

エンドポイントの構文とパラメータの詳細については、 「 名前で 1 つ取得 」および「 ID で 1 つの取得 」を参照してください。

Atlas CLI を使用してコレクションのMongoDB ベクトル検索インデックスを返すには、次の手順を実行します。

1

clusterName

クラスターの名前。

db

インデックス付きコレクションを含むクラスター上のデータベースの名前。

collection

データベース内のインデックス作成されたコレクションの名前。

projectId

プロジェクトの一意の識別子。

2
atlas clusters search indexes list --clusterName [cluster_name] --db <db-name> --collection <collection-name>

コマンドで、次のプレースホルダー値を置き換えます。

  • cluster-name - インデックスされたコレクションを含むクラスターの名前。

  • db-name - インデックスを検索するコレクションを含むデータベースの名前。

  • collection-name - インデックスを検索するコレクションの名前。

コマンド構文とパラメーターについて詳しくは、Atlas CLI ドキュメントのAtlas クラスター検索インデックス リストコマンドを参照してください。

1

MongoDB Search ページには、Search & Vector Search オプションまたは Data Explorer から移動できます。

ページには、ページのインデックスに関する次の詳細が表示されます。

名前

インデックスを識別するラベル。

インデックス タイプ

MongoDB Search またはMongoDB ベクトル検索インデックスを示すラベル。値には、次のものが含まれます。

  • search MongoDB Search インデックス用。

  • vectorSearch MongoDB ベクトル検索インデックス用。

インデックス フィールド

このインデックスがインデックスを作成するフィールドを含むリスト。

ステータス

クラスターのプライマリノード上のインデックスの現在の状態。 有効な値については、「 インデックス ステータス 」を参照してください。

サイズ

プライマリ ノードのインデックスのサイズ。

ドキュメント

コレクション内のドキュメントの総数のうち、インデックスが作成されたドキュメントの数。

必要なメモリ

ベクトル検索クエリの実行に必要なメモリのおおよその量。

アクション

インデックスに対して実行できるアクション。 ここでは、次の作業が可能です。

Search Tester UIでは、vectorSearch タイプのインデックスに対してクエリを実行できません。Query ボタンをクリックすると、 MongoDB ベクトル検索にサンプル$vectorSearch が表示されます。このサンプルをコピーして、Atlas UIでコピー、変更、サポートされている他のクライアントを使用して実行することができます。

mongosh を使用してコレクションのMongoDB ベクトル検索インデックスを表示するには、次の手順を実行します。

1

詳細については、「mongosh経由でクラスターに接続する」を参照してください。

2
3

db.collection.getSearchIndexes()メソッドの構文は次のとおりです。

1db.<collectionName>.getSearchIndexes( "<index-name>" );

C#ドライバー 以降を使用してコレクションのMongoDB3.1.0 ベクトル検索インデックスを表示するには、次の手順を実行します。

1
1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5
6public class IndexService
7{
8 private const string MongoConnectionString = "<connectionString>";
9 // Other class methods here...
10 public void ViewSearchIndexes()
11 {
12 try
13 {
14 // Connect to your Atlas deployment
15 var client = new MongoClient(MongoConnectionString);
16
17 // Access your database and collection
18 var database = client.GetDatabase("<databaseName>");
19 var collection = database.GetCollection<BsonDocument>("<collectionName>");
20
21 // Get a list of the collection's search indexes and print them
22 var searchIndexView = collection.SearchIndexes;
23 var indexes = searchIndexView.List();
24
25 foreach (var index in indexes.ToEnumerable())
26 {
27 Console.WriteLine(index);
28 }
29 }
30 catch (Exception e)
31 {
32 Console.WriteLine($"Exception: {e.Message}");
33 }
34 }
35}
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

コレクションを含むデータベースの名前。

<collectionName>

コレクションの名前。

3
using query_quick_start;
var indexService = new IndexService();
indexService.ViewSearchIndexes();
4
dotnet run

MongoDB Goドライバー v2.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを表示するには、次の手順を実行します。

1
1package main
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("<databaseName>").Collection("<collectionName>")
30
31 // Specify the options for the index to retrieve
32 indexName := "<indexName>"
33 opts := options.SearchIndexes().SetName(indexName)
34
35 // Get the index
36 cursor, err := coll.SearchIndexes().List(ctx, opts)
37 if err != nil {
38 log.Fatalf("failed to get the index: %v", err)
39 }
40
41 // Print the index details to the console as JSON
42 var results []bson.M
43 if err := cursor.All(ctx, &results); err != nil {
44 log.Fatalf("failed to unmarshal results to bson: %v", err)
45 }
46 res, err := json.Marshal(results)
47 if err != nil {
48 log.Fatalf("failed to marshal results to json: %v", err)
49 }
50 fmt.Println(string(res))
51}
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

コレクションを含むデータベース。

<collectionName>

インデックスを検索するコレクション。

<indexName>

特定のインデックスを検索する場合は、インデックスの名前を指定します。コレクションのすべての検索インデックスを返すには、この値を省略し、検索インデックスオプションを作成する場合にSetName()メソッドの呼び出しを削除します。

3
go run get-index.go

MongoDB Javaドライバー v5.2.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを表示するには、次の手順を実行します。

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class ViewVectorIndex {
8
9 public static void main(String[] args) {
10
11 // Replace the placeholder with your Atlas connection string
12 String uri = "<connectionString>";
13
14 // Connect to your Atlas cluster
15 try (MongoClient mongoClient = MongoClients.create(uri)) {
16
17 // Set the namespace
18 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
19 MongoCollection<Document> collection = database.getCollection("<collectionName>");
20
21 // Specify the options for the index to retrieve
22 String indexName = "<indexName>";
23
24 // Get the index and print details to the console as JSON
25 try {
26 Document listSearchIndex = collection.listSearchIndexes().name(indexName).first();
27 if (listSearchIndex != null) {
28 System.out.println("Index found: " + listSearchIndex.toJson());
29 } else {
30 System.out.println("Index not found.");
31 }
32 } catch (Exception e) {
33 throw new RuntimeException("Error finding index: " + e);
34 }
35
36 } catch (Exception e) {
37 throw new RuntimeException("Error connecting to MongoDB: " + e);
38 }
39 }
40}
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

コレクションを含むデータベース。

<collectionName>

インデックスを検索するコレクション。

<indexName>

特定のインデックスを検索する場合は、インデックスの名前。 コレクションのすべてのインデックスを返すには、この値を省略します。

3

IDE からファイルを実行し、指定されたインデックスを検索します。

MongoDB Node ドライバー v6.6.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを表示するには、次の手順を実行します。

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // run the helper method
14 const result = await collection.listSearchIndexes("<indexName>").toArray();
15 console.log(result);
16 } finally {
17 await client.close();
18 }
19}
20run().catch(console.dir);
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

コレクションを含むデータベース。

<collectionName>

インデックスを検索するコレクション。

<indexName>

特定のインデックスを検索する場合は、インデックスの名前。 コレクションのすべてのインデックスを返すには、この値を省略します。

3
node <file-name>.js

この例の実行可能なバージョンを Python エディタとして使用します。

PyMongoドライバー v4.7 以降を使用してコレクションのMongoDB ベクトル検索インデックスを表示するには、次の手順を実行します。

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11# Get a list of the collection's search indexes and print them
12cursor = collection.list_search_indexes()
13for index in cursor:
14 print(index)

詳しくは、list_search_indexes() メソッド を参照してください。

2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

コレクションを含むデータベースの名前。

<collectionName>

コレクションの名前。

3
python <file-name>.py

既存のMongoDB ベクトル検索インデックスのインデックス定義は、 Atlas UI、 Atlas 管理API、 Atlas CLI、mongosh 、またはサポートされているMongoDBドライバーから変更できます。インデックスの名前を変更したり、インデックスタイプを変更したりすることはできません。インデックスの名前またはタイプを変更する必要がある場合は、新しいインデックスを作成し、古いインデックスを削除する必要があります。

重要

インデックスを編集すると、 MongoDB ベクトル検索 はそのインデックスを再構築します。インデックスの再ビルド中も、古いインデックス定義を使用してベクトル検索クエリを引き続き実行できます。インデックスの再構築が完了すると、古いインデックスは自動的に置き換えられます。このプロセスはMongoDB Search インデックスと同様です。詳しくは、「 MongoDB Search インデックスの作成と更新 」を参照してください。

MongoDB ベクトル検索インデックスを編集するには、Project Search Index Editor 以上のロールが必要です。

注意

mongosh コマンドまたはドライバーヘルパーメソッドを使用して、すべての Atlas クラスター階層のMongoDB ベクトル検索インデックスを編集できます。サポートされているドライバー バージョンのリストについては、 サポートされているクライアント を参照してください。


➤ [言語を選択 ] ドロップダウン メニューを使用して、インデックスの編集に使用するクライアントを選択します。


Atlas APIを使用してコレクションのMongoDB ベクトル検索インデックスを編集するには、編集するインデックスの一意のIDまたは名前(4 行)を指定してMongoDB Search indexes エンドポイントに PATCHリクエストを送信します。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest --include \
2 --header "Accept: application/json" \
3 --header "Content-Type: application/json" \
4 --request PATCH "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}" \
5 --data'
6 {
7 "database": "<name-of-database>",
8 "collectionName": "<name-of-collection>",
9 "type": "vectorSearch",
10 "name": "<index-name>",
11 "definition": {
12 "fields":[
13 {
14 "type": "vector",
15 "path": <field-to-index>,
16 "numDimensions": <number-of-dimensions>,
17 "similarity": "euclidean | cosine | dotProduct"
18 },
19 {
20 "type": "filter",
21 "path": "<field-to-index>"
22 },
23 ...
24 }
25 ]
26 }'

エンドポイントの構文とパラメータの詳細については、「名前を使用して 1 つ更新 」および「 ID を使用して 1 つの更新 」を参照してください。

Atlas CLI を使用してコレクションのMongoDB ベクトル検索インデックスを編集するには、次の手順を実行します。

1

インデックス定義は、次の形式のようになります。

1{
2 "database": "<name-of-database>",
3 "collectionName": "<name-of-collection>",
4 "type": "vectorSearch",
5 "name": "<index-name>",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "<field-to-index>",
10 "numDimensions": <number-of-dimensions>,
11 "similarity": "euclidean | cosine | dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "<field-to-index>"
16 },
17 ...
18 ]
19}
2

<name-of-database>

インデックスを作成するコレクションを含むデータベース。

<name-of-collection>

インデックスを作成するコレクション。

<index-name>

インデックスの名前。インデックス名を省略すると、 MongoDB ベクトル検索 はインデックスに vector_index という名前を付けます。

<number-of-dimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<field-to-index>

インデックスするベクトル フィールドとフィルター フィールド。

3
atlas clusters search indexes update <indexId> --clusterName [cluster_name] --file [vector-_index].json

コマンドで、次のプレースホルダー値を置き換えます。

  • cluster_name -インデックスを更新するコレクションを含むクラスターの名前。

  • vector_index - MongoDB ベクトル検索インデックスの変更されたインデックス定義を含むJSONファイルの名前

コマンド構文とパラメーターについて詳しくは、Atlas CLI ドキュメントのAtlas クラスター検索インデックス更新コマンド を参照してください。

1

MongoDB Search ページには、Search & Vector Search オプションまたは Data Explorer から移動できます。

2
  1. 編集するvectorSearch型インデックスを見つけます。

  2. そのインデックスの「Actions」列にある をクリックします。

  3. Edit With Visual Editor を選択してガイド付き体験を行うか、Edit With JSON Editor を選択して生のインデックス定義を編集してください。

  4. 現在の構成設定を確認し、必要に応じて編集します。

    MongoDB ベクトル検索インデックスのフィールドの詳細については、 「ベクトル検索のフィールドにインデックスを作成する方法」 を参照してください。

  5. 変更を適用するには、 Saveをクリックします。

インデックスのステータスが Active から Building に変わります。この状態では、アップデートされたインデックスが使用可能になるまで、 MongoDB ベクトル検索 が古いインデックスを削除しないため、古いインデックスを使用し続けることができます。ステータスが Active に戻ったら、変更されたインデックスは使用可能になります。

mongosh を使用してコレクションのMongoDB ベクトル検索インデックスを編集するには、次の手順を行います。

1

詳細については、「mongosh経由でクラスターに接続する」を参照してください。

2
3

db.collection.updateSearchIndex()メソッドの構文は次のとおりです。

1db.<collectionName>.updateSearchIndex(
2 "<index-name>",
3 {
4 fields: [
5 {
6 "type": "vector",
7 "numDimensions": <number-of-dimensions>,
8 "path": "<field-to-index>",
9 "similarity": "euclidean | cosine | dotProduct"
10 },
11 {
12 "type": "filter",
13 "path": "<field-to-index>"
14 },
15 ...
16 ]
17 }
18);

C# ドライバー 3.1.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを更新するには、次の手順を実行します。

1
1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5
6public class IndexService
7{
8 private const string MongoConnectionString = "<connectionString>";
9 // Other class methods here...
10 public void EditVectorIndex()
11 {
12 try
13 {
14 // Connect to your Atlas deployment
15 var client = new MongoClient(MongoConnectionString);
16
17 // Access your database and collection
18 var database = client.GetDatabase("<databaseName>");
19 var collection = database.GetCollection<BsonDocument>("<collectionName>");
20
21 var definition = new BsonDocument
22 {
23 { "fields", new BsonArray
24 {
25 new BsonDocument
26 {
27 { "type", "vector" },
28 { "path", "<fieldToIndex>" },
29 { "numDimensions", <numberOfDimensions> },
30 { "similarity", "euclidean | cosine | dotProduct" }
31 }
32 }
33 }
34 };
35
36 // Update your search index
37 var searchIndexView = collection.SearchIndexes;
38 searchIndexView.Update(name, definition);
39 }
40 catch (Exception e)
41 {
42 Console.WriteLine($"Exception: {e.Message}");
43 }
44 }
45}
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの構成。インデックス名を省略すると、 はデフォルトで vector_index となります。

<numberOfDimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<fieldToIndex>

インデックスするベクトル フィールドとフィルター フィールド。

3
using query_quick_start;
var indexService = new IndexService();
indexService.EditVectorIndex();
4
dotnet run

MongoDB Goドライバー v2.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを更新するには、次の手順を実行します。

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/mongo"
9 "go.mongodb.org/mongo-driver/v2/mongo/options"
10)
11
12func main() {
13 ctx := context.Background()
14
15 // Replace the placeholder with your Atlas connection string
16 const uri = "<connection-string>"
17
18 // Connect to your Atlas cluster
19 clientOptions := options.Client().ApplyURI(uri)
20 client, err := mongo.Connect(clientOptions)
21 if err != nil {
22 log.Fatalf("failed to connect to the server: %v", err)
23 }
24 defer func() { _ = client.Disconnect(ctx) }()
25
26 // Set the namespace
27 coll := client.Database("<databaseName>").Collection("<collectionName>")
28 indexName := "<indexName>"
29
30 type vectorDefinitionField struct {
31 Type string `bson:"type"`
32 Path string `bson:"path"`
33 NumDimensions int `bson:"numDimensions"`
34 Similarity string `bson:"similarity"`
35 }
36
37 type vectorDefinition struct {
38 Fields []vectorDefinitionField `bson:"fields"`
39 }
40
41 definition := vectorDefinition{
42 Fields: []vectorDefinitionField{{
43 Type: "vector",
44 Path: "<fieldToIndex>",
45 NumDimensions: <numberOfDimensions>,
46 Similarity: "euclidean | cosine | dotProduct"}},
47 }
48 err = coll.SearchIndexes().UpdateOne(ctx, indexName, definition)
49
50 if err != nil {
51 log.Fatalf("failed to update the index: %v", err)
52 }
53
54 fmt.Println("Successfully updated the search index")
55}
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

<numberOfDimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<fieldToIndex>

インデックスするベクトル フィールドとフィルター フィールド。

3
go run edit-index.go

MongoDB Javaドライバー v5.2.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを編集するには、次の手順を実行します。

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6import org.bson.conversions.Bson;
7
8import java.util.Collections;
9
10public class EditVectorIndex {
11
12 public static void main(String[] args) {
13
14 // Replace the placeholder with your Atlas connection string
15 String uri = "<connectionString>";
16
17 // Connect to your Atlas cluster
18 try (MongoClient mongoClient = MongoClients.create(uri)) {
19
20 // Set the namespace
21 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
22 MongoCollection<Document> collection = database.getCollection("<collectionName>");
23
24 // Define the index changes
25 String indexName = "<indexName>";
26 Bson definition = new Document(
27 "fields",
28 Collections.singletonList(
29 new Document("type", "vector")
30 .append("path", "<fieldToIndex>")
31 .append("numDimensions", "<numberOfDimensions>")
32 .append("similarity", "euclidean | cosine | dotProduct")
33 .append("quantization", "none | scalar | binary")));
34
35 // Update the index
36 collection.updateSearchIndex(indexName, definition);
37 System.out.println("Successfully updated the index");
38 }
39 }
40}
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

<numberOfDimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<fieldToIndex>

インデックスするベクトル フィールドとフィルター フィールド。

3

IDE からファイルを実行して、変更内容でインデックスを更新します。

MongoDB Node ドライバー v6.6.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを更新するには、次の手順を実行します。

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // define your MongoDB Search index
14 const index = {
15 name: "<indexName>",
16 type: "vectorSearch",
17 //updated search index definition
18 definition: {
19 "fields": [
20 {
21 "type": "vector",
22 "numDimensions": <numberOfDimensions>,
23 "path": "<field-to-index>",
24 "similarity": "euclidean | cosine | dotProduct"
25 },
26 {
27 "type": "filter",
28 "path": "<fieldToIndex>"
29 },
30 ...
31 ]
32 }
33 }
34
35 // run the helper method
36 await collection.updateSearchIndex("<index-name>", index);
37 } finally {
38 await client.close();
39 }
40}
41run().catch(console.dir);
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

<numberOfDimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<fieldToIndex>

インデックスするベクトル フィールドとフィルター フィールド。

3
node <file-name>.js

この例の実行可能なバージョンを Python エディタとして使用します。

PyMongoドライバー v4.7 以降を使用してコレクションのMongoDB ベクトル検索インデックスを更新するには、次の手順を実行します。

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11definition = {
12 "fields": [
13 {
14 "type": "vector",
15 "numDimensions": <numberofDimensions>,
16 "path": "<fieldToIndex>",
17 "similarity": "euclidean | cosine | dotProduct",
18 "quantization": " none | scalar | binary "
19 },
20 {
21 "type": "filter",
22 "path": "<fieldToIndex>"
23 },
24 ...
25 ]
26}
27
28# Update your search index
29collection.update_search_index("<indexName>", definition)

詳しくは、update_search_index() メソッド を参照してください。

2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの構成。インデックス名を省略すると、 はデフォルトで vector_index となります。

<numberOfDimensions>

MongoDB ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。

<fieldToIndex>

インデックスするベクトル フィールドとフィルター フィールド。

3
python <file-name>.py

MongoDB ベクトル検索インデックスは、 Atlas UI、 Atlas 管理API、Atlas CLI、mongosh、またはサポートされているMongoDBドライバーからいつでも削除できます。

MongoDB ベクトル検索インデックスを削除するには、Project Search Index Editor 以上のロールが必要です。

注意

mongosh コマンドまたはドライバーヘルパーメソッドを使用して、すべての Atlas クラスター階層上のMongoDB ベクトル検索インデックスを削除できます。サポートされているドライバー バージョンのリストについては、 サポートされているクライアント を参照してください。


➤ [言語を選択 ] ドロップダウン メニューを使用して、インデックスを削除するために使用するクライアントを選択します。


Atlas APIを使用してコレクションのMongoDB ベクトル検索インデックスを削除するには、一意のIDまたは削除するインデックスの名前のいずれかを指定して、 MongoDB Search indexes エンドポイントに DELETEリクエストを送信します。

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request DELETE "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}"

エンドポイントの構文とパラメータの詳細については、「名前を使用して1 つの検索インデックスを削除 」および「 ID を使用して 1 つの検索インデックスを削除 」を参照してください。

Atlas CLI を使用してコレクションのMongoDB ベクトル検索インデックスを削除するには、次の手順を実行します。

1

<indexId>

削除するインデックスの一意の識別子。

<clusterName>

クラスターの名前。

<projectId>

プロジェクトの一意の識別子。

2
atlas clusters search indexes delete <indexId> [options]

コマンドで、 indexIdプレースホルダー値を削除するインデックスの一意の識別子に置き換えます。

コマンド構文とパラメーターについて詳しくは、Atlas CLI ドキュメントのAtlas クラスター検索インデックス削除コマンドを参照してください。

1

MongoDB Search ページには、Search & Vector Search オプションまたは Data Explorer から移動できます。

2
  1. 削除するvectorSearchタイプ インデックスを見つけます。

  2. そのインデックスのActionsドロップダウンから [ Delete Indexをクリックします。

  3. 確認ウィンドウで [ Drop Indexをクリックします。

mongosh を使用してコレクションのMongoDB ベクトル検索インデックスを削除するには、次の手順を行います。

1

詳細については、「mongosh経由でクラスターに接続する」を参照してください。

2
3

db.collection.dropSearchIndex()メソッドの構文は次のとおりです。

1db.<collectionName>.dropSearchIndex( "<index-name>" );

C# ドライバー 3.1.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを削除するには、次の手順を実行します。

1
1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5
6public class IndexService
7{
8 private const string MongoConnectionString = "<connectionString>";
9 // Other class methods here...
10 public void DeleteVectorIndex()
11 {
12 try
13 {
14 // Connect to your Atlas deployment
15 var client = new MongoClient(MongoConnectionString);
16
17 // Access your database and collection
18 var database = client.GetDatabase("<databaseName>");
19 var collection = database.GetCollection<BsonDocument>("<collectionName>");
20
21 // Delete your search index
22 var searchIndexView = collection.SearchIndexes;
23 var name = "vector_index";
24 searchIndexView.DropOne(name);
25
26 Console.WriteLine($"Dropping search index named {name}. This may take up to a minute.");
27 }
28 catch (Exception e)
29 {
30 Console.WriteLine($"Exception: {e.Message}");
31 }
32 }
33}
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

コレクションを含むデータベースの名前。

<collectionName>

コレクションの名前。

<indexName>

削除するインデックスの名前。

3
using query_quick_start;
var indexService = new IndexService();
indexService.DeleteVectorIndex();
4
dotnet run

MongoDB Goドライバー v2.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを削除するには、次の手順を実行します。

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/mongo"
9 "go.mongodb.org/mongo-driver/v2/mongo/options"
10)
11
12func main() {
13 ctx := context.Background()
14
15 // Replace the placeholder with your Atlas connection string
16 const uri = "<connectionString>"
17
18 // Connect to your Atlas cluster
19 clientOptions := options.Client().ApplyURI(uri)
20 client, err := mongo.Connect(clientOptions)
21 if err != nil {
22 log.Fatalf("failed to connect to the server: %v", err)
23 }
24 defer func() { _ = client.Disconnect(ctx) }()
25
26 // Set the namespace
27 coll := client.Database("<databaseName>").Collection("<collectionName>")
28 indexName := "<indexName>"
29
30 err = coll.SearchIndexes().DropOne(ctx, indexName)
31 if err != nil {
32 log.Fatalf("failed to delete the index: %v", err)
33 }
34
35 fmt.Println("Successfully deleted the Vector Search index")
36}
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

3
go run delete-index.go

MongoDB Javaドライバー v 以降を使用してコレクションのMongoDB ベクトル検索インデックスを削除するには、次の手順を実行します。5.2.0

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class DeleteIndex {
8
9 public static void main(String[] args) {
10
11 // Replace the placeholder with your Atlas connection string
12 String uri = "<connectionString>";
13
14 // Connect to your Atlas cluster
15 try (MongoClient mongoClient = MongoClients.create(uri)) {
16
17 // Set the namespace
18 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
19 MongoCollection<Document> collection = database.getCollection("<collectionName>");
20
21 // Specify the index to delete
22 String indexName = "<indexName>";
23
24 try {
25 collection.dropSearchIndex(indexName);
26 } catch (Exception e) {
27 throw new RuntimeException("Error deleting index: " + e);
28 }
29
30 } catch (Exception e) {
31 throw new RuntimeException("Error connecting to MongoDB: " + e);
32 }
33 }
34}
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

3

IDE からファイルを実行して、指定されたインデックスを削除します。

MongoDB Node ドライバー v6.6.0 以降を使用してコレクションのMongoDB ベクトル検索インデックスを削除するには、次の手順を実行します。

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // run the helper method
14 await collection.dropSearchIndex("<indexName>");
15
16 } finally {
17 await client.close();
18 }
19}
20run().catch(console.dir);
2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

インデックスを作成するコレクションを含むデータベース。

<collectionName>

インデックスを作成するコレクション。

<indexName>

インデックスの名前。インデックス名を省略すると、 はデフォルトで vector_index となります。

3
node <file-name>.js

この例の実行可能なバージョンを Python エディタとして使用します。

PyMongoドライバー v4.7 以降を使用してコレクションのMongoDB ベクトル検索インデックスを削除するには、次の手順を実行します。

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11# Delete your search index
12collection.drop_search_index("<indexName>")

詳しくは、drop_search_index() メソッド を参照してください。

2

<connectionString>

Atlas接続文字列。 詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

<databaseName>

コレクションを含むデータベースの名前。

<collectionName>

コレクションの名前。

<indexName>

削除するインデックスの名前。

3
python <file-name>.py

MongoDB ベクトル検索インデックスを作成すると、Status 列にはクラスターのプライマリノードにおけるインデックスの現在の状態が表示されます。クラスタ内のすべてのノードにおけるインデックスの状態を表示するには、ステータスの下にある View status details リンクをクリックします。

Status 列が Active の場合、インデックスは使用可能です。そのほかの状態の場合は、インデックスに対するクエリに不完全な結果が返される場合があります。

ステータス
説明

開始前

Atlas によるインデックスの構築は開始されていません。

最初の同期

Atlas はインデックスを構築中、または編集したインデックスを再構築中です。インデックスがこの状態のとき、次の状況が発生します。

  • 新しいインデックスの場合、 MongoDB ベクトル検索 はインデックス構築が完了するまでクエリを処理しません。

  • 既存のインデックスの場合、インデックスの再構築が完了するまで、ユーザーは古いインデックスを引き続き使用して既存のクエリと新しいクエリを処理できます。

アクティブ

インデックスをいつでも使用できます。

リカバリ中

レプリケーションでエラーが発生しました。この状態は通常、現在のレプリケーション点がmongod oplogで使用できなくなった場合に発生します。既存のインデックスがアップデートされ、ステータスが Active に変わるまで、引き続き既存のインデックスをクエリできます。View status details モーダルウィンドウのエラーを使用して、問題のトラブルシューティングを行います。詳しくは、「問題の修正」を参照してください。

失敗

Atlas によるインデックスのビルドは失敗しました 。View status details モーダルウィンドウのエラーを使用して、問題のトラブルシューティングを行います。詳しくは、「問題の修正」を参照してください。

削除中

Atlas はクラスター ノードからインデックスを削除しています。

Atlas によるインデックスの構築中および構築の完了後、Documents 列にはインデックス済みドキュメントの割合と数が表示されます。また、この列には、コレクション内の総ドキュメント数も表示されます。

戻る

埋め込みの作成

ルール バッジを取得する

「Vector Search の基礎」を無料で習得できます。

詳細