ベクトルAtlas Searchのフィールドにインデックスを付ける方法
項目一覧
vectorSearch
タイプを使用して、 $vectorSearch
クエリを実行中のフィールドにインデックスを作成できます。 クエリするベクトル埋め込みと、データを事前フィルタリングするために使用するブール値、日付、ObjectId、数値、string、または UUID 値のインデックスを定義できます。 データをフィルタリングすると、セマンティック検索の範囲を絞り込み、マルチテナント環境など特定のベクトル埋め込みが比較の対象とならないようにするのに役立ちます。
Atlas Vector Search インデックスを 作成 するには、Atlas UI、Atlas Administration API、Atlas CLI、mongosh
、またはサポートされている MongoDB ドライバー を使用できます。
注意
非推奨のknnBeta演算子を使用して、 vectorSearch
型のインデックス定義を使用してインデックス付けされたフィールドをクエリすることはできません。
Considerations
vectorSearch
型のインデックス定義では、単一要素のみを含む配列のインデックスを作成できます。 ドキュメントの配列内のフィールド、またはオブジェクトの配列内のフィールドをインデックスすることはできません。 ドット表記を使用してドキュメント内のフィールドにインデックスを付けることができます。
埋め込みのインデックスを作成する前に、Atlas クラスターに効率的にストレージを使用するために、埋め込みをサブタイプ float32
、int1
、または int8
を持つBSON BinData ベクトルに変換することをお勧めします。詳細については、埋め込みをBSONベクトルに変換する方法 を参照してください。
注意
次の Atlas ベクトル検索サポートはプレビュー機能として利用できます。
サブタイプを持つBSON BinData
int1
ベクトルの取り込み。自動スカラー量子化。
自動バイナリ量子化。
Atlas Vector Search インデックスを使用する際、Atlas クラスターのアイドル状態のノードで、リソース消費量が増加する可能性があります。これは、Atlas Vector Search のさまざまな重要な操作を実行する基盤である mongot プロセスによるものです。アイドル状態のノードにおける CPU 使用率は、インデックスの数、複雑さ、および規模によって変動する可能性があります。
サポートされているクライアント
Atlas Vector SearchAtlasmongosh
Atlas CLIAtlasAtlasAPIMongoDB ベクトル検索インデックスは、 Atlas UI、 、 Atlas CLI 、 Atlas Administration API 、および次のMongoDBドライバー を使用して作成、管理できます。
構文
次の構文は、 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 }, 10 { 11 "type": "filter", 12 "path": "<field-to-index>" 13 }, 14 ... 15 ] 16 }
Atlas Vector Search インデックス フィールド
Atlas Vector Search インデックス定義には次のフィールドがあります。
オプション | タイプ | 必要性 | 目的 |
---|---|---|---|
| ドキュメントの配列 | 必須 | インデックスするベクトル フィールドとフィルター フィールド(ドキュメントごとに 1 つ)。 少なくとも 1 つのドキュメントには、ベクトル フィールドのフィールド定義が含まれている必要があります。 オプションで、ブール値、日付、数値、 ObjectId 、 string 、および UUID フィールドをドキュメントごとに 1 つずつインデックスして、データを事前にフィルタリングすることもできます。 |
| string | 必須 |
|
| string | 必須 | インデックスを作成するフィールドの名前。ネストされたフィールドの場合は、ドット表記を使用して埋め込みフィールドへのパスを指定します。 連続するドットが 2 つあるフィールド名やドットで終わるフィールド名はインデックスできません。たとえば、Atlas Vector Search では、 |
| 整数 | 必須 | Atlas ベクトル検索 がインデックス作成時およびクエリ時に強制されるベクトル次元の数。
このフィールドは |
| string | 必須 | 上位 K 近傍の検索に使用するベクトル類似度関数。このフィールドは
詳細については、「 類似性関数について 」を参照してください。 |
| string | 任意 | ベクトルの自動ベクトル量子化のタイプ。 ベクトルに適用する量子化のタイプを指定できます。 埋め込みが
精度が重要な場合は、 詳細については、「 ベクトル量子化 」を参照してください。 |
vector
型について
インデックス定義の vector
フィールドには、次のいずれかのタイプの数値の配列が含まれている必要があります。
BSON
double
BSON BinData
vector
サブタイプfloat32
BSON BinData
vector
サブタイプint1
BSON BinData
vector
サブタイプint8
注意
データ用にサブタイプ または を使用してBSON BinData ベクトルを生成する方法の詳細については、「 事前に量子化されたベクトルを取り込む方法float32
int1
int8
」を参照してください。
次の Atlas ベクトル検索サポートはプレビュー機能として利用できます。
サブタイプを持つBSON BinData
int1
ベクトルの取り込み。自動スカラー量子化。
自動バイナリ量子化。
ベクトル フィールドは、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 }, 10 ... 11 ] 12 }
類似度関数について
Atlas ベクトル検索 は次の類似性関数をサポートしています。
euclidean
- ベクトルの端点間の距離を測定します。 この値により、さまざまな次元に基づいて類似性を測定できます。 詳しくは、「 Euclidean 」を参照してください。cosine
- ベクトル間の角度に基づいて類似性を測定します。 この値により、大きさでスケーリングされない類似性を測定できます。cosine
では絶対値ゼロのベクトルは使用できません。 コサイン類似度を測定するには、ベクトルを正規化し、代わりにdotProduct
を使用することをお勧めします。dotProduct
-cosine
と同様の類似性を測定しますが、ベクトルの大きさを考慮します。 大きさを正規化すると、類似性の測定においてcosine
とdotProduct
はほぼ同じになります。dotProduct
を使用するには、インデックス作成時とクエリ時にベクトルを単位の長さで正規化する必要があります。
次の表は、さまざまなタイプの類似性関数を示しています。
ベクトル埋め込みタイプ | euclidean | cosine | dotProduct |
---|---|---|---|
| ✓ | ||
| ✓ | ✓ | ✓ |
| ✓ | ✓ | ✓ |
| ✓ | ✓ | ✓ |
ベクトル取り込み用。
自動スカラーまたはバイナリ定量化用。
最高のパフォーマンスを得るには、埋め込みモデルをチェックして、どの類似度関数が埋め込みモデルの訓練プロセスと一致するかを判断します。 ガイダンスがない場合は、dotProduct
から開始してください。 fields.similarity
を dotProduct
の値に設定すると、角度と大きさの両方に基づいて類似性を効率的に測定できます。 dotProduct
は cosine
よりも計算リソースの消費量が少なく、ベクトルが単位の長さの場合に効率的です。 ただし、ベクトルが正規化されていない場合は、サンプルクエリの結果の類似性スコアを euclidean
距離と cosine
類似性について評価して、どれが妥当な結果に対応しているかを判断してください。
filter
型について
オプションで、ブール値、日付、数値、ObjectId、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 }
注意
データを事前にフィルタリングしても、Atlas Vector Search が$vectorSearch
クエリに$vectorSearchScore
を使用して返すスコアには影響しません。
Atlas Vector Search インデックスの作成
Atlas UI、Atlas Administration API、Atlas CLI を使用して、Atlas クラスター上の任意の種類のデータとともに、長さが4096次元以下のベクトル埋め込みを含むすべてのコレクションに対する Atlas Vector Search インデックスを作成できます。 、 mongosh
、またはサポートされているMongoDB ドライバー。
前提条件
Atlas Vector Search インデックスを作成するには、次の前提条件を持つ Atlas クラスターが必要です。
MongoDB バージョン
6.0.11
、7.0.2
、または 以上Atlas Vector Search インデックスの作成対象のコレクション
注意
mongosh
コマンドまたはドライバーヘルパーメソッドを使用して、すべての Atlas クラスター階層に Atlas ベクトル検索インデックスを作成できます。サポートされているドライバー バージョンのリストについては、 サポートされているクライアント を参照してください。
必要なアクセス権
Atlas Vector Search インデックスを作成および管理するには、 Project Data Access Admin
以上のロールが必要です。
インデックスの制限
インデックス作成数の上限は以下のとおりです。
M0
クラスターで 3 件。M2
クラスターで 5 件M5
クラスターで 10 件Flex クラスターで 10 インデックス。
単一の M10+
クラスターには、2,500 以下の検索インデックスを作成することを推奨します。
手順
➤ [言語を選択 ] ドロップダウン メニューを使用して、インデックスの作成に使用するクライアントを選択します。
注意
この手順には、embedded_movies
データベース内のsample_mflix
コレクションのインデックス定義の例が含まれています。サンプルデータを クラスターにロードし、このコレクションの例Atlas$vectorSearch
ベクトル検索インデックスを作成すると、このコレクションに対してサンプル クエリを実行できます。実行できるサンプルクエリの詳細については、「 $vectorSearch の例 」を参照してください。
Atlas Administration API を使用してコレクション用 Atlas Vector Search インデックスを作成するには、必要なパラメータを指定して Atlas Search indexes
エンドポイントにPOST
リクエストを送信します。
1 curl --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 }'
エンドポイントの構文とパラメータの詳細については、「 Atlas Search インデックスを 1 つ作成する 」を参照してください。
例
次のインデックス定義は「plot_embedding
」フィールドを vector
タイプとしてインデックスします。「plot_embedding
」フィールドには、OpenAI の text-embedding-ada-002
埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義は 1536
ベクトル次元を指定し、dotProduct
関数を使用して類似度を測定します。
次のインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールドのみをインデックスします。
1 curl --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", 17 "numDimensions": 1536, 18 "similarity": "dotProduct" 19 } 20 ] 21 } 22 }'
このインデックス定義は、次のフィールドをインデックスします。
データを事前にフィルタリングするためのstringフィールド(
genres
)と数値フィールド(year
)。事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド(
plot_embedding
)。
1 curl --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", 17 "numDimensions": 1536, 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 v 1.14.3以降を使用してコレクションに Atlas Vector Search インデックスを作成するには、次の手順を実行します。
.json
ファイルを作成し、ファイル内にインデックスを定義します。
インデックス定義は、次の形式のようになります。
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
という名前のファイルを作成します。
以下のプレースホルダー値を置き換えて、ファイルを保存します。
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。 インデックス名を省略すると、Atlas Vector Search はインデックスに |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
例
次のインデックス定義をコピーして、vector-index.json
ファイルに貼り付けます。 次のインデックス定義は、Atlas ベクトル検索インデックスで、plot_embedding
フィールドをvector
タイプとしてインデックス化し、genres
フィールドと year
フィールドを filter
タイプとしてインデックス化します。 plot_embedding
フィールドには、 OpenAI の text-embedding-ada-002
埋め込みモデルを使用して作成された埋め込みが含まれます。 インデックス定義では、1536
ベクトル次元を指定し、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", 10 "numDimensions": 1536, 11 "similarity": "dotProduct" 12 } 13 ] 14 }
このインデックス定義は、次のフィールドをインデックスします。
データを事前にフィルタリングするためのstringフィールド(
genres
)と数値フィールド(year
)。事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド(
plot_embedding
)。
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", 10 "numDimensions": 1536, 11 "similarity": "dotProduct" 12 }, 13 { 14 "type": "filter", 15 "path": "genres" 16 }, 17 { 18 "type": "filter", 19 "path": "year" 20 } 21 ] 22 }
以下のコマンドを実行してインデックスを作成します。
atlas clusters search indexes create --clusterName [cluster_name] --file [vector_index].json
コマンドで、次のプレースホルダー値を置き換えます。
cluster_name
は、インデックスを作成するコレクションを含む Atlas クラスターの名前です。vector_index
は、Atlas Vector Search インデックスのインデックス定義を含むJSONファイルの名前です。
例
atlas clusters search indexes create --clusterName [cluster_name] --file vector-index.json
コマンド構文とパラメーターについて詳しくは、Atlas CLI ドキュメントのAtlas クラスター検索インデックス作成コマンド を参照してください。
Atlas Atlasで、プロジェクトの {0 ページにGoします。GoClusters
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
インデックスの設定を開始します。
ページで次の選択を行い、Next をクリックしてください。
Search Type | Vector Search のインデックスタイプを選択します。 |
Index Name and Data Source | 以下の情報を指定してください。
|
Configuration Method | For a guided experience, select Visual Editor. To edit the raw index definition, select JSON Editor. |
インデックスの定義を指定してください。
Atlas は、ベクトル埋め込みを含むフィールドとその対応する次元を自動的に検出し、最大 3 つのベクトルフィールドを事前に入力します。インデックスを設定するには、次の操作を行う必要があります。
必要に応じて、[Path] ドロップダウンからインデックスを作成するベクトルフィールドを選択してください。
[Add Another Field] を選択して、追加フィールドにインデックスを作成します。
[Similarity Method] ドロップダウンメニューで、各インデックスフィールドの類似度メソッドを指定してください。
(任意)[Advanced] をクリックし、ドロップダウンメニューから [Scalar] または [Binary] の量子化を選択して、フィールド内の埋め込みを自動的に量子化します。
(任意)コレクション内の他のフィールドを指定して、「Filter Field」セクションでデータをフィルタリングします。
Atlas Vector Search のインデックス設定の詳細については、「ベクトル検索のためのフィールドのインデックス作成方法」を参照してください。
例
embedded_movies
コレクションでは、plot_embedding
フィールドが表示されます。
インデックスを構成するには、Similarity Method ドロップダウンから Dot Product を選択します。
このインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールド(plot_embedding
)のみをインデックスします。
embedded_movies
コレクションでは、plot_embedding
フィールドが表示されます。
インデックスを設定するには、次の操作を行う必要があります。
Similarity MethodドロップダウンからDot Productを選択します。
[Advanced] をクリックして、ドロップダウンメニューから Scalar 量子化を選択します。
Filter Field セクションで、
genres
フィールドとyear
フィールドを指定してデータをフィルタリングします。
このインデックス定義は、次のフィールドをインデックスします。
データを事前にフィルタリングするためのstringフィールド(
genres
)と数値フィールド(year
)。事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド(
plot_embedding
)。
また、埋め込みの効率的な処理のために自動量子化(scalar
)を有効にします。
Atlas Vector Search インデックスは次の例のようになります。
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
」フィールドを vector
タイプとしてインデックスします。「plot_embedding
」フィールドには、OpenAI の text-embedding-ada-002
埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義は 1536
ベクトル次元を指定し、dotProduct
関数を使用して類似度を測定します。
次のインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールドのみをインデックスします。
1 { 2 "fields": [{ 3 "type": "vector", 4 "path": "plot_embedding", 5 "numDimensions": 1536, 6 "similarity": "dotProduct" 7 }] 8 }
このインデックス定義は、次のフィールドをインデックスします。
データを事前にフィルタリングするためのstringフィールド(
genres
)と数値フィールド(year
)。事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド(
plot_embedding
)。
また、埋め込みの効率的な処理のために自動量子化(scalar
)を有効にします。
1 { 2 "fields": [{ 3 "type": "vector", 4 "path": "plot_embedding", 5 "numDimensions": 1536, 6 "similarity": "dotProduct", 7 "quantization": "scalar" 8 }, 9 { 10 "type": "filter", 11 "path": "genres" 12 }, 13 { 14 "type": "filter", 15 "path": "year" 16 }] 17 }
mongosh
v 2.1.2以降を使用してコレクションに Atlas Vector Search インデックスを作成するには、次の手順を実行します。
mongosh
を使用して Atlas クラスターに接続します。
詳しくは、「 mongosh
経由で接続 」を参照してください。
db.collection.createSearchIndex()
メソッドを実行します。
db.collection.createSearchIndex()
メソッドの構文は次のとおりです。
1 db.<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
」フィールドを vector
タイプとしてインデックスします。「plot_embedding
」フィールドには、OpenAI の text-embedding-ada-002
埋め込みモデルを使用して作成された埋め込みが含まれます。インデックス定義は 1536
ベクトル次元を指定し、dotProduct
関数を使用して類似度を測定します。
次のインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールドのみをインデックスします。
1 db.embedded_movies.createSearchIndex( 2 "vector_index", 3 "vectorSearch", 4 { 5 "fields": [ 6 { 7 "type": "vector", 8 "path": "plot_embedding", 9 "numDimensions": 1536, 10 "similarity": "dotProduct", 11 "quantization": "scalar" 12 } 13 ] 14 } 15 );
このインデックス定義は、次のフィールドをインデックスします。
データを事前にフィルタリングするためのstringフィールド(
genres
)と数値フィールド(year
)。事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド(
plot_embedding
)。
1 db.embedded_movies.createSearchIndex( 2 "vector_index", 3 "vectorSearch", 4 { 5 "fields": [ 6 { 7 "type": "vector", 8 "path": "plot_embedding", 9 "numDimensions": 1536, 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 以降を使用してコレクションの Atlas Vector Search インデックスを作成するには、次の手順を実行します。
.cs
ファイルを作成し、ファイル内にインデックスを定義します。
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 using System; 4 using System.Threading; 5 6 // Connect to your Atlas deployment 7 private const string MongoConnectionString = "<connectionString>"; 8 var client = new MongoClient(MongoConnectionString); 9 10 // Access your database and collection 11 var database = client.GetDatabase("<databaseName>"); 12 var collection = database.GetCollection<BsonDocument>("<collectionName>"); 13 14 // Create your index model, then create the search index 15 var name = "<indexName>"; 16 var type = SearchIndexType.VectorSearch; 17 18 var 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 33 var model = new CreateSearchIndexModel(name, type, definition); 34 35 var searchIndexView = collection.SearchIndexes; 36 searchIndexView.CreateOne(model); 37 Console.WriteLine($"New search index named {name} is building."); 38 39 // Wait for initial sync to complete 40 Console.WriteLine("Polling to check if the index is ready. This may take up to a minute."); 41 bool queryable = false; 42 while (!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 } 57 Console.WriteLine($"{name} is ready for querying.");
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 using System; 4 using System.Threading; 5 6 // Connect to your Atlas deployment 7 private const string MongoConnectionString = "<connectionString>"; 8 var client = new MongoClient(MongoConnectionString); 9 10 // Access your database and collection 11 var database = client.GetDatabase("<databaseName>"); 12 var collection = database.GetCollection<BsonDocument>("<collectionName>"); 13 14 // Create your index models and add them to an array 15 var type = SearchIndexType.VectorSearch; 16 17 var 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 }; 31 var modelOne = new CreateSearchIndexModel("<indexName>", type, definitionOne); 32 33 var 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 }; 47 var modelTwo = new CreateSearchIndexModel("<indexName>", type, definitionTwo); 48 49 var models = new CreateSearchIndexModel[] { modelOne, modelTwo }; 50 51 // Create the search indexes 52 var searchIndexView = collection.SearchIndexes; 53 searchIndexView.CreateMany(models); 54 55 Console.WriteLine($"New search indexes are building. This may take up to a minute.");
例
IndexService.cs
という名前のファイルを作成します。
以下の値を置き換えて、ファイルを保存します。
| Atlas接続string 。 詳しくは、「ドライバーによる接続 」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
例
以下をコピーして IndexService.cs
に貼り付け、<connectionString>
プレースホルダー値を置き換えます。 次のインデックス定義は、Atlas ベクトル検索インデックスで、plot_embedding
フィールドをvector
タイプとしてインデックス化し、genres
フィールドと year
フィールドを filter
タイプとしてインデックス化します。 plot_embedding
フィールドには、 OpenAI の text-embedding-ada-002
埋め込みモデルを使用して作成された埋め込みが含まれます。 インデックス定義では、1536
ベクトル次元を指定し、dotProduct
関数を使用して類似性を測定します。
次のインデックス定義は、ベクトル検索を実行するためにベクトル埋め込みフィールド( plot_embedding
)のみをインデックスします。
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 using System; 6 using System.Threading; 7 8 public 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" }, 33 { "numDimensions", 1536 }, 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
)。
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 using System; 6 using System.Threading; 7 8 public 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" }, 33 { "numDimensions", 1536 }, 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 }
MongoDB Goドライバー v 以降を使用してコレクション用に Atlas2.0 ベクトル検索インデックスを作成するには、次の手順を実行します。
create-index.go
というファイルを作成し、ファイルにインデックスを定義します。
1 package main 2 3 import ( 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 13 func 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 以降のプログラムによる Atlas ベクトル検索インデックス管理をサポートしていますが、前述のコードは v2.x ドライバーの構文を示しています。
以下の値を置き換えて、ファイルを保存します。
| Atlas接続string 。 詳しくは、「ドライバーによる接続 」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
例
以下をコピーして create-index.go
ファイルに貼り付け、<connectionString>
プレースホルダー値を置き換えます。 次のインデックス定義は、Atlas ベクトル検索インデックスで、plot_embedding
フィールドをvector
タイプとしてインデックス化し、genres
フィールドと year
フィールドを filter
タイプとしてインデックス化します。 plot_embedding
フィールドには、 OpenAI の text-embedding-ada-002
埋め込みモデルを使用して作成された埋め込みが含まれます。 インデックス定義では、1536
ベクトル次元を指定し、dotProduct
関数を使用して類似性を測定します。
次のインデックス定義は、ベクトル検索を実行するためにベクトル埋め込みフィールド( plot_embedding
)のみをインデックスします。
1 package main 2 3 import ( 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 14 func main() { 15 ctx := context.Background() 16 17 // Replace the placeholder with your Atlas connection string 18 const uri = "<connection-string>" 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", 52 NumDimensions: 1536, 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
)。
1 package main 2 3 import ( 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 14 func 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", 53 NumDimensions: 1536, 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 }
MongoDB Java ドライバー v5.2.0 以降を使用してコレクションの Atlas Vector Search インデックスを作成するには、次の手順を実行します。
.java
ファイルを作成し、ファイル内にインデックスを定義します。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.model.SearchIndexModel; 6 import com.mongodb.client.model.SearchIndexType; 7 import org.bson.Document; 8 import org.bson.conversions.Bson; 9 10 import java.util.Arrays; 11 import java.util.Collections; 12 import java.util.List; 13 14 public 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 Atlas to build the index 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 }
以下の値を置き換えて、ファイルを保存します。
| Atlas接続string 。 詳しくは、「ドライバーによる接続 」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
以下の例では、インデックス定義を行います。
Atlas ベクトル検索インデックスで、
plot_embedding
フィールドをvector
型として、genres
フィールドとyear
フィールドをfilter
型としてインデックスします。plot_embedding
フィールドをベクトル埋め込みフィールドとして指定します。このフィールドには、OpenAI のtext-embedding-ada-002
埋め込みモデルを使用して作成された埋め込みが含まれます。1536
ベクトル次元を指定し、dotProduct
関数を使用して類似性を測定します。
このインデックス定義は、ベクトル検索を実行するためのベクトル埋め込みフィールド(plot_embedding
)のみをインデックスします。
以下をコピーして作成したファイルに貼り付け、<connectionString>
プレースホルダー値を置き換えます。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.model.SearchIndexModel; 6 import com.mongodb.client.model.SearchIndexType; 7 import org.bson.Document; 8 import org.bson.conversions.Bson; 9 10 import java.util.Collections; 11 import java.util.List; 12 13 public 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") 34 .append("numDimensions", 1536) 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 Atlas to build the index 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
)。
以下をコピーして作成したファイルに貼り付け、<connectionString>
プレースホルダー値を置き換えます。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.model.SearchIndexModel; 6 import com.mongodb.client.model.SearchIndexType; 7 import org.bson.Document; 8 import org.bson.conversions.Bson; 9 10 import java.util.Arrays; 11 import java.util.Collections; 12 import java.util.List; 13 14 public 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") 35 .append("numDimensions", 1536) 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 Atlas to build the index 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 }
MongoDB Node ドライバーv 6.6.0以降を使用してコレクション用に Atlas Vector Search インデックスを作成するには、次の手順を実行します。
.js
ファイルを作成し、ファイル内にインデックスを定義します。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("<databaseName>"); 11 const collection = database.collection("<collectionName>"); 12 13 // define your Atlas 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 } 57 run().catch(console.dir);
例
vector-index.js
という名前のファイルを作成します。
以下の値を置き換えて、ファイルを保存します。
| Atlas接続string 。 詳しくは、「ドライバーによる接続 」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
例
以下をコピーして vector-index.js
ファイルに貼り付け、<connectionString>
プレースホルダー値を置き換えます。 次のインデックス定義は、Atlas ベクトル検索インデックスで、plot_embedding
フィールドをvector
タイプとしてインデックス化し、genres
フィールドと year
フィールドを filter
タイプとしてインデックス化します。 plot_embedding
フィールドには、 OpenAI の text-embedding-ada-002
埋め込みモデルを使用して作成された埋め込みが含まれます。 インデックス定義では、1536
ベクトル次元を指定し、dotProduct
関数を使用して類似性を測定します。
次のインデックス定義は、ベクトル検索を実行するためにベクトル埋め込みフィールド( plot_embedding
)のみをインデックスします。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("sample_mflix"); 11 const collection = database.collection("embedded_movies"); 12 13 // define your Atlas Vector Search index 14 const index = { 15 name: "vector_index", 16 type: "vectorSearch", 17 definition: { 18 "fields": [ 19 { 20 "type": "vector", 21 "numDimensions": 1536, 22 "path": "plot_embedding", 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 } 54 run().catch(console.dir);
このインデックス定義は、次のフィールドをインデックスします。
データを事前にフィルタリングするためのstringフィールド(
genres
)と数値フィールド(year
)。事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド(
plot_embedding
)。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("sample_mflix"); 11 const collection = database.collection("embedded_movies"); 12 13 // define your Atlas Vector Search index 14 const index = { 15 name: "vector_index", 16 type: "vectorSearch", 17 definition: { 18 "fields": [ 19 { 20 "type": "vector", 21 "numDimensions": 1536, 22 "path": "plot_embedding", 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 } 62 run().catch(console.dir);
この例の実行可能なバージョンを Python エディタとして使用します。
PyMongoドライバー v 以降を使用してコレクション用に Atlas4.7 ベクトル検索インデックスを作成するには、次の手順を実行します。
.py
ファイルを作成し、ファイル内にインデックスを定義します。
1 import pymongo 2 from pymongo.mongo_client import MongoClient 3 from pymongo.operations import SearchIndexModel 4 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 model, then create the search index 14 search_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 34 result = collection.create_search_index(model=search_index_model) 35 print("New search index named " + result + " is building.") 36 37 # Wait for initial sync to complete 38 print("Polling to check if the index is ready. This may take up to a minute.") 39 predicate=None 40 if predicate is None: 41 predicate = lambda index: index.get("queryable") is True 42 43 while True: 44 indices = list(collection.list_search_indexes(result)) 45 if len(indices) and predicate(indices[0]): 46 break 47 time.sleep(5) 48 print(result + " is ready for querying.") 49 50 client.close()
詳細については、「 create_search_index() 」を参照してください。 使用して複数のドキュメントを挿入できます。
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 def 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_indexs() 」を参照してください。 使用して複数のドキュメントを挿入できます。
例
vector-index.py
という名前のファイルを作成します。
以下の値を置き換えて、ファイルを保存します。
| Atlas接続string 。 詳しくは、「ドライバーによる接続 」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
例
以下をコピーして vector-index.py
に貼り付け、<connectionString>
プレースホルダー値を置き換えます。 次のインデックス定義は、Atlas ベクトル検索インデックスで、plot_embedding
フィールドをvector
タイプとしてインデックス化し、genres
フィールドと year
フィールドを filter
タイプとしてインデックス化します。 plot_embedding
フィールドには、 OpenAI の text-embedding-ada-002
埋め込みモデルを使用して作成された埋め込みが含まれます。 インデックス定義では、1536
ベクトル次元を指定し、dotProduct
関数を使用して類似性を測定します。
この例の実行可能なバージョンを Python エディタとして使用します。
次のインデックス定義は、ベクトル検索を実行するためにベクトル埋め込みフィールド( plot_embedding
)のみをインデックスします。
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 import time 4 5 # Connect to your Atlas deployment 6 uri = "<connectionString>" 7 client = MongoClient(uri) 8 9 # Access your database and collection 10 database = client["sample_mflix"] 11 collection = database["embedded_movies"] 12 13 # Create your index model, then create the search index 14 search_index_model = SearchIndexModel( 15 definition={ 16 "fields": [ 17 { 18 "type": "vector", 19 "path": "plot_embedding", 20 "numDimensions": 1536, 21 "similarity": "dotProduct", 22 "quantization": "scalar" 23 } 24 ] 25 }, 26 name="vector_index", 27 type="vectorSearch" 28 ) 29 30 result = collection.create_search_index(model=search_index_model) 31 print("New search index named " + result + " is building.") 32 33 # Wait for initial sync to complete 34 print("Polling to check if the index is ready. This may take up to a minute.") 35 predicate=None 36 if predicate is None: 37 predicate = lambda index: index.get("queryable") is True 38 39 while True: 40 indices = list(collection.list_search_indexes(result)) 41 if len(indices) and predicate(indices[0]): 42 break 43 time.sleep(5) 44 print(result + " is ready for querying.") 45 46 client.close()
この例の実行可能なバージョンを Python エディタとして使用します。
このインデックス定義は、次のフィールドをインデックスします。
データを事前にフィルタリングするためのstringフィールド(
genres
)と数値フィールド(year
)。事前フィルタリングされたデータに対してベクトル検索を実行するためのベクトル埋め込みフィールド(
plot_embedding
)。
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 import time 4 5 # Connect to your Atlas deployment 6 uri = "<connectionString>" 7 client = MongoClient(uri) 8 9 # Access your database and collection 10 database = client["sample_mflix"] 11 collection = database["embedded_movies"] 12 13 # Create your index model, then create the search index 14 search_index_model = SearchIndexModel( 15 definition={ 16 "fields": [ 17 { 18 "type": "vector", 19 "path": "plot_embedding", 20 "numDimensions": 1536, 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 38 result = collection.create_search_index(model=search_index_model) 39 print("New search index named " + result + " is building.") 40 41 # Wait for initial sync to complete 42 print("Polling to check if the index is ready. This may take up to a minute.") 43 predicate=None 44 if predicate is None: 45 predicate = lambda index: index.get("queryable") is True 46 47 while True: 48 indices = list(collection.list_search_indexes(result)) 49 if len(indices) and predicate(indices[0]): 50 break 51 time.sleep(5) 52 print(result + " is ready for querying.") 53 54 client.close()
Atlas Vector Search インデックスの表示
Atlas UI、Atlas 管理 API、Atlas CLI、 mongosh
、またはサポートされているMongoDB ドライバーから、すべてのコレクションの Atlas Vector Search インデックスを表示できます。
必要なアクセス権
Atlas Vector Search インデックスを表示するには、 Project Search Index Editor
以上のロールが必要です。
注意
mongosh
コマンドまたはドライバーヘルパーメソッドを使用して、すべての Atlas クラスター階層の Atlas ベクトル検索インデックスを検索できます。サポートされているドライバー バージョンのリストについては、 サポートされているクライアント を参照してください。
手順
➤ [言語の選択]ドロップダウン メニューを使用して、このセクション内の例の言語を設定します。
Atlas Administration API を使用してコレクションのすべての Atlas Vector Search インデックスを検索するには、データベースとコレクションの名前を指定して Atlas Search indexes
エンドポイントにGET
リクエストを送信します。
1 curl --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 つのコレクションのすべての Atlas Search インデックスを返す 」を参照してください。
Administration Atlas Vector Searchを使用してコレクション用の インデックスをAtlasAPI 1GET
つ取得するには、取得対象のインデックスの一意のAtlas Searchindexes
IDまたは名前(4 行)を指定して エンドポイントに リクエストを送信します。
1 curl --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 を使用してコレクションの Atlas Vector Search インデックスを返すには、次の手順を実行します。
次のコマンドを実行して、コレクションのインデックスを検索します。
atlas clusters search indexes list --clusterName [cluster_name] --db <db-name> --collection <collection-name>
コマンドで、次のプレースホルダー値を置き換えます。
cluster-name
- インデックス作成されたコレクションを含む Atlas クラスターの名前。db-name
- インデックスを検索するコレクションを含むデータベースの名前。collection-name
- インデックスを検索するコレクションの名前。
コマンド構文とパラメーターについて詳しくは、Atlas CLI ドキュメントのAtlas クラスター検索インデックス リストコマンドを参照してください。
AtlasGoClustersAtlas で、プロジェクトの ページにGoします。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
ページには、ページのインデックスに関する次の詳細が表示されます。
名前 | インデックスを識別するラベル。 |
インデックス タイプ | Atlas Search または Atlas Vector Search インデックスを示すラベル。 値には、次のものが含まれます。
|
インデックス フィールド | このインデックスがインデックスを作成するフィールドを含むリスト。 |
ステータス | クラスターのプライマリノード上のインデックスの現在の状態。 有効な値については、「 インデックス ステータス 」を参照してください。 |
サイズ | プライマリ ノードのインデックスのサイズ。 |
ドキュメント | コレクション内のドキュメントの総数のうち、インデックスが作成されたドキュメントの数。 |
アクション | インデックスに対して実行できるアクション。 ここでは、次の作業が可能です。 Search Tester UIでは、 |
mongosh
を使用してコレクションの Atlas Vector Search インデックスを表示するには、次の手順を実行します。
mongosh
を使用して Atlas クラスターに接続します。
詳しくは、「 mongosh
経由で接続 」を参照してください。
db.collection.getSearchIndexes()
メソッドを実行します。
db.collection.getSearchIndexes()
メソッドの構文は次のとおりです。
1 db.<collectionName>.getSearchIndexes( "<index-name>" );
C# ドライバー 3.1.0 以降を使用してコレクションの Atlas Vector Search インデックスを表示するには、次の手順を実行します。
.cs
ファイルを作成し、.List()
メソッドを使用してコレクションのインデックスを取得します。
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 6 public 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 }
以下の値を置き換えて、ファイルを保存します。
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| コレクションを含むデータベースの名前。 |
| コレクションの名前。 |
MongoDB Goドライバー v2.0 以降を使用してコレクションの Atlas ベクトル検索インデックスを表示するには、次の手順を実行します。
get-index.go
という名前のファイルを作成し、SearchIndexes().List()
メソッドを使用してインデックスを検索します。
1 package main 2 3 import ( 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 14 func 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 }
以下の値を置き換えて、ファイルを保存します。
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| コレクションを含むデータベース。 |
| インデックスを検索するコレクション。 |
| 特定のインデックスを検索する場合は、インデックスの名前。コレクションのすべてのインデックスを返すには、検索インデックスオプションを作成するときに、この値を省略し、 |
MongoDB Java ドライバー v5.2.0 以降を使用してコレクションの Atlas Vector Search インデックスを表示するには、次の手順を実行します。
.java
ファイルを作成し、listSearchIndexes()
メソッドを使用してインデックスを検索します。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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 }
以下の値を置き換えて、ファイルを保存します。
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| コレクションを含むデータベース。 |
| インデックスを検索するコレクション。 |
| 特定のインデックスを検索する場合は、インデックスの名前。 コレクションのすべてのインデックスを返すには、この値を省略します。 |
MongoDB Node ドライバーv 6.6.0以降を使用してコレクションの Atlas Vector Search インデックスを表示するには、次の手順を実行します。
.js
ファイルを作成し、listSearchIndexes()
メソッドを使用してインデックスを検索します。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 20 run().catch(console.dir);
以下の値を置き換えて、ファイルを保存します。
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| コレクションを含むデータベース。 |
| インデックスを検索するコレクション。 |
| 特定のインデックスを検索する場合は、インデックスの名前。 コレクションのすべてのインデックスを返すには、この値を省略します。 |
この例の実行可能なバージョンを Python エディタとして使用します。
PyMongoドライバー v 4.7以降を使用してコレクションの Atlas Vector Search インデックスを表示するには、次の手順を実行します。
.py
ファイルを作成し、list_search_indexes()
メソッドを使用してコレクションのインデックスを取得します。
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 # Get a list of the collection's search indexes and print them 12 cursor = collection.list_search_indexes() 13 for index in cursor: 14 print(index)
詳しくは、 list_search_indexs() を参照してください 使用して複数のドキュメントを挿入できます。
以下の値を置き換えて、ファイルを保存します。
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| コレクションを含むデータベースの名前。 |
| コレクションの名前。 |
Atlas Vector Search インデックスの編集
既存の Atlas Vector Search インデックスのインデックス定義は、Atlas UI、Atlas Administration API、Atlas CLI、 mongosh
、またはサポートされているMongoDB ドライバーから変更できます。 インデックスの名前を変更したり、インデックス タイプを変更したりすることはできません。 インデックスの名前またはタイプを変更する必要がある場合は、新しいインデックスを作成し、古いインデックスを削除する必要があります。
重要
インデックスを編集すると、Atlas ベクトル検索 はそのインデックスを再構築します。インデックスの再ビルド中も、古いインデックス定義を使用してベクトル検索クエリを引き続き実行できます。インデックスの再構築が完了すると、古いインデックスは自動的に置き換えられます。このプロセスは Atlas Search インデックスと同様です。詳しくは、Atlas Search インデックスの作成と更新 を参照してください。
必要なアクセス権
Atlas Vector Search インデックスを編集するには、 Project Search Index Editor
以上のロールが必要です。
注意
mongosh
コマンドまたはドライバーヘルパーメソッドを使用して、すべての Atlas クラスター階層の Atlas ベクトル検索インデックスを編集できます。サポートされているドライバー バージョンのリストについては、 「サポートされているクライアント」 を参照してください。
手順
➤ [言語を選択 ] ドロップダウン メニューを使用して、インデックスの編集に使用するクライアントを選択します。
Atlas Administration API を使用してコレクションの Atlas Vector Search インデックスを編集するには、編集するインデックスの一意の ID または名前( 4行)を指定して Atlas Search indexes
エンドポイントにPATCH
リクエストを送信します。
1 curl --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 を使用してコレクションの Atlas Vector Search インデックスを編集するには、次の手順を実行します。
.json
ファイルを作成し、ファイル内にインデックスへの変更を定義します。
インデックス定義は、次の形式のようになります。
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 }
以下のプレースホルダー値を置き換えて、ファイルを保存します。
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。 インデックス名を省略すると、Atlas Vector Search はインデックスに |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
以下のコマンドを実行して、インデックスを更新します。
atlas clusters search indexes update <indexId> --clusterName [cluster_name] --file [vector-_index].json
コマンドで、次のプレースホルダー値を置き換えます。
cluster_name
- インデックスを更新するコレクションを含む Atlas クラスターの名前。vector_index
- Atlas Vector Search インデックスの変更されたインデックス定義を含むJSONファイルの名前
コマンド構文とパラメーターについて詳しくは、Atlas CLI ドキュメントのAtlas クラスター検索インデックス更新コマンド を参照してください。
AtlasGoClustersAtlas で、プロジェクトの ページにGoします。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
インデックスを編集します。
編集する
vectorSearch
型インデックスを見つけます。そのインデックスの「Actions」列にある をクリックします。
Edit With Visual Editor を選択してガイド付き体験を行うか、Edit With JSON Editor を選択して生のインデックス定義を編集してください。
現在の構成設定を確認し、必要に応じて編集します。
Atlas Vector Search インデックスのフィールドの詳細については、 「ベクトル検索のフィールドにインデックスを作成する方法」 を参照してください。
変更を適用するには、 Saveをクリックします。
インデックスのステータスがActiveからBuildingに変わります。 この状態では、アップデートされたインデックスが使用可能になるまで、Atlas Vector Search が古いインデックスを削除しないため、古いインデックスを使用し続けることができます。 ステータスがActiveに戻ったら、変更されたインデックスは使用可能になります。
mongosh
を使用してコレクションの Atlas Vector Search インデックスを編集するには、次の手順を実行します。
mongosh
を使用して Atlas クラスターに接続します。
詳しくは、「 mongosh
経由で接続 」を参照してください。
db.collection.updateSearchIndex()
メソッドを実行します。
db.collection.updateSearchIndex()
メソッドの構文は次のとおりです。
1 db.<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 以降を使用してコレクションの Atlas Vector Search インデックスを更新するには、次の手順を実行します。
.cs
ファイルを作成し、ファイル内にインデックスへの変更を定義します。
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 6 public 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 }
以下の値を置き換えて、ファイルを保存します。
| Atlas接続string 。 詳しくは、「ドライバーによる接続 」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの構成。インデックス名を省略すると、 はデフォルトで |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
MongoDB Goドライバー v 以降を使用してコレクションの Atlas2.0 ベクトル検索インデックスを更新するには、次の手順を実行します。
edit-index.go
というファイルを作成し、ファイルにインデックスの変更を定義します。
1 package main 2 3 import ( 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 12 func 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 }
以下の値を置き換えて、ファイルを保存します。
| Atlas接続string 。 詳しくは、「ドライバーによる接続 」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
MongoDB Java ドライバー v5.2.0 以降を使用してコレクションの Atlas Vector Search インデックスを編集するには、次の手順を実行します。
.java
ファイルを作成し、ファイル内にインデックスへの変更を定義します。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 import org.bson.conversions.Bson; 7 8 import java.util.Collections; 9 10 public 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 }
以下の値を置き換えて、ファイルを保存します。
| Atlas接続string 。 詳しくは、「ドライバーによる接続 」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
MongoDB Node ドライバーv 6.6.0以降を使用してコレクションの Atlas Vector Search インデックスを更新するには、次の手順を実行します。
.js
ファイルを作成し、ファイル内にインデックスへの変更を定義します。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("<databaseName>"); 11 const collection = database.collection("<collectionName>"); 12 13 // define your Atlas 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 } 41 run().catch(console.dir);
以下の値を置き換えて、ファイルを保存します。
| Atlas接続string 。 詳しくは、「ドライバーによる接続 」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
この例の実行可能なバージョンを Python エディタとして使用します。
PyMongoドライバー v 4.7以降を使用してコレクションの Atlas Vector Search インデックスを更新するには、次の手順を実行します。
.py
ファイルを作成し、ファイル内にインデックスへの変更を定義します。
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 definition = { 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 29 collection.update_search_index("<indexName>", definition)
詳しくは、 update_search_index() 使用して複数のドキュメントを挿入できます。
以下の値を置き換えて、ファイルを保存します。
| Atlas接続string 。 詳しくは、「ドライバーによる接続 」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの構成。インデックス名を省略すると、 はデフォルトで |
| Atlas Vector Search がインデックス作成時およびクエリ時に強制されるベクトル次元の数。 |
| インデックスするベクトル フィールドとフィルター フィールド。 |
Atlas Vector Search インデックスの削除
Atlas Vector Search インデックスは、Atlas UI、Atlas Administration API、Atlas CLI、 mongosh
、またはサポートされているMongoDB ドライバーからいつでも削除できます。
必要なアクセス権
Atlas Vector Search インデックスを削除するには、 Project Search Index Editor
以上のロールが必要です。
注意
mongosh
コマンドまたはドライバーヘルパーメソッドを使用して、すべての Atlas クラスター階層上の Atlas ベクトル検索インデックスを削除できます。サポートされているドライバー バージョンのリストについては、 サポートされているクライアント を参照してください。
手順
➤ [言語を選択 ] ドロップダウン メニューを使用して、インデックスを削除するために使用するクライアントを選択します。
Atlas Administration API を使用してコレクションの Atlas Vector Search インデックスを削除するには、一意の ID または削除するインデックスの名前を指定して、Atlas Search indexes
エンドポイントにDELETE
リクエストを送信します。
1 curl --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 を使用してコレクションの Atlas Vector Search インデックスを削除するには、次の手順を実行します。
コマンドを実行してインデックスを削除します。
atlas clusters search indexes delete <indexId> [options]
コマンドで、 indexId
プレースホルダー値を削除するインデックスの一意の識別子に置き換えます。
コマンド構文とパラメーターについて詳しくは、Atlas CLI ドキュメントのAtlas クラスター検索インデックス削除コマンドを参照してください。
AtlasGoClustersAtlas で、プロジェクトの ページにGoします。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
mongosh
を使用してコレクションの Atlas Vector Search インデックスを削除するには、次の手順を実行します。
mongosh
を使用して Atlas クラスターに接続します。
詳しくは、「 mongosh
経由で接続 」を参照してください。
db.collection.dropSearchIndex()
メソッドを実行します。
db.collection.dropSearchIndex()
メソッドの構文は次のとおりです。
1 db.<collectionName>.dropSearchIndex( "<index-name>" );
C# ドライバー 3.1.0 以降を使用してコレクションの Atlas Vector Search インデックスを削除するには、次の手順を実行します。
.cs
ファイルを作成し、DropOne()
メソッドを使用してインデックスを削除します。
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 6 public 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 }
以下の値を置き換えて、ファイルを保存します。
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| コレクションを含むデータベースの名前。 |
| コレクションの名前。 |
| 削除するインデックスの名前。 |
MongoDB Goドライバー v 以降を使用してコレクションの Atlas ベクトル検索インデックスを削除するには、次の手順を実行します。2.0
delete-index.go
というファイルを作成し、SearchIndexes().DropOne()
メソッドを使用してインデックスを削除します。
1 package main 2 3 import ( 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 12 func 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 }
以下の値を置き換えて、ファイルを保存します。
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
MongoDB Java ドライバー v5.2.0 以降を使用してコレクションの Atlas Vector Search インデックスを削除するには、次の手順を実行します。
.java
ファイルを作成し、collection.dropSearchIndex()
メソッドを使用してインデックスを削除します。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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 }
以下の値を置き換えて、ファイルを保存します。
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
MongoDB Node ドライバーv 6.6.0以降を使用してコレクションの Atlas Vector Search インデックスを削除するには、次の手順を実行します。
.js
ファイルを作成し、dropSearchIndex()
メソッドを使用してインデックスを削除します。
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 20 run().catch(console.dir);
以下の値を置き換えて、ファイルを保存します。
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| インデックスを作成するコレクションを含むデータベース。 |
| インデックスを作成するコレクション。 |
| インデックスの名前。インデックス名を省略すると、 はデフォルトで |
この例の実行可能なバージョンを Python エディタとして使用します。
PyMongoドライバー v 4.7以降を使用してコレクションの Atlas Vector Search インデックスを削除するには、次の手順を実行します。
.py
ファイルを作成し、drop_search_index()
メソッドを使用してインデックスを削除します。
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 # Delete your search index 12 collection.drop_search_index("<indexName>")
詳細については、 drop_search_index() 使用して複数のドキュメントを挿入できます。
以下の値を置き換えて、ファイルを保存します。
| Atlas 接続文字列。詳しくは、「ドライバーによる接続」を参照してください。 |
| コレクションを含むデータベースの名前。 |
| コレクションの名前。 |
| 削除するインデックスの名前。 |
インデックスのステータス
Atlas Vector Search インデックスを作成すると、 Status列にはクラスターのプライマリ ノードにおけるインデックスの現在の状態が表示されます。 クラスタ内のすべてのノードにおけるインデックスの状態を表示するには、ステータスの下にあるView status detailsリンクをクリックします。
Status 列が Active の場合、インデックスは使用可能です。そのほかの状態の場合は、インデックスに対するクエリに不完全な結果が返される場合があります。
ステータス | 説明 |
---|---|
開始前 | Atlas によるインデックスの構築は開始されていません。 |
最初の同期 | Atlas はインデックスを構築中、または編集したインデックスを再構築中です。インデックスがこの状態のとき、次の状況が発生します。
|
アクティブ | インデックスをいつでも使用できます。 |
リカバリ中 | |
失敗 | Atlas によるインデックスのビルドは失敗しました 。 View status details モーダルウィンドウのエラーを使用して、問題のトラブルシューティングを行います。詳しくは、問題の修正 を参照してください。 |
削除中 | Atlas はクラスター ノードからインデックスを削除しています。 |
Atlas によるインデックスの構築中および構築の完了後、Documents 列にはインデックス済みドキュメントの割合と数が表示されます。また、この列には、コレクション内の総ドキュメント数も表示されます。