Docs Menu
Docs Home

MongoDB ベクトル検索を使用した埋め込みの自動生成

MongoDB ベクトル検索を構成して、クラスター内のテキストデータのベクトル埋め込みを自動的に生成および管理できます。 M10 以上の Atlas クラスターに 1 クリックのAIセマンティック検索インデックスを作成し、Vorage AI埋め込みモデルを使用すると、インデックス作成、アップデート、ベクトルによるクエリが簡素化されます。

自動埋め込みを有効にすると、 MongoDB ベクトル検索 は、自動コレクション用にインデックスされたフィールドに対して、インデックス時に指定された埋め込みモデルを使用して埋め込みを自動的に生成し、クエリ時にクエリ内のテキスト string を使用してフィールドを自動的に生成します。

重要

MongoDB ベクトル検索 の自動埋め込みは、任意のクラウドプロバイダー上の任意の M10 以上のクラスターで使用できます。ただし、ベクトル埋め込みを生成するための推論プロセスを取り扱うサービスは、Google Cloud Platformで実行されます。 つまり、クラスターのクラウドプロバイダーに関係なく、埋め込み生成と取得のためにデータがGoogle Cloud Platformに送信されます。 エンタープライズ レベルのセキュリティを提供しているため、データは クラスターにのみ保存されます。

埋め込みモデルは、共有のマルチテナント推論プラットフォームで実行されます。したがって、プレビュー期間中は、100kドキュメント未満のデータセットを使用し、負荷テストではなく機能の評価のみを目的としてクエリを実行する必要があります。より高い制限を持つユースケースがある場合は、アカウントチームにお問い合わせください。

ワークロードには厳密なレート制限はありませんが、グローバルな制限があります。クエリがレート制限エラー(エラー 409)を返す場合は、アプリケーションコードでバックオフを実行し、再試行します。これにより、アプリケーションはレート制限をグレースフルに処理し、継続的な機能を確保できます。

自動埋め込みを使用してベクトル検索を有効にするには、次のものが必要です。

  • M10 またはそれ以上のクラスター

  • 自動埋め込み用にインデックステキストフィールドを持つコレクション。

  • 次のクライアントの 1 つ:

    • インデックスを作成するための Atlas UI

    • mongosh 、インデックスの作成とクエリの実行中用

    • インデックスの作成とクエリの実行中には Node Driver 以上が必要6.6.0

    • 4.7インデックスの作成とクエリの実行中用にPythonドライバー 以上

    次のドロップダウン メニューを使用して、このページの手順のクライアントを設定します。

次のセクションでは、テキストフィールドの埋め込みの自動生成を有効にするためのMongoDB ベクトル検索インデックスの構文とフィールドについて説明し、自動埋め込み用にインデックスを構成する手順について説明します。

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

以下は、埋め込みの自動生成を有効にするための構文です。

1{
2 "fields": [
3 {
4 "type": "text",
5 "path": "<field-name>",
6 "model": "voyage-3-large | voyage-3.5 | voyage-3.5-lite"
7 }
8 ]
9}

インデックス定義では、次のフィールドが必要です。

フィールド

タイプ

説明

type

string

フィールドの型。自動埋め込みの場合、これは text である必要があります。

path

string

自動埋め込み用にインデックスするコレクション内のフィールドの名前。

model

string

インデックスの埋め込みの生成に使用する Voyage AI 埋め込みモデル。次のいずれかのモデルを指定できます。

  • voyage-3-large - 言語とドメイン全体で最高品質の検索。

  • voyage-3.5 - 多言語使用と一般的な検索精度のバランス調整されたモデル。

  • voyage-3.5-lite -レイテンシと 低コストのために最適化された軽量、高速モデル。

インデックスの作成 後に埋め込みモデルを変更すると、 MongoDB ベクトル検索 はデータセットの新しい埋め込みを生成します。MongoDB ベクトル検索 が埋め込みを生成している間も、古い埋め込みを使用してクエリを続行できます。古い埋め込みが新しい埋め込みモデルの埋め込みに置き換えられると、 MongoDB ベクトル検索 は古い埋め込みを削除します。

自動埋め込みのインデックスフィールドは、次の vector 型のインデックスフィールドと相互に排他的です。

  • numDimensions

  • similarity

  • quantization

コレクションにすでに埋め込みがある場合は、vector 型のフィールドを使用して埋め込みのインデックスを作成する必要があります。埋め込みを使用したフィールドのインデックス作成について詳しくは、「ベクトル検索のフィールドにインデックスを作成する方法」をご覧ください。

埋め込みを自動生成するためにテキストフィールドをインデックス、独自の埋め込みを持つフィールドもインデックスする場合は、textvector の両方のタイプでインデックスを作成できます。MongoDB ベクトル検索 は、text タイプとしてインデックス付けされたフィールドのみに対するクエリの埋め込みを自動的に生成します。vector タイプとしてインデックス付けされたフィールドを検索するには、クエリに埋め込みを指定する必要があります。

MongoDB ベクトル検索 filter タイプを使用して、データを事前にフィルタリングするためのフィールドのインデックスも可能です。事前フィルタリングにより、類似性比較を実行するドキュメントの数が減るため、クエリのレイテンシが削減され、検索結果の精度が向上します。データの事前フィルタリングの詳細については、 filter タイプについて を参照してください。

次の手順では、 MongoDB ベクトル検索インデックスへの自動埋め込みを有効にする手順について説明します。sample_mflix.movies データセットをロードした場合、手順の例は、コレクションの fullplotフィールドの自動埋め込みを有効にする方法を示しています。

1
  1. まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー

  2. まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。

  3. サイドバーで、 Database見出しの下のClustersをクリックします。

[ Clusters (クラスター) ] ページが表示されます。

2

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

3

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

Search Type

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

Index Name and Data Source

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

  • Index Name: <INDEX-NAME>

  • Database and Collection:

    • <DATABASE-NAME>

    • <COLLECTION-NAME>

Configuration Method

JSON Editor を選択します。

たとえば、インデックス名として「movies_automated_embeddings」と入力し、sample_mflixmoviesDatabase and Collection ドロップダウンから選択します。

4

JSON エディターで、次のインデックス定義を入力します。

1{
2 "fields": [
3 {
4 "type": "text",
5 "path": "<FIELD-NAME>",
6 "model": "voyage-3-large | voyage-3.5 | voyage-3.5-lite"
7 }
8 ]
9}

例えば、voyage-3-largeモデルを使用してコレクションのfullplotフィールドに自動埋め込みを可能にするインデックスを作成するには、次のように入力します。

1{
2 "fields": [
3 {
4 "type": "text",
5 "path": "fullplot",
6 "model": "voyage-3-large"
7 }
8 ]
9}
5
  1. [Next] をクリックします。

  2. インデックス構成を確認し、[Create Vector Search Index] をクリックします。

注意

インデックスの作成が完了するまでに時間がかかることがあります。インデックスが作成中の場合、Atlas UI の Status 列に Pending が表示されます。インデックスの作成が完了すると、Atlas UI のStatus 列にReady が表示されます。

1

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

2

切り替えるには、次のコマンドを実行します。

use <DATABASE-NAME>

ここで、<DATABASE-NAME> は、使用するデータベースの名前です。

例、 を、moviesコレクションを含む sample_mflixデータベースに切り替えるには、次のコマンドを実行します。

use sample_mflix
3

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

1db.<COLLECTION-NAME>.createSearchIndex(
2 "<INDEX-NAME>",
3 "vectorSearch",
4 {
5 "fields": [
6 {
7 "type": "text",
8 "path": "<FIELD-NAME>",
9 "model": "voyage-3-large | voyage-3.5 | voyage-3.5-lite"
10 },
11 {
12 "type": "filter",
13 "path": "<FIELD-NAME>"
14 },
15 ...
16 ]
17 }
18);

例、コレクションの fullplotフィールドの voyage-3-large モデルを使用して、自動埋め込みを有効にするインデックスを作成するには、ターミナルで次のコマンドを実行します。

1db.movies.createSearchIndex(
2 "movies_automated_embeddings",
3 "vectorSearch",
4 {
5 "fields": [
6 {
7 "type": "text",
8 "path": "fullplot",
9 "model": "voyage-3-large"
10 }
11 ]
12 }
13);
1

ターミナルで次のコマンドを実行して、 auto-embeddings-projectという名前の新しいディレクトリを作成し、プロジェクトを初期化します。

mkdir auto-embeddings-project
cd auto-embeddings-project
npm init -y
2
touch <file-name>.js

例えば、create_index.jsという名前のファイルを作成します。

touch create_index.js
3
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<CONNECTION-STRING>";
5const client = new MongoClient(uri);
6
7async function run() {
8 try {
9 const database = client.db("<DATABASE-NAME>");
10 const collection = database.collection("<COLLECTION-NAME>");
11
12 // define your MongoDB Vector Search index
13 const index = {
14 "name": "<INDEX-NAME>",
15 "type": "vectorSearch",
16 "definition": {
17 "fields": [
18 {
19 "type": "vector",
20 "path": "<FIELD-NAME>",
21 "model": "voyage-3-large | voyage-3.5 | voyage-3.5-lite"
22 },
23 ]
24 }
25 }
26 // run the helper method
27 await collection.createSearchIndex("<INDEX-NAME>", index);
28 } finally {
29 await client.close();
30 }
31}
32run().catch(console.dir);

例、sample_mflix.movies名前空間の fullplotフィールドの voyage-3-large モデルを使用して自動埋め込みを有効にするインデックスを作成するには、以下をコピーして、create_index.jsファイルに貼り付けます。

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<CONNECTION-STRING>";
5const client = new MongoClient(uri);
6
7async function run() {
8 try {
9 const database = client.db("sample_mflix");
10 const collection = database.collection("movies");
11
12 // define your MongoDB Vector Search index
13 const index = {
14 "name": "movies_automated_embeddings",
15 "type": "vectorSearch",
16 "definition": {
17 "fields": [
18 {
19 "type": "text",
20 "path": "fullplot",
21 "model": "voyage-3-large"
22 }
23 ]
24 }
25 }
26 // run the helper method
27 await collection.createSearchIndex(index);
28 } finally {
29 await client.close();
30 }
31}
32run().catch(console.dir);
4

<CONNECTION-STRING>

Atlas クラスターの接続文字列。

<DATABASE-NAME>

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

<COLLECTION-NAME>

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

<FIELD-NAME>

自動埋め込み用にインデックスするコレクション内のフィールドの名前。

<INDEX-NAME>

作成するインデックスの名前。

5
node <file-name>.js

例として、create_index.js ファイルに定義されているインデックスを作成するには、ターミナルで次のコマンドを実行します。

node create_index.js
1
touch <file-name>.py

例えば、create_index.pyという名前のファイルを作成します。

touch create_index.py
2
1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4client = pymongo.MongoClient("<CONNECTION-STRING>")
5db = client["<DATABASE-NAME>"]
6collection = db["<COLLECTION-NAME>"]
7
8search_index_model = SearchIndexModel(
9 definition={
10 "fields": [
11 {
12 "type": "text",
13 "path": "<FIELD-NAME>",
14 "model": "voyage-3-large | voyage-3.5 | voyage-3.5-lite"
15 }
16 ]
17 },
18 name="<INDEX-NAME>",
19 type="vectorSearch",
20)
21result = collection.create_search_index(model=search_index_model)
22print(result)

例、sample_mflix.movies名前空間の fullplotフィールドの voyage-3-large モデルを使用して自動埋め込みを有効にするインデックスを作成するには、以下をコピーして、create_index.pyファイルに貼り付けます。

1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4client = MongoClient("<CONNECTION-STRING>")
5db = client["sample_mflix"]
6collection = db["movies"]
7
8search_index_model = SearchIndexModel(
9 definition={
10 "fields": [
11 {
12 "type": "text",
13 "path": "fullplot",
14 "model": "voyage-3-large"
15 }
16 ]
17 },
18 name="movies_automated_embeddings",
19 type="vectorSearch",
20)
21result = collection.create_search_index(model=search_index_model)
22print(result)
3

<CONNECTION-STRING>

Atlas クラスターの接続文字列。

<database-name>

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

<collection-name>

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

<field-name>

自動埋め込み用にインデックスするコレクション内のフィールドの名前。

<index-name>

作成するインデックスの名前。

4
python <file-name>.py

例として、create_index.py ファイルに定義されているインデックスを作成するには、ターミナルで次のコマンドを実行します。

python create_index.py

自動埋め込みを使用してインデックスを作成したら、インデックス付きフィールドに対してテキスト クエリを実行できます。MongoDB ベクトル検索 は、インデックスで指定された同じ埋め込みモデルを使用して、クエリ内のテキスト string の埋め込みを自動的に生成します。埋め込みを使用して、指定されたクエリテキストにセマンティックに類似しているドキュメントをインデックスから検索します。

次のセクションでは、自動埋め込み用にインデックス付けされたフィールドに対してクエリテキストの埋め込みを自動生成するための$vectorSearch パイプラインの構文とフィールドについて説明し、自動埋め込み用にインデックス付けされたフィールドに対してセマンティック検索クエリを実行する方法を説明します。

次の構文は、自動埋め込み用にインデックス付けされたフィールドに対してクエリを実行する方法を示しています。

1{
2 "$vectorSearch": {
3 "index": "<index-name>",
4 "limit": <number-of-results>,
5 "numCandidates": <number-of-candidates>,
6 "path": "<field-to-search>",
7 "query": "<query-string>"
8 }
9}

自動埋め込みを使用するMongoDB ベクトル検索クエリには次のフィールドが必要です。

フィールド
タイプ
必要性
説明

exact

ブール値

条件付き

numCandidates を省略する場合、このフィールドは必須です。numCandidates と相互に排他的です。

UNIX または ANN 検索のどちらを実行するかを指定するフラグ。値は次のいずれかになります。

  • false - Ann検索を実行する場合

  • true - ENN検索を実行する場合

省略した場合、デフォルトは false になります。

index

string

必須

使用するMongoDB ベクトル検索インデックスの名前。

MongoDB ベクトル検索、インデックス名のスペルをうっかり間違えた場合、または指定されたインデックスがクラスター上にまだ存在しない場合には結果が返されません。

limit

数値

必須

結果で返されるドキュメントの数( intのみ)。 numCandidatesを指定する場合、この値はnumCandidatesの値を超えることはできません。

numCandidates

数値

条件付き

exactfalse であるか省略されている場合、このフィールドは必須です。exact と相互排他的です。

検索中に使用する最近傍の数。 値は ( <=10000以下である必要があります。 返されるドキュメント数より小さい数値は指定できません( limit )。

path

string

必須

検索するインデックス付きのベクトルタイプフィールド。

query

string

必須

埋め込みを自動的に生成し、セマンティック検索を実行するテキスト。

インデックスが作成されたフィールドに対して近似最近傍探索または厳密最近傍探索クエリを実行できます。詳細については、「近似最近傍探索検索」および「厳密最近傍探索検索」を参照してください。

自動埋め込み用にインデックス付きされたフィールドに対してベクトル埋め込みを指定することはできません。代わりに、フィールドに対して自然言語クエリを実行する必要があります。自動埋め込み用にインデックスされたフィールドに対して自然言語クエリを実行すると、 MongoDB ベクトル検索 はインデックス付きフィールドと同じ埋め込みモデルを使用してクエリテキストの埋め込みを自動的に生成します。次に、生成された埋め込みを使用して、インデックス付きフィールドに対してセマンティック検索を実行します。

オプションで、クエリに filter フィールドを指定して、 MongoDB ベクトル検索 がセマンティック検索を実行するドキュメントを事前にフィルタリングすることができます。詳細については、 MongoDB ベクトル検索 のプレフィルター を参照してください。

オプションで、結果内のドキュメントのスコアを検索することもできます。詳細については、 MongoDB ベクトル検索 Score を参照してください。

Atlas UIではMongoDB ベクトル検索クエリを実行できません。mongoshクエリを実行するには、 またはサポートされているドライバーを使用します。

1

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

2
use <database-name>

例として、sample_mflix データベースに切り替えるには、ターミナルで次のコマンドを実行します。

use sample_mflix
3

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

1db.<COLLECTION-NAME>.aggregate([
2 {
3 "$vectorSearch": {
4 "index": "<INDEX-NAME>",
5 "path": "<FIELD-NAME>",
6 "query": "<QUERY-TEXT>",
7 "numCandidates": <NUMBER-OF-CANDIDATES-TO-CONSIDER>,
8 "limit": <NUMBER-OF-DOCUMENTS-TO-RETURN>
9 }
10 }
11])

例、moviesコレクションの fullplotフィールドに対してクエリを実行し、young heroes caught in epic struggles between light and darkness にセマンティックに類似する映画のセマンティック検索を実行するには、次のクエリをコピーして貼り付け、実行します。

1db.movies.aggregate([
2 {
3 "$vectorSearch": {
4 "index": "movies_automated_embeddings",
5 "path": "fullplot",
6 "query": "young heroes caught in epic struggles between light and darkness",
7 "numCandidates": 1000,
8 "limit": 10
9 }
10 },
11 {
12 "$project": {
13 "_id": 0,
14 "title": 1,
15 "fullplot": 1,
16 "score": {"$meta": "vectorSearchScore"}
17 }
18 }
19])
1[
2 {
3 title: 'Day Watch',
4 fullplot: 'Anton belongs to the Forces of the Light as well as his powerful girlfriend and apprentice, but his son is a powerful teenager from the Darkness and Anton protects him. When the balance between Light and Darkness is affected by the death of some evil vampires, Anton is framed and accused of the murders, and he chases an ancient chalk that has the power of changing the destiny of its owner.',
5 score: 0.5449697971343994
6 },
7 {
8 title: 'Dungeons & Dragons',
9 fullplot: "The Empire of Izmer has long been a divided land. The Mages - an elite group of magic-users - rule whilst the lowly commoners are powerless. Izmer's young Empress, Savina, wants equality and prosperity for all, but the evil Mage Profion is plotting to depose her and establish his own rule. The Empress possesses a scepter which controls Izmer's Golden Dragons. To challenge her rule, Profion must have the scepter, and tricks the Council of Mages into believing Savina is unfit to hold it. Knowing that Profion will bring death and destruction to Izmer, Savina must find the legendary Rod of Savrille, a mythical rod that has the power to control Red Dragons, a species even mightier than the Gold. Enter two thieves, Ridley and Snails, who unwittingly become instrumental in Savina's search for the Rod. Joined by a feisty Dwarf named Elwood, and helped by the Empress's expert tracker, the Elf Norda, the young heroes go in search of the Rod of Savrille. From the deadly maze of the Thieves Guild at Antius to an Elven Village, secret grotto and abandoned castles, Ridley and his band must outwit Profion's chief henchman Damodar at every turn while, back in Izmer, Profion prepares to do battle with the Empress. All depends on the Rod, but the outcome of the race to reach it first is far from certain, and Izmar's very survival hangs in the balance.",
10 score: 0.5414832830429077
11 },
12 {
13 title: 'Brave Story',
14 fullplot: 'A young boy attempts to change his destiny by entering a magic gateway to another world; but on his quest to find the Tower of Fortune and be granted any wish, he must conjure up all his bravery to battle demons, his friends, and ultimately himself.',
15 score: 0.5404887795448303
16 },
17 {
18 title: 'Justin and the Knights of Valour',
19 fullplot: 'Justin lives in a kingdom where bureaucrats rule and knights have been ousted. His dream is to be become one of the Knights of Valour, like his grandfather was, but his father Reginald, the chief counsel to the Queen, wants his son to follow in his footsteps and become a lawyer. After an inspiring visit to his beloved Grandmother and bidding farewell to his supposed lady-love Lara, Justin leaves home and embarks on a quest to become a knight. Along the way he meets the beautiful, feisty Talia, a quirky wizard called Melquiades, and the handsome Sir Clorex and is mentored by three monks; Blucher, Legantir and Braulio, who teach and test him in the ancient ways of the Knights of Valour. Whilst an unlikely candidate for knighthood, Justin must rise to the challenge quickly when banished former knight Sir Heraclio and his army, lead by Sota, return and threaten to destroy the Kingdom.',
20 score: 0.5374966859817505
21 },
22 {
23 title: 'Forest Warrior',
24 fullplot: 'John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.',
25 score: 0.5331881642341614
26 },
27 {
28 title: 'Forest Warrior',
29 fullplot: 'John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.',
30 score: 0.5331881642341614
31 },
32 {
33 title: 'Catatan (Harian) si Boy',
34 fullplot: "A circle of friends risking their Friendship, Trust, Love and Hope in search of a legend. A young and privileged teenager with a golden heart, beset with challenges and tribulations we face today with the goal to open many young people's mind with inspirations and hopes that drive them in achieving their dreams. To get out of their comfort zone and finish what they started.",
35 score: 0.5322973728179932
36 },
37 {
38 title: 'Bionicle: Mask of Light',
39 fullplot: "In a land of living machines, two young ones are chosen to seek the legendary Mask of Light to reveal the savior of all the lands from the dark forces of the Makuta. During the course of their adventure, they will call on the heroes of their people, the great Toa. These Toa, masters of nature's forces such as Fire, Wind, Earth & Water, try to protect the chosen ones as they seek their destiny.",
40 score: 0.5315042734146118
41 },
42 {
43 title: 'Fear No Evil',
44 fullplot: 'High school student turns out to be personification of Lucifer. Two arch angels in human form (as women) take him on.',
45 score: 0.5295513868331909
46 },
47 {
48 title: 'Tales of Vesperia: The First Strike',
49 fullplot: 'In a mythical kingdom, the mighty Imperial Knights harness a magical substance known as Aer to power their weapons and protect humanity from the monsters of the forest. But something strange is afoot. The Aer is somehow changing, causing the wilderness to waste away and stirring the woodland beasts to attack with greater frequency. As danger creeps steadily closer to civilization, two young recruits - Flynn, the rigid son of a fallen hero, and the rebellious and brash Yuri - must ride with their fellow Imperial Knights to distant ruins in hopes of uncovering the truth behind the transforming Aer. Some will not survive the thrilling journey. Some will be betrayed. If Flynn and Yuri cannot overcome their differences and learn to fight together, all will be lost for the people of the realm.',
50 score: 0.5276793241500854
51 }
52]
1

例えば、automated-embeddings-query.jsという名前のファイルを作成します。

touch automated-embeddings-query.js
2
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas cluster
4const uri = "<CONNECTION-STRING>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 await client.connect();
11
12 // set namespace
13 const database = client.db("<DATABASE-NAME>");
14 const coll = database.collection("<COLLECTION-NAME>");
15
16 // define pipeline
17 const agg = [
18 {
19 '$vectorSearch': {
20 'index': '<INDEX-NAME>',
21 'path': '<FIELD-NAME>',
22 'query': "<QUERY-TEXT>",
23 'numCandidates': <NUMBER-OF-CANDIDATES-TO-CONSIDER>,
24 'limit': <NUMBER-OF-DOCUMENTS-TO-RETURN>
25 }
26 }
27 ];
28 // run pipeline
29 const result = coll.aggregate(agg);
30
31 // print results
32 await result.forEach((doc) => console.dir(JSON.stringify(doc)));
33 } finally {
34 await client.close();
35 }
36}
37run().catch(console.dir);

例、automated-embeddings-query.jsファイルでは、次のコードをコピーして、young heroes caught in epic struggles between light and darkness にセマンティックに似た映画をセマンティック検索するための、moviesコレクションの fullplotフィールドに対するクエリを定義します。

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas cluster
4const uri = "<CONNECTION-STRING>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 await client.connect();
11
12 // set namespace
13 const database = client.db("sample_mflix");
14 const coll = database.collection("movies");
15
16 // define pipeline
17 const agg = [
18 {
19 '$vectorSearch': {
20 'index': 'movies_automated_embeddings',
21 'path': 'fullplot',
22 'query': "young heroes caught in epic struggles between light and darkness",
23 'numCandidates': 1000,
24 'limit': 10
25 }
26 }, {
27 '$project': {
28 '_id': 0,
29 'fullplot': 1,
30 'title': 1,
31 'score': {
32 '$meta': 'vectorSearchScore'
33 }
34 }
35 }
36 ];
37 // run pipeline
38 const result = coll.aggregate(agg);
39
40 // print results
41 await result.forEach((doc) => console.dir(JSON.stringify(doc)));
42 } finally {
43 await client.close();
44 }
45}
46run().catch(console.dir);
3

<CONNECTION-STRING>

クラスター接続文字列。

<DATABASE-NAME>

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

<COLLECTION-NAME>

インデックスフィールドを含むコレクションの名前。

<INDEX-NAME>

インデックスの名前。

<FIELD-NAME>

インデックスフィールドの名前。

<QUERY-TEXT>

埋め込みを生成し、セマンティック検索で使用するテキスト文字列。

<NUMBER-OF-CANDIDATES-TO-CONSIDER>

考慮する最近傍の数。

<NUMBER-OF-DOCUMENTS-TO-RETURN>

結果で返されるドキュメントの数。

4
node <FILE-NAME>.js

ここで、<FILE-NAME> は、作成した .jsファイルの名前です。

例が、automated-embeddings-query.jsファイルの例クエリを実行するには、次のコマンドを実行します。

node automated-embeddings-query.js
'{"title":"Day Watch","fullplot":"Anton belongs to the Forces of the Light as well as his powerful girlfriend and apprentice, but his son is a powerful teenager from the Darkness and Anton protects him. When the balance between Light and Darkness is affected by the death of some evil vampires, Anton is framed and accused of the murders, and he chases an ancient chalk that has the power of changing the destiny of its owner.","score":0.5449697971343994}'
`{"title":"Dungeons & Dragons","fullplot":"The Empire of Izmer has long been a divided land. The Mages - an elite group of magic-users - rule whilst the lowly commoners are powerless. Izmer's young Empress, Savina, wants equality and prosperity for all, but the evil Mage Profion is plotting to depose her and establish his own rule. The Empress possesses a scepter which controls Izmer's Golden Dragons. To challenge her rule, Profion must have the scepter, and tricks the Council of Mages into believing Savina is unfit to hold it. Knowing that Profion will bring death and destruction to Izmer, Savina must find the legendary Rod of Savrille, a mythical rod that has the power to control Red Dragons, a species even mightier than the Gold. Enter two thieves, Ridley and Snails, who unwittingly become instrumental in Savina's search for the Rod. Joined by a feisty Dwarf named Elwood, and helped by the Empress's expert tracker, the Elf Norda, the young heroes go in search of the Rod of Savrille. From the deadly maze of the Thieves Guild at Antius to an Elven Village, secret grotto and abandoned castles, Ridley and his band must outwit Profion's chief henchman Damodar at every turn while, back in Izmer, Profion prepares to do battle with the Empress. All depends on the Rod, but the outcome of the race to reach it first is far from certain, and Izmar's very survival hangs in the balance.","score":0.5414832830429077}`
'{"title":"Brave Story","fullplot":"A young boy attempts to change his destiny by entering a magic gateway to another world; but on his quest to find the Tower of Fortune and be granted any wish, he must conjure up all his bravery to battle demons, his friends, and ultimately himself.","score":0.5404887795448303}'
'{"title":"Justin and the Knights of Valour","fullplot":"Justin lives in a kingdom where bureaucrats rule and knights have been ousted. His dream is to be become one of the Knights of Valour, like his grandfather was, but his father Reginald, the chief counsel to the Queen, wants his son to follow in his footsteps and become a lawyer. After an inspiring visit to his beloved Grandmother and bidding farewell to his supposed lady-love Lara, Justin leaves home and embarks on a quest to become a knight. Along the way he meets the beautiful, feisty Talia, a quirky wizard called Melquiades, and the handsome Sir Clorex and is mentored by three monks; Blucher, Legantir and Braulio, who teach and test him in the ancient ways of the Knights of Valour. Whilst an unlikely candidate for knighthood, Justin must rise to the challenge quickly when banished former knight Sir Heraclio and his army, lead by Sota, return and threaten to destroy the Kingdom.","score":0.5374966859817505}'
'{"title":"Forest Warrior","fullplot":"John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.","score":0.5331881642341614}'
'{"title":"Forest Warrior","fullplot":"John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.","score":0.5331881642341614}'
`{"title":"Catatan (Harian) si Boy","fullplot":"A circle of friends risking their Friendship, Trust, Love and Hope in search of a legend. A young and privileged teenager with a golden heart, beset with challenges and tribulations we face today with the goal to open many young people's mind with inspirations and hopes that drive them in achieving their dreams. To get out of their comfort zone and finish what they started.","score":0.5322973728179932}`
`{"title":"Bionicle: Mask of Light","fullplot":"In a land of living machines, two young ones are chosen to seek the legendary Mask of Light to reveal the savior of all the lands from the dark forces of the Makuta. During the course of their adventure, they will call on the heroes of their people, the great Toa. These Toa, masters of nature's forces such as Fire, Wind, Earth & Water, try to protect the chosen ones as they seek their destiny.","score":0.5315042734146118}`
'{"title":"Fear No Evil","fullplot":"High school student turns out to be personification of Lucifer. Two arch angels in human form (as women) take him on.","score":0.5295513868331909}'
'{"title":"Tales of Vesperia: The First Strike","fullplot":"In a mythical kingdom, the mighty Imperial Knights harness a magical substance known as Aer to power their weapons and protect humanity from the monsters of the forest. But something strange is afoot. The Aer is somehow changing, causing the wilderness to waste away and stirring the woodland beasts to attack with greater frequency. As danger creeps steadily closer to civilization, two young recruits - Flynn, the rigid son of a fallen hero, and the rebellious and brash Yuri - must ride with their fellow Imperial Knights to distant ruins in hopes of uncovering the truth behind the transforming Aer. Some will not survive the thrilling journey. Some will be betrayed. If Flynn and Yuri cannot overcome their differences and learn to fight together, all will be lost for the people of the realm.","score":0.5276793241500854}'
1

例えば、automated-embeddings-query.jsという名前のファイルを作成します。

touch automated-embeddings-query.py
2
1import pymongo
2
3# connect to your Atlas cluster
4client = pymongo.MongoClient("<CONNECTION-STRING>")
5
6# define pipeline
7pipeline = [
8 {
9 '$vectorSearch': {
10 'index': '<INDEX-NAME>',
11 'path': '<FIELD-NAME>',
12 'query': '<QUERY-TEXT>',
13 'numCandidates': <NUMBER-OF-CANDIDATES-TO-CONSIDER>,
14 'limit': <NUMBER-OF-DOCUMENTS-TO-RETURN>
15 }
16 }
17]
18
19# run pipeline
20result = client["<DATABASE-NAME>"]["<COLLECTION-NAME>"].aggregate(pipeline)
21
22# print results
23for i in result:
24 print(i)
25

例、automated-embeddings-query.pyファイルでは、次のコードをコピーして、young heroes caught in epic struggles between light and darkness にセマンティックに似た映画をセマンティック検索するための、moviesコレクションの fullplotフィールドに対するクエリを定義します。

1import pymongo
2
3# connect to your Atlas cluster
4client = pymongo.MongoClient("<CONNECTION-STRING>")
5
6# define pipeline
7pipeline = [
8 {
9 '$vectorSearch': {
10 'index': 'movies_automated_embeddings',
11 'path': 'fullplot',
12 'query': "young heroes caught in epic struggles between light and darkness",
13 'numCandidates': 1000,
14 'limit': 10
15 },
16 },
17 {
18 '$project': {
19 '_id': 0,
20 'title': 1,
21 'fullplot': 1,
22 'score': {'$meta': 'vectorSearchScore'}
23 }
24 }
25]
26
27# run pipeline
28result = client["sample_mflix"]["movies"].aggregate(pipeline)
29
30# print results
31for i in result:
32 print(i)
33
3

<CONNECTION-STRING>

クラスター接続文字列。

<DATABASE-NAME>

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

<COLLECTION-NAME>

インデックスフィールドを含むコレクションの名前。

<INDEX-NAME>

インデックスの名前。

<FIELD-NAME>

インデックスフィールドの名前。

<QUERY-TEXT>

埋め込みを生成し、セマンティック検索で使用するテキスト文字列。

<NUMBER-OF-CANDIDATES-TO-CONSIDER>

考慮する最近傍の数。

<NUMBER-OF-DOCUMENTS-TO-RETURN>

結果で返されるドキュメントの数。

4
python <FILE-NAME>.py

ここで、<FILE-NAME> は、作成した .pyファイルの名前です。

例が、automated-embeddings-query.pyファイルの例クエリを実行するには、次のコマンドを実行します。

python automated-embeddings-query.js
{'title': 'Day Watch', 'fullplot': 'Anton belongs to the Forces of the Light as well as his powerful girlfriend and apprentice, but his son is a powerful teenager from the Darkness and Anton protects him. When the balance between Light and Darkness is affected by the death of some evil vampires, Anton is framed and accused of the murders, and he chases an ancient chalk that has the power of changing the destiny of its owner.', 'score': 0.5449697971343994}
{'title': 'Dungeons & Dragons', 'fullplot': "The Empire of Izmer has long been a divided land. The Mages - an elite group of magic-users - rule whilst the lowly commoners are powerless. Izmer's young Empress, Savina, wants equality and prosperity for all, but the evil Mage Profion is plotting to depose her and establish his own rule. The Empress possesses a scepter which controls Izmer's Golden Dragons. To challenge her rule, Profion must have the scepter, and tricks the Council of Mages into believing Savina is unfit to hold it. Knowing that Profion will bring death and destruction to Izmer, Savina must find the legendary Rod of Savrille, a mythical rod that has the power to control Red Dragons, a species even mightier than the Gold. Enter two thieves, Ridley and Snails, who unwittingly become instrumental in Savina's search for the Rod. Joined by a feisty Dwarf named Elwood, and helped by the Empress's expert tracker, the Elf Norda, the young heroes go in search of the Rod of Savrille. From the deadly maze of the Thieves Guild at Antius to an Elven Village, secret grotto and abandoned castles, Ridley and his band must outwit Profion's chief henchman Damodar at every turn while, back in Izmer, Profion prepares to do battle with the Empress. All depends on the Rod, but the outcome of the race to reach it first is far from certain, and Izmar's very survival hangs in the balance.", 'score': 0.5414832830429077}
{'title': 'Brave Story', 'fullplot': 'A young boy attempts to change his destiny by entering a magic gateway to another world; but on his quest to find the Tower of Fortune and be granted any wish, he must conjure up all his bravery to battle demons, his friends, and ultimately himself.', 'score': 0.5404887795448303}
{'title': 'Justin and the Knights of Valour', 'fullplot': 'Justin lives in a kingdom where bureaucrats rule and knights have been ousted. His dream is to be become one of the Knights of Valour, like his grandfather was, but his father Reginald, the chief counsel to the Queen, wants his son to follow in his footsteps and become a lawyer. After an inspiring visit to his beloved Grandmother and bidding farewell to his supposed lady-love Lara, Justin leaves home and embarks on a quest to become a knight. Along the way he meets the beautiful, feisty Talia, a quirky wizard called Melquiades, and the handsome Sir Clorex and is mentored by three monks; Blucher, Legantir and Braulio, who teach and test him in the ancient ways of the Knights of Valour. Whilst an unlikely candidate for knighthood, Justin must rise to the challenge quickly when banished former knight Sir Heraclio and his army, lead by Sota, return and threaten to destroy the Kingdom.', 'score': 0.5374966859817505}
{'title': 'Forest Warrior', 'fullplot': 'John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.', 'score': 0.5331881642341614}
{'title': 'Forest Warrior', 'fullplot': 'John McKenna is a spiritual being who is able to transform into bear, wolf or eagle. He lives in the forests of Tanglewood and has dedicated his life to protect them. One day a gang of evil lumberjacks led by Travis Thorne arrive Tanglewood to chop the forest down. McKenna cannot let this happen, and together with his new friends - Lords of the Tanglewood, a band of children who love to play in the forest - he battles against Thorne and his evil gang.', 'score': 0.5331881642341614}
{'title': 'Catatan (Harian) si Boy', 'fullplot': "A circle of friends risking their Friendship, Trust, Love and Hope in search of a legend. A young and privileged teenager with a golden heart, beset with challenges and tribulations we face today with the goal to open many young people's mind with inspirations and hopes that drive them in achieving their dreams. To get out of their comfort zone and finish what they started.", 'score': 0.5322973728179932}
{'title': 'Bionicle: Mask of Light', 'fullplot': "In a land of living machines, two young ones are chosen to seek the legendary Mask of Light to reveal the savior of all the lands from the dark forces of the Makuta. During the course of their adventure, they will call on the heroes of their people, the great Toa. These Toa, masters of nature's forces such as Fire, Wind, Earth & Water, try to protect the chosen ones as they seek their destiny.", 'score': 0.5315042734146118}
{'title': 'Fear No Evil', 'fullplot': 'High school student turns out to be personification of Lucifer. Two arch angels in human form (as women) take him on.', 'score': 0.5295513868331909}
{'title': 'Tales of Vesperia: The First Strike', 'fullplot': 'In a mythical kingdom, the mighty Imperial Knights harness a magical substance known as Aer to power their weapons and protect humanity from the monsters of the forest. But something strange is afoot. The Aer is somehow changing, causing the wilderness to waste away and stirring the woodland beasts to attack with greater frequency. As danger creeps steadily closer to civilization, two young recruits - Flynn, the rigid son of a fallen hero, and the rebellious and brash Yuri - must ride with their fellow Imperial Knights to distant ruins in hopes of uncovering the truth behind the transforming Aer. Some will not survive the thrilling journey. Some will be betrayed. If Flynn and Yuri cannot overcome their differences and learn to fight together, all will be lost for the people of the realm.', 'score': 0.5276793241500854}