AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

テキストクエリの実行

このガイドでは、 Lambda MongoDBを使用してテキストクエリを実行する方法を学習します。

テキストクエリを使用して、指定されたフィールドにタームまたはフレーズを含むドキュメントを取得できます。タームは、空白文字を除外する文字のシーケンスです。フレーズは、任意の数の空白文字を含むタームのシーケンスです。

このガイドでは、テキストを検索するために使用できる Eloquent モデル メソッドについて説明し、例を示します。Laravel 統合での Eloquent モデルについて詳しく学ぶには、Eloquent モデルクラス セクションを参照してください。

このガイドのコード例を実行するには、「クイック スタート 」チュートリアルを完了してください。 このチュートリアルでは、サンプル データを使用して MongoDB Atlas インスタンスを設定し、Lambda ウェブ アプリケーションで次のファイルを作成する手順を説明します。

  • Movie.php ファイル( moviesコレクション内のドキュメントを表すMovieモデルを含む)

  • MovieController.php ファイル(データベース操作を実行するためのshow()関数を含む)

  • browse_movies.blade.php データベース操作の結果を表示するための HTML コードを含む ファイル

次のセクションでは、Laravel アプリケーション内のファイルを編集して検索操作コード例を実行し、期待される出力を表示する方法について説明します。

Before you can perform a text query, you must create a text index on the text-valued field. To learn more about creating indexes, see the Manage Indexes section of the Schema Builder guide.

You can perform a text query by using the $text operator followed by the $search field in your query filter that you pass to the where() method. The $text operator performs a text query on the text-indexed fields. The $search field specifies the text to search for.

where()メソッドを使用してクエリを作成したら、 get()メソッドを連鎖させてクエリ結果を検索します。

この例では、Movie Elonger モデルの where() メソッドを呼び出して、plotフィールドに "love story" というフレーズが含まれるドキュメントを検索します。このテキスト クエリを実行するには、コレクションに plotフィールドのテキストインデックスが 必要 です。

クエリを指定するには、次の構文を使用します。

$movies = Movie::where('$text', ['$search' => '"love story"'])
->get();

A text query assigns a numerical text score to indicate how closely each result matches the string in your query filter. You can sort the results by relevance by using the orderBy() method to sort on the textScore metadata field. You can access this metadata by using the $meta operator:

$movies = Movie::where('$text', ['$search' => '"love story"'])
->orderBy('score', ['$meta' => 'textScore'])
->get();

Tip

orderBy()メソッドの詳細については、「 クエリ出力の変更 」ガイドの「 クエリ結果のソート 」セクションを参照してください。

Lambda 統合を使用して検索操作を実行する方法を示す実行可能なコード例については、次の使用例を参照してください。

フィルター条件に基づいてデータを取得する方法については、 「データの取得」ガイドを参照してください 。