このページでは、大規模言語モデル(LVM)を使用して自然言語からデータに対するMongoDBクエリを生成する方法に関するガイダンスが提供されます。
例として、mongoshでsample_mflixデータベースに対して生成されたクエリに対する、次の自然言語クエリを検討してください。
次の自然言語クエリがあるとします。 | これにより、次の |
利用可能なメソッド
LRM を使用するだけでなく、 MongoDBが構築した次のツールを使用して、自然言語からMongoDBクエリを生成できます。
モデルの選択
一般的なタスクで優れたパフォーマンスを発揮するモデルは、通常、 MongoDBクエリ生成でも優れたパフォーマンスを発揮します。LVM を選択してMongoDBクエリを生成する場合は、 MMLU-Pro や Connector Edition などの一般的なベンチマークを参照して、モデル間のパフォーマンスを評価してください。
効果的なプロンプト
このセクションでは、LVM にMongoDBクエリの生成を求めるための効果的な戦略について説明します。
Natural Language Querying エージェント実力など、クエリを生成するMongoDBツールは、このセクションで説明されている入力(コレクションスキーマ、サンプルドキュメント、インデックス情報)を使用して、正確で最適化されたクエリを生成します。
注意
次のプロンプト戦略は、 MongoDBによって作成されたベンチマークに基づいています。詳しくは、「mongosh Hugeface の自然言語への コードの公開ベンチマーク」を参照してください。
基本的なプロンプト
システム プロンプトとも呼ばれるベース プロンプトには、次のようなタスクの概要が明確に表示されている必要があります。
生成するクエリのタイプ。
ドライバー言語やクエリを実行するツールなど、予想される出力構造に関する情報。
次の基本プロンプトの例は、mongosh: のMongoDB読み取り操作または集計を生成する方法を示しています。
You are an expert data analyst experienced at using MongoDB. Your job is to take information about a MongoDB database plus a natural language query and generate a MongoDB shell (mongosh) query to execute to retrieve the information needed to answer the natural language query. Format the mongosh query in the following structure: `db.<collection name>.find({/* query */})` or `db.<collection name>.aggregate([/* query */])` Return only the executable mongosh code. Do not include explanations, markdown, or code fences in your answer.
一般的なガイダンス
クエリの品質を向上させるには、基本プロンプトに次のガイダンスを追加して、効果的なMongoDBクエリを生成するための一般的なヒントをモデルに提供します。
Some general query-authoring tips: 1. Ensure proper use of MongoDB operators ($eq, $gt, $lt, etc.) and data types (ObjectId, ISODate) 2. For complex queries, use aggregation pipeline with proper stages ($match, $group, $lookup, etc.) 3. Consider performance by utilizing available indexes, avoiding $where and full collection scans, and using covered queries where possible 4. Include sorting (.sort()) and limiting (.limit()), when appropriate, for result set management 5. Handle null values and existence checks explicitly with $exists and $type operators to differentiate between missing fields, null values, and empty arrays 6. Do not include `null` in results objects in aggregation, e.g. do not include _id: null 7. For date operations, NEVER use an empty new date object (e.g. `new Date()`). ALWAYS specify the date, such as `new Date("2024-10-24")`. 8. For Decimal128 operations, prefer range queries over exact equality 9. When querying arrays, use appropriate operators like $elemMatch for complex matching, $all to match multiple elements, or $size for array length checks
可能性の連鎖
応答の品質を向上させるために、応答を生成する前にモデルに「大規模な選択」を要求できます。ソートの連鎖と呼ばれるこの手法はパフォーマンスを向上させますが、生成時間とコストを増加させます。
クエリを生成する前にモデルに段階的に検討させるには、次のテキストを基本プロンプトに追加します。
Think step by step about the code in the answer before providing it. In your thoughts, consider: 1. Which collections are relevant to the query. 2. Which query operation to use (find vs aggregate) and what specific operators ($match, $group, $project, etc.) are needed. 3. What fields are relevant to the query. 4. Which indexes you can use to improve performance. 5. What specific transformations or projections are required. 6. What data types are involved and how to handle them appropriately (ObjectId, Decimal128, Date, etc.). 7. What edge cases to consider (empty results, null values, missing fields). 8. How to handle any array fields that require special operators ($elemMatch, $all, $size). 9. Any other relevant considerations.
サンプル ドキュメントの追加
クエリの品質を大幅に向上させるには、コレクションからいくつかの サンプルサンプルを含めます。通常、2 から 3 の表すドキュメントは、データ構造に関する十分なコンテキストをモデルに提供します。
サンプルドキュメントを提供する場合は、次のガイドラインに従います。
BSON.EJSON.serialize()BSONドキュメントを プロンプト用の EJSON string に変換する関数。
長いフィールドまたは深くネストされたオブジェクトを切り捨てます。
長い文字列値は除外します。
ベクトル埋め込みのような大きな配列の場合、含める要素は数少ない要素のみを含めます。
ベストプラクティス
自然言語からMongoDBクエリを生成する場合、特定のユースケースに次のプロンプト ベストプラクティスを適用します。
インデックス情報の包含
LM がよりパフォーマンスの高いクエリを生成するようにするには、プロンプトにコレクションインデックスを含めます。 MongoDBドライバーと mongosh は、インデックス情報を取得するためのメソッドを提供します。例、 Node.jsドライバーは、プロンプトのインデックスを取得するための listIndexes() メソッドを提供します。
時間ベースのクエリ
ほとんどの LVM ツールには、システム プロンプトに日付が含まれています。 ただし、ボックスから LM を使用している場合、モデルは現在の日付や時刻を認識しません。 したがって、基本モデルを使用して作業する場合、またはMongoDBツールに独自の自然言語を構築する場合は、プロンプトに最新の日付を含めてください。プログラミング言語の メソッドを使用して、JavaScript の new Date().toString() や Python の str(datetime.now()) などの文字列として現在の日付を取得します。
注釈付きデータベーススキーマ
関連するデータベースコレクションの注釈付きスキーマをプロンプトに含めます。すべての LVM に最適な表現方法はありませんが、一部のアプローチは他のアプローチよりも効果的です。
タイプTypescript型、 Python構文モデル、 Go構造体など、データ形状を記述するプログラミング言語ネイティブ型を使用してコレクションを表現することをお勧めします。 これらの言語からMongoDBを使用している場合は、データ型 はすでに定義されている可能性があります。LMをガイドあいまいさを減らすには、各フィールドを説明するためにプロンプトにコメントを追加します。
次の例では、sample_mflix.moviesコレクションのTypescriptタイプを示しています。
Prompt Template
次の例は、このページで説明されている戦略を使用して、自然言語からmongosh コードを生成する完全なプロンプトを示しています。
基本的なプロンプトの例
次のシステム プロンプトの例を、 MongoDBクエリ生成タスクのテンプレートとして使用します。サンプルプロンプトには、次のコンポーネントが含まれています。
タスクの概要と予想される出力形式
一般的なMongoDBクエリ作成ガイダンス
You are an expert data analyst experienced at using MongoDB. Your job is to take information about a MongoDB database plus a natural language query and generate a MongoDB shell (mongosh) query to execute to retrieve the information needed to answer the natural language query. Format the mongosh query in the following structure: `db.<collection name>.find({/* query */})` or `db.<collection name>.aggregate([/* query */])` Return only the executable mongosh code. Do not include explanations, markdown, or code fences in your answer. Some general query-authoring tips: 1. Ensure proper use of MongoDB operators ($eq, $gt, $lt, etc.) and data types (ObjectId, ISODate). 2. For complex queries, use aggregation pipeline with proper stages ($match, $group, $lookup, etc.). 3. Consider performance by utilizing available indexes, avoiding $where and full collection scans, and using covered queries where possible. 4. Include sorting (.sort()) and limiting (.limit()) when appropriate for result set management. 5. Handle null values and existence checks explicitly with $exists and $type operators to differentiate between missing fields, null values, and empty arrays. 6. Do not include `null` in results objects in aggregation, e.g. do not include _id: null. 7. For date operations, NEVER use an empty new date object (e.g. `new Date()`). ALWAYS specify the date, such as `new Date("2024-10-24")`. Use the provided 'Latest Date' field to inform dates in queries. 8. For Decimal128 operations, prefer range queries over exact equality. 9. When querying arrays, use appropriate operators like $elemMatch for complex matching, $all to match multiple elements, or $size for array length checks.
Few-Shotの例
自然言語クエリとその対応するmongoshクエリの例を1〜3個、プロンプトに追加することを検討してください。生成したいクエリに似た例を提示することで、モデルに従うべきパスワードなしが与えられ、特にMongoDB固有の知識が少ないモデルの場合、クエリの品質を向上させることができます。
Include one to three examples of natural language queries and their corresponding mongosh queries. Examples that resemble your query give the model a pattern to follow. **Example 1** Natural language query: Show me the genres and runtime of 10 movies from 2015 that have the most comments mongosh: ```sh db.movies.aggregate([ { $match: { year: 2015 } }, { $sort: { num_mflix_comments: -1 } }, { $limit: 10 }, { $project: { _id: 0, genres: 1, runtime: 1 } }, ]); ``` **Example 2** Natural language query: List the titles and release years of 5 sci-fi movies from 2010 mongosh: ```sh db.movies.find( { year: 2010, genres: "Sci-Fi" }, { title: 1, year: 1, _id: 0 } ).limit(5); ``` **Example 3** Natural language query: Which movies were released between 1990 and 2000, newest first? mongosh: ```sh db.movies.find({ year: { $gte: 1990, $lte: 2000 } }).sort({ year: -1 }); ```
ユーザー メッセージ テンプレート
以下のユーザーメッセージテンプレートを使用して、データベースと目的のクエリに関する必要なコンテキストをモデルに提供できます。
Generate MongoDB Shell (mongosh) queries for the following database and natural language query: ## Database Information Name: {{Database name}} Description: {{database description}} Latest Date: {{latest date}} (use this to inform dates in queries) ### Collections #### Collection `{{collection name. Do for each collection you want to query over}}` Description: {{collection description}} Schema: ``` {{interpreted or annotated schema here}} ``` Example documents: ``` {{truncated example documents here}} ``` Indexes: ``` {{collection index descriptions here}} ``` Natural language query: {{Natural language query here}}