加重フィールドを使用した Atlas Search 複合クエリの実行方法
このチュートリアルでは、検索フィールドに重みを追加して、結果または結果のカテゴリ内のドキュメントをブーストまたは埋め込みする方法を説明します。 フィールドに 1 つ以上の値を割り当てて、スコアの高い結果または低い結果を返す方法を示します。
具体的には、チュートリアルでは、 sample_mflix.movies
コレクションに 動的マッピングを使用してインデックスを作成する 方法を示します。 複合クエリを実行し、 constant
、 function
、 boost
を使用してスコアを変更する方法を示します。 次の手順が必要です。
sample_mflix.movies
コレクションの 動的マッピング を使用して Atlas Search インデックスを設定します。次の Atlas Search クエリを実行します。
year
フィールドをクエリし、title
フィールドの特定の単語を使用してスコアを変更して、結果内のドキュメントをブーストします。title
フィールドとplot
フィールドをクエリし、genres
フィールドの特定のジャンルに基づいてスコアを変更して、そのジャンルの結果を埋め込みます。
開始する前に、Atlas クラスターが前提条件 に記載されている要件を満たしていることを確認してください。
Atlas Search インデックスを作成するには、プロジェクトに対するProject Data Access Admin
以上のアクセス権が必要です。
動的マッピングを使用した Atlas Search インデックスの作成
このセクションでは、動的マッピングを使用してsample_mflix.movies
コレクション内のフィールドにインデックスを付けるための Atlas Search インデックスを作成します。
Atlas Atlasで、プロジェクトの {0 ページにGoします。GoClusters
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ クラスター]ページが表示されます。
Index Name を入力し、Database and Collection を設定します。
Index Nameフィールドに
compound-query-custom-score-tutorial
と入力します。インデックスに
default
と名付けると、 $searchパイプライン ステージでindex
パラメータを指定する必要がなくなります。 インデックスにカスタム名を付ける場合は、index
パラメータでこの名前を指定する必要があります。Database and Collectionセクションで、
sample_mflix
データベースを検索し、movies
コレクションを選択します。
インデックスの定義を指定します。
動的マッピングまたは静的マッピングを使用する Atlas Search インデックスを作成できます。 動的マッピングと静的マッピングについて詳しくは、「静的マッピングと動的マッピング 」を参照してください。
次のインデックス定義は、 movies
コレクション内のサポートされている型のフィールドを動的にインデックス化します。 Atlas Search Visual Editor またはAtlas Search JSON Editor を使用して、 Atlas userインターフェースでインデックスを作成できます。
ビジュアル エディター
[Next] をクリックします。
movies
コレクションの"default"
インデックス定義を確認します。
JSON エディター
[Next] をクリックします。
インデックスの定義を確認します。
インデックス定義は、次のようになります。
{ "mappings": { "dynamic": true } } 上記のインデックス定義は、
movies
コレクション内の各ドキュメントでサポートされているタイプのフィールドを動的にインデックス化します。[Next] をクリックします。
複合クエリの実行
複合演算子 を使用して、2 つ以上の演算子を 1 つのクエリに結合します。 Atlas Search は、クエリで返される各ドキュメントに対して、関連性に基づいて最高スコアから最低スコアの順にスコアを割り当てます。 クエリは、結果内のドキュメントをブーストまたは埋め込む方法を示します。
➤ [言語の選択]ドロップダウン メニューを使用して、このセクション内の例の言語を設定します。
Tip
Atlas Search には、ガイダンス付きのサンプル複合クエリ テンプレートが用意されています。詳細については、「クエリ ガイダンス テンプレートの表示」を参照してください。
複合クエリを実行して結果をブースト
このセクションでは、Atlas クラスターに接続し、 title
year
sample_mflix.movies
コレクションの フィールドと フィールドに対して 複合 演算子を使用してサンプル クエリを実行します。サンプル クエリはカスタム スコアリングを使用して、 snow
というタームを含む映画タイトルの Atlas Search によって返される関連性スコアを変更します。
AtlasGoClustersAtlas で、プロジェクトの ページにGoします。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーのOrganizationsメニュー
まだ表示されていない場合は、ナビゲーション バーのProjectsメニューから目的のプロジェクトを選択します。
まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。
[ Clusters (クラスター) ] ページが表示されます。
movies
コレクションに対して compound
演算子を使用して、次の Atlas Search クエリを実行します。
次のクエリをコピーして、 Query Editorに貼り付け、 Query EditorのSearchボタンをクリックします。
次の例では、サブクエリとともにcompound
演算子を使用して、 title
フィールドにsnow
というタームを含む、 2013
から2015
年の間の映画を検索します。
以下のクエリでは、
次の
compound
演算子句を使用します。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
[ { $search: { index: "compound-query-custom-score-tutorial", compound: { filter: [{ range: { path: "year", gte: 2013, lte: 2015 } }], should: [{ text: { query: "snow", path: "title", score: {constant: {value: 5}} } }] }, highlight:{ path: "title" } } } ]
SCORE: 5 _id: "573a13d7f29313caabda38ad" Snow in Paradise Matching fields: title SCORE: 5 _id: "573a13e2f29313caabdbeded" Dead Snow 2: red vs. Matching fields: title SCORE: 5 _id: "573a13e6f29313caabdc66c4" The Snow White Murder Case Matching fields: title SCORE: 5 _id: "573a13edf29313caabdd37bd" Snow on the Blades Matching fields: title SCORE: 0 _id: "573a13acf29313caabd29366" No highlights found. Matching fields: unknown SCORE: 0 _id: "573a13adf29313caabd2b765" No highlights found. Matching fields: unknown SCORE: 0 _id: "573a13b0f29313caabd333e7" No highlights found. Matching fields: unknown SCORE: 0 _id: "573a13b0f29313caabd3486a" No highlights found. Matching fields: unknown SCORE: 0 _id: "573a13b1f29313caabd3719d" No highlights found. Matching fields: unknown SCORE: 0 _id: "573a13b2f29313caabd3abb9" No highlights found. Matching fields: unknown
結果の最初の 4 つのドキュメントは、クエリのshould
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should
句は、 constant
オプションを使用して、クエリ タームsnow
のスコアも変更します。
以下のクエリでは、
次の
compound
演算子句を使用します。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
[ { $search: { index: "compound-query-custom-score-tutorial", compound: { must: [{ range: { path: "year", gte: 2013, lte: 2015 } }], should: [{ text: { query: "snow", path: "title", score: {boost: {value: 2}} } }] }, highlight:{ path: "title" } } } ]
SCORE: 6.7722930908203125 _id: "573a13d7f29313caabda38ad" Snow in Paradise Matching fields: title SCORE: 6.063445568084717 _id: "573a13edf29313caabdd37bd" Snow on the Blades Matching fields: title SCORE: 5.509652137756348 _id: "573a13e6f29313caabdc66c4" The Snow White Murder Case Matching fields: title SCORE: 5.065053939819336 _id: "573a13e2f29313caabdbeded" Dead Snow 2: Red vs. Matching fields: title SCORE: 1 _id: "573a13acf29313caabd29366" No highlights found. Matching fields: unknown SCORE: 1 _id: "573a13adf29313caabd2b765" No highlights found. Matching fields: unknown SCORE: 1 _id: "573a13b0f29313caabd333e7" No highlights found. Matching fields: unknown SCORE: 1 _id: "573a13b0f29313caabd3486a" No highlights found. Matching fields: unknown SCORE: 1 _id: "573a13b1f29313caabd3719d" No highlights found. Matching fields: unknown SCORE: 1 _id: "573a13b2f29313caabd3abb9" No highlights found. Matching fields: unknown
結果の最初の 4 つのドキュメントは、クエリのshould
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should
句は、 boost
オプションを使用して、クエリ タームsnow
のスコアも変更します。
以下のクエリでは、
次の
compound
演算子句をboost
オプションとともに使用して、一部のフィールドを他のフィールドよりも優先するようにします。must
句をテキスト演算子とともに使用すると、ジャンルcomedy
が最も優先度が高く、その後にtitle
フィールドの用語snow
が優先されます。boost
オプションはフィールドに重みを適用します。should
句を範囲演算子とともに使用すると、2013
から2015
年の間の映画が検索されます。
注意
boost
オプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。
[ { $search: { index: "compound-query-custom-score-tutorial", compound: { must: [{ text: { query: "comedy", path: "genres", score: {boost: {value: 9}} } }, { text: { query: "snow", path: "title", score: {boost: {value: 5}} } }], should: [{ range: { path: "year", gte: 2013, lte: 2015, score: {boost: {value: 3}} } }] } } } ]
SCORE: 21.872983932495117 _id: "573a13c2f29313caabd6874c" plot: "A ski vacation turns horrific for a group of medical students, as they…" genres: Array runtime: 91 SCORE: 21.043487548828125 _id: "573a139ff29313caabcffff8" fullplot: "When an entire town in upstate New York is closed down by an unexpecte…" imdb: Object year: 2000 SCORE: 21.043487548828125 _id: "573a13a6f29313caabd16b02" plot: "When a Miami dentist inherits a team of sled dogs, he's got to learn t…" genres: Array runtime: 99 SCORE: 19.523927688598633 _id: "573a13a1f29313caabd06765" fullplot: "Our two young lovers meet on a series of snowy days in high school. Ye…" imdb: Object runtime: 1999 SCORE: 17.426334381103516 _id: "573a13e2f29313caabdbeded" plot: "Still on the run from a group of Nazi zombies, a man seeks the aid of …" genres: Array runtime: 100 SCORE: 16.367326736450195 _id: "573a13c2f29313caabd6688e" countries: Array genres: Array runtime: 108 SCORE: 15.537829399108887 _id: "573a13b1f29313caabd36d7d" plot: "A love-struck Italian poet is stuck in Iraq at the onset of an America…" genres: Array runtime: 110 SCORE: 14.4263334274292 _id: "573a1395f29313caabce1925" plot: "An ice-skating Snow White finds refuge from the Wicked Queen with the …" genres: Array runtime: 107
以下のクエリでは、
次の
compound
演算子句を使用します。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
[ { $search: { index: "compound-query-custom-score-tutorial", compound: { must: [{ range: { path: "year", gte: 2013, lte: 2015, } }], should: [{ text: { query: "snow", path: "title", score: { function: { add: [{ path: { value: "imdb.rating", undefined: 2 } }, { score: "relevance" }] } } } }] }, highlight: { path: "title" } } } ]
SCORE: 10.454826354980469 _id: "573a13e6f29313caabdc66c4" The Snow White Murder Case Matching fields: title SCORE: 10.3317232131958 _id: "573a13edf29313caabdd37bd" Snow on the Blades Matching fields: title SCORE: 10.032526969909668 _id: "573a13e2f29313caabdbeded" Dead Snow 2: Red vs. Matching fields: title SCORE: 8.386146545410156 _id: "573a13d7f29313caabda38ad" Snow in Paradise Matching fields: title SCORE: 1 _id: "573a13acf29313caabd29366" No highlights found. Matching fields: unknown SCORE: 1 _id: "573a13adf29313caabd2b765" No highlights found. Matching fields: unknown SCORE: 1 _id: "573a13b0f29313caabd333e7" No highlights found. Matching fields: unknown SCORE: 1 _id: "573a13b0f29313caabd3486a" No highlights found. Matching fields: unknown SCORE: 1 _id: "573a13b1f29313caabd3719d" No highlights found. Matching fields: unknown SCORE: 1 _id: "573a13b2f29313caabd3abb9" No highlights found. Matching fields: unknown
結果の最初の 4 つのドキュメントは、クエリのshould
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should
句は、 function
オプションを使用して、クエリ タームsnow
のスコアも変更します。
クエリ結果を展開します。
Search Testerでは、返されるドキュメント内のすべてのフィールドが表示されない場合があります。 クエリパスで指定したフィールドを含むすべてのフィールドを表示するには、結果内のドキュメントを展開します。
mongosh
内のクラスターに接続します。
ターミナル ウィンドウでmongosh
を開き、クラスターに接続します。 接続の詳細な手順については、「 mongosh
経由での接続 」を参照してください。
sample_mflix
データベースを使用します。
mongosh
プロンプトで次のコマンドを実行します。
use sample_mflix
movies
コレクションに対して compound
演算子を使用して、次の Atlas Search クエリを実行します。
次の例では、サブクエリとともにcompound
演算子を使用して、 title
フィールドにsnow
というタームを含む、 2013
から2015
年の間の映画を検索します。
このクエリでは、次のパイプライン ステージを使用します。
$search
コレクションをクエリします。 クエリでは以下の操作が実行されます。次の
compound
演算子句を使用します。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
$limit
ステージを使用して、出力を10
の結果に制限します。$project
stageを次のように設定します。title
とyear
を除くすべてのフィールドを除外score
フィールドを追加する
db.movies.aggregate([ { "$search": { "index": "compound-query-custom-score-tutorial", "compound": { "filter": [{ "range": { "path": "year", "gte": 2013, "lte": 2015 } }], "should": [{ "text": { "query": "snow", "path": "title", "score": {"constant": {"value": 5}} } }] }, "highlight": { "path": "title" } } }, { "$limit": 10 }, { "$project": { "_id": 0, "title": 1, "year": 1, "score": { "$meta": "searchScore" }, "highlights": { "$meta": "searchHighlights" } } } ])
Atlas Search により、 constant
について次の結果が返されます。
[ { title: 'Snow in Paradise', year: 2014, score: 5, highlights: [ { score: 1.382846713066101, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' in Paradise', type: 'text' } ] } ] }, { title: 'Dead Snow 2: Red vs. Dead', year: 2014, score: 5, highlights: [ { score: 1.3924485445022583, path: 'title', texts: [ { value: 'Dead ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' 2: Red vs. ', type: 'text' } ] } ] }, { title: 'The Snow White Murder Case', year: 2014, score: 5, highlights: [ { score: 1.3525336980819702, path: 'title', texts: [ { value: 'The ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' White Murder Case', type: 'text' } ] } ] }, { title: 'Snow on the Blades', year: 2014, score: 5, highlights: [ { score: 1.3766303062438965, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' on the Blades', type: 'text' } ] } ] }, { year: 2013, title: 'The Secret Life of Walter Mitty', score: 0, highlights: [] }, { title: 'Jurassic World', year: 2015, score: 0, highlights: [] }, { title: 'Action Jackson', year: 2014, score: 0, highlights: [] }, { year: 2013, title: 'In Secret', score: 0, highlights: [] }, { title: 'The Stanford Prison Experiment', year: 2015, score: 0, highlights: [] }, { year: 2014, title: 'The Giver', score: 0, highlights: [] } ]
結果の最初の 4 つのドキュメントは、クエリのshould
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should
句は、 constant
オプションを使用して、クエリ タームsnow
のスコアも変更します。
このクエリでは、次のパイプライン ステージを使用します。
$search
コレクションをクエリします。 クエリでは以下の操作が実行されます。次の
compound
演算子句を使用します。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
$limit
ステージを使用して、出力を10
の結果に制限します。$project
stageを次のように設定します。title
とyear
を除くすべてのフィールドを除外score
フィールドを追加する
db.movies.aggregate([ { "$search": { "index": "compound-query-custom-score-tutorial", "compound": { "must": [{ "range": { "path": "year", "gte": 2013, "lte": 2015 } }], "should": [{ "text": { "query": "snow", "path": "title", "score": {"boost": {"value": 2}} } }] }, "highlight": { "path": "title" } } }, { "$limit": 10 }, { "$project": { "_id": 0, "title": 1, "year": 1, "score": { "$meta": "searchScore" }, "highlights": { "$meta": "searchHighlights" } } } ])
Atlas Search により、 boost
について次の結果が返されます。
[ { title: 'Snow in Paradise', year: 2014, score: 6.7722930908203125, highlights: [ { score: 1.382846713066101, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' in Paradise', type: 'text' } ] } ] }, { title: 'Snow on the Blades', year: 2014, score: 6.063445568084717, highlights: [ { score: 1.3766303062438965, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' on the Blades', type: 'text' } ] } ] }, { title: 'The Snow White Murder Case', year: 2014, score: 5.509652137756348, highlights: [ { score: 1.3525336980819702, path: 'title', texts: [ { value: 'The ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' White Murder Case', type: 'text' } ] } ] }, { title: 'Dead Snow 2: Red vs. Dead', year: 2014, score: 5.065053939819336, highlights: [ { score: 1.3924485445022583, path: 'title', texts: [ { value: 'Dead ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' 2: Red vs. ', type: 'text' } ] } ] }, { year: 2013, title: 'The Secret Life of Walter Mitty', score: 1, highlights: [] }, { title: 'Jurassic World', year: 2015, score: 1, highlights: [] }, { title: 'Action Jackson', year: 2014, score: 1, highlights: [] }, { year: 2013, title: 'In Secret', score: 1, highlights: [] }, { title: 'The Stanford Prison Experiment', year: 2015, score: 1, highlights: [] }, { year: 2014, title: 'The Giver', score: 1, highlights: [] } ]
結果の最初の 4 つのドキュメントは、クエリのshould
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should
句は、 boost
オプションを使用して、クエリ タームsnow
のスコアも変更します。
このクエリでは、次のパイプライン ステージを使用します。
$search
を使用してコレクションをクエリします。 クエリでは、次のcompound
演算子句をboost
オプションとともに使用して、一部のフィールドを他のフィールドよりも優先してください。must
句をテキスト演算子とともに使用すると、ジャンルcomedy
が最も優先度が高く、その後にtitle
フィールドの用語snow
が優先されます。boost
オプションはフィールドに重みを適用します。should
句を範囲演算子とともに使用すると、2013
から2015
年の間の映画が検索されます。
注意
boost
オプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。$limit
ステージを使用して、出力を10
の結果に制限します。$project
stageを次のように設定します。すべてのフィールドを除外
title
、year
、genres
score
フィールドを追加する
db.movies.aggregate([ { "$search": { "index": "compound-query-custom-score-tutorial", "compound": { "must": [{ "text": { "path": "genres", "query": "comedy", "score": {"boost": {"value": 9}} } }, { "text": { "path": "title", "query": "snow", "score": {"boost": {"value": 5}} } }], "should": [{ "range": { "path": "year", "gte": 2013, "lte": 2015, "score": {"boost": {"value": 3}} } }] } } }, { "$limit": 10 }, { "$project": { "_id": 0, "title": 1, "year": 1, "genres": 1, "score": { "$meta": "searchScore" } } } ])
[ { genres: [ 'Comedy', 'Horror' ], title: 'Dead Snow', year: 2009, score: 21.872983932495117 }, { year: 2000, genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow Day', score: 21.043487548828125 }, { genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow Dogs', year: 2002, score: 21.043487548828125 }, { year: 1999, genres: [ 'Comedy', 'Romance' ], title: 'Let It Snow', score: 19.523927688598633 }, { genres: [ 'Action', 'Comedy', 'Horror' ], title: 'Dead Snow 2: Red vs. Dead', year: 2014, score: 17.426334381103516 }, { genres: [ 'Comedy', 'Drama' ], title: 'Snow White and Russian Red', year: 2009, score: 16.367326736450195 }, { genres: [ 'Comedy', 'Drama', 'Romance' ], title: 'The Tiger and the Snow', year: 2005, score: 15.537829399108887 }, { genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow White and the Three Stooges', year: 1961, score: 14.4263334274292 } ]
このクエリでは、次のパイプライン ステージを使用します。
$search
コレクションをクエリします。 クエリでは以下の操作が実行されます。次の
compound
演算子句を使用します。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
$limit
ステージを使用して、出力を10
の結果に制限します。$project
stageを次のように設定します。title
とyear
を除くすべてのフィールドを除外score
フィールドを追加する
db.movies.aggregate([ { "$search": { "index": "compound-query-custom-score-tutorial", "compound": { "must": [{ "range": { "path": "year", "gte": 2013, "lte": 2015 } }], "should": [{ "text": { "query": "snow", "path": "title", "score": { "function": { "add": [{ "path": { "value": "imdb.rating", "undefined": 2 } }, { "score": "relevance" }] } } } }] }, "highlight": { "path": "title" } } }, { "$limit": 10 }, { "$project": { "_id": 0, "title": 1, "year": 1, "score": { "$meta": "searchScore" }, "highlights": { "$meta": "searchHighlights" } } } ])
Atlas Search により、 function
について次の結果が返されます。
[ { title: 'The Snow White Murder Case', year: 2014, score: 10.454826354980469, highlights: [ { score: 1.3525336980819702, path: 'title', texts: [ { value: 'The ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' White Murder Case', type: 'text' } ] } ] }, { title: 'Snow on the Blades', year: 2014, score: 10.3317232131958, highlights: [ { score: 1.3766303062438965, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' on the Blades', type: 'text' } ] } ] }, { title: 'Dead Snow 2: Red vs. Dead', year: 2014, score: 10.032526969909668, highlights: [ { score: 1.3924485445022583, path: 'title', texts: [ { value: 'Dead ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' 2: Red vs. ', type: 'text' } ] } ] }, { title: 'Snow in Paradise', year: 2014, score: 8.386146545410156, highlights: [ { score: 1.382846713066101, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' in Paradise', type: 'text' } ] } ] }, { year: 2013, title: 'The Secret Life of Walter Mitty', score: 1, highlights: [] }, { title: 'Jurassic World', year: 2015, score: 1, highlights: [] }, { title: 'Action Jackson', year: 2014, score: 1, highlights: [] }, { year: 2013, title: 'In Secret', score: 1, highlights: [] }, { title: 'The Stanford Prison Experiment', year: 2015, score: 1, highlights: [] }, { year: 2014, title: 'The Giver', score: 1, highlights: [] } ]
結果の最初の 4 つのドキュメントは、クエリのshould
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should
句は、 function
オプションを使用して、クエリ タームsnow
のスコアも変更します。
MongoDB Compass のクラスターに接続します。
MongoDB Compass を開き、クラスターに接続します。 接続の詳細な手順については、「 Compass 経由での接続 」を参照してください。
constant
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
クエリは、次のタスクを実行します。
次の
compound
演算子句を使用します。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。次のパイプライン ステージを使用します。
MongoDB Compass でこのクエリを実行するには:
[Aggregations] タブをクリックします。
Select...をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプライン ステージを構成します。 ステージを追加するには、 Add Stageをクリックします。
パイプラインステージクエリ$search
{ "index": "compound-query-custom-score-tutorial", "compound": { "filter": [{ "range": { "path": "year", "gte": 2013, "lte": 2015 } }], "should": [{ "text": { "query": "snow", "path": "title", "score": {"constant": {"value": 5}} } }] }, "highlight": { "path": "title" } } $limit
10 $project
{ "_id": 0, "title": 1, "year": 1, "score": { "$meta": "searchScore" }, "highlights": { "$meta": "searchHighlights" } } Auto Previewを有効にした場合、MongoDB Compass は
$project
パイプライン ステージの横に次のドキュメントを表示します。{ title: 'Snow in Paradise', year: 2014, score: 5, highlights: [{ score: 1.382846713066101, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' in Paradise', type: 'text' } ] }] }, { title: 'Dead Snow 2: Red vs. Dead', year: 2014, score: 5, highlights: [{ score: 1.3924485445022583, path: 'title', texts: [ { value: 'Dead ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' 2: Red vs. ', type: 'text' } ] }] }, { title: 'The Snow White Murder Case', year: 2014, score: 5, highlights: [{ score: 1.3525336980819702, path: 'title', texts: [ { value: 'The ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' White Murder Case', type: 'text' } ] }] }, { title: 'Snow on the Blades', year: 2014, score: 5, highlights: [{ score: 1.3766303062438965, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' on the Blades', type: 'text' } ] }] }, { year: 2013, title: 'The Secret Life of Walter Mitty', score: 0, highlights: [] }, { title: 'Jurassic World', year: 2015, score: 0, highlights: [] }, { title: 'Action Jackson', year: 2014, score: 0, highlights: [] }, { year: 2013, title: 'In Secret', score: 0, highlights: [] }, { title: 'The Stanford Prison Experiment', year: 2015, score: 0, highlights: [] }, { year: 2014, title: 'The Giver', score: 0, highlights: [] } 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、constant
オプションを使用して、クエリ タームsnow
のスコアも変更します。
boost
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
[Aggregations] タブをクリックします。
Select...をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプライン ステージを構成します。 ステージを追加するには、 Add Stageをクリックします。
クエリは、次のパイプライン ステージを使用します。
$search
次のタスクを実行する必要があります。次の
compound
演算子句を使用するクエリ。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
出力を10の結果に制限する$limitステージ
$projectステージから次の操作へ。
title
とyear
を除くすべてのフィールドを除外score
とhighlights
という名前の 2 つのフィールドを追加します
パイプラインステージクエリ$search
{ "index": "compound-query-custom-score-tutorial", "compound": { "must": [{ "range": { "path": "year", "gte": 2013, "lte": 2015 } }], "should": [{ "text": { "query": "snow", "path": "title", "score": {"boost": {"value": 2}} } }] }, "highlight": { "path": "title" } } $limit
10 $project
{ "_id": 0, "title": 1, "year": 1, "score": { "$meta": "searchScore" }, "highlights": { "$meta": "searchHighlights" } } このクエリでは、次のパイプライン ステージを使用します。
$search
次のタスクを実行する必要があります。
出力を10の結果に制限する$limitステージ
$projectステージから次の操作へ。
title
とyear
を除くすべてのフィールドを除外score
とhighlights
という名前の 2 つのフィールドを追加します
must
句をテキスト演算子とともに使用すると、ジャンルcomedy
が最も優先度が高く、その後にtitle
フィールドの用語snow
が優先されます。boost
オプションはフィールドに重みを適用します。should
句を範囲演算子とともに使用すると、2013
から2015
年の間の映画が検索されます。
注意
boost
オプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。パイプラインステージクエリ$search
{ "index": "compound-query-custom-score-tutorial", "compound": { "must": [{ "text": { "path": "genres", "query": "comedy", "score": {"boost": {"value": 9}} } }, { "text": { "path": "title", "query": "snow", "score": {"boost": {"value": 5}} } }], "should": [{ "range": { "path": "year", "gte": 2013, "lte": 2015, "score": {"boost": {"value": 3}} } }] } } $limit
10 $project
{ "_id": 0, "title": 1, "year": 1, "genres": 1, "score": { "$meta": "searchScore" } } Auto Previewを有効にした場合、MongoDB Compass は
$project
パイプライン ステージの横に次のドキュメントを表示します。{ title: 'Snow in Paradise', year: 2014, score: 6.7722930908203125, highlights: [{ score: 1.382846713066101, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' in Paradise', type: 'text' } ] }] }, { title: 'Snow on the Blades', year: 2014, score: 6.063445568084717, highlights: [{ score: 1.3766303062438965, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' on the Blades', type: 'text' } ] }] }, { title: 'The Snow White Murder Case', year: 2014, score: 5.509652137756348, highlights: [{ score: 1.3525336980819702, path: 'title', texts: [ { value: 'The ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' White Murder Case', type: 'text' } ] }] }, { title: 'Dead Snow 2: Red vs. Dead', year: 2014, score: 5.065053939819336, highlights: [{ score: 1.3924485445022583, path: 'title', texts: [ { value: 'Dead ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' 2: Red vs. ', type: 'text' } ] }] }, { year: 2013, title: 'The Secret Life of Walter Mitty',score: 1, highlights: [] }, { title: 'Jurassic World', year: 2015, score: 1, highlights: [] }, { title: 'Action Jackson', year: 2014, score: 1, highlights: [] }, { year: 2013, title: 'In Secret', score: 1, highlights: [] }, { title: 'The Stanford Prison Experiment', year: 2015, score: 1, highlights: [] }, { year: 2014, title: 'The Giver', score: 1, highlights: [] } 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、boost
オプションを使用して、クエリ タームsnow
のスコアも変更します。[ { genres: [ 'Comedy', 'Horror' ], title: 'Dead Snow', year: 2009, score: 21.872983932495117 }, { year: 2000, genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow Day', score: 21.043487548828125 }, { genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow Dogs', year: 2002, score: 21.043487548828125 }, { year: 1999, genres: [ 'Comedy', 'Romance' ], title: 'Let It Snow', score: 19.523927688598633 }, { genres: [ 'Action', 'Comedy', 'Horror' ], title: 'Dead Snow 2: Red vs. Dead', year: 2014, score: 17.426334381103516 }, { genres: [ 'Comedy', 'Drama' ], title: 'Snow White and Russian Red', year: 2009, score: 16.367326736450195 }, { genres: [ 'Comedy', 'Drama', 'Romance' ], title: 'The Tiger and the Snow', year: 2005, score: 15.537829399108887 }, { genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow White and the Three Stooges', year: 1961, score: 14.4263334274292 } ]
function
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
クエリは、次のパイプライン ステージを使用します。
$search
ステージでは、次のタスクを実行します。次の
compound
演算子句を使用するクエリ。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
出力を10の結果に制限する$limitステージ
$projectステージから次の操作へ。
title
とyear
を除くすべてのフィールドを除外score
とhighlights
という名前の 2 つのフィールドを追加します
MongoDB Compass でこのクエリを実行するには:
[Aggregations] タブをクリックします。
Select...をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプライン ステージを構成します。 ステージを追加するには、 Add Stageをクリックします。
パイプラインステージクエリ$search
{ "index": "compound-query-custom-score-tutorial", "compound": { "must": [{ "range": { "path": "year", "gte": 2013, "lte": 2015 } }], "should": [{ "text": { "query": "snow", "path": "title", "score": { "function": { "add": [{ "path": { "value": "imdb.rating", "undefined": 2 } }, { "score": "relevance" }] } } } }]}, "highlight":{ "path": "title" } } $limit
10 $project
{ "_id": 0, "title": 1, "year": 1, "score": { "$meta": "searchScore" }, "highlights": { "$meta": "searchHighlights" } } Auto Previewを有効にした場合、MongoDB Compass は
$project
パイプライン ステージの横に次のドキュメントを表示します。{ title: 'The Snow White Murder Case', year: 2014, score: 10.454826354980469, highlights: [{ score: 1.3525336980819702, path: 'title', texts: [ { value: 'The ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' White Murder Case', type: 'text' } ] }] }, { title: 'Snow on the Blades', year: 2014, score: 10.3317232131958, highlights: [{ score: 1.3766303062438965, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' on the Blades', type: 'text' } ] }] }, { title: 'Dead Snow 2: Red vs. Dead', year: 2014, score: 10.032526969909668, highlights: [{ score: 1.3924485445022583, path: 'title', texts: [ { value: 'Dead ', type: 'text' }, { value: 'Snow', type: 'hit' }, { value: ' 2: Red vs. ', type: 'text' } ] }] }, { title: 'Snow in Paradise', year: 2014, score: 8.386146545410156, highlights: [{ score: 1.382846713066101, path: 'title', texts: [ { value: 'Snow', type: 'hit' }, { value: ' in Paradise', type: 'text' } ] }] }, { year: 2013, title: 'The Secret Life of Walter Mitty', score: 1, highlights: [] }, { title: 'Jurassic World', year: 2015, score: 1, highlights: [] }, { title: 'Action Jackson', year: 2014, score: 1, highlights: [] }, { year: 2013, title: 'In Secret', score: 1, highlights: [] }, { title: 'The Stanford Prison Experiment', year: 2015, score: 1, highlights: [] }, { year: 2014, title: 'The Giver', score: 1, highlights: [] } 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、function
オプションを使用して、クエリ タームsnow
のスコアも変更します。
constant
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
compound-constant-example
という新しいディレクトリを作成し、dotnet new
コマンドでプロジェクトを初期化します。mkdir compound-constant-example cd compound-constant-example dotnet new console .NET/C# ドライバーを依存関係としてプロジェクトに追加します。
dotnet add package MongoDB.Driver Program.cs
ファイルの内容を、次のコードで置き換えます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次の複合句を使用して、コレクションをクエリします。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundConstantExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Filter(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015))) 26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Constant(5))), 27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title), 28 indexName: "compound-query-custom-score-tutorial") 29 .Project<MovieDocument>(Builders<MovieDocument>.Projection 30 .Include(movie => movie.Title) 31 .Include(movie => movie.Year) 32 .Exclude(movie => movie.Id) 33 .MetaSearchScore(movie => movie.Score) 34 .MetaSearchHighlights("highlights")) 35 .Limit(10) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string Title { get; set; } 52 public int Year { get; set; } 53 [ ]54 public List<SearchHighlight> Highlights { get; set; } 55 public double Score { get; set; } 56 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。Program.cs
ファイルをコンパイルして実行します。dotnet run compound-constant-example.csproj { "title" : "Snow in Paradise", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3828467130661011, "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " in Paradise" }] }], "score" : 5.0 } { "title" : "Dead Snow 2: Red vs. Dead", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3924485445022583, "texts" : [{ "type" : "Text", "value" : "Dead " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " 2: Red vs. " }] }], "score" : 5.0 } { "title" : "The Snow White Murder Case", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3525336980819702, "texts" : [{ "type" : "Text", "value" : "The " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " White Murder Case" }] }], "score" : 5.0 } { "title" : "Snow on the Blades", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3766303062438965, "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " on the Blades" }] }], "score" : 5.0 } { "title" : "The Secret Life of Walter Mitty", "year" : 2013, "highlights" : [], "score" : 0.0 } { "title" : "Jurassic World", "year" : 2015, "highlights" : [], "score" : 0.0 } { "title" : "Action Jackson", "year" : 2014, "highlights" : [], "score" : 0.0 } { "title" : "In Secret", "year" : 2013, "highlights" : [], "score" : 0.0 } { "title" : "The Stanford Prison Experiment", "year" : 2015, "highlights" : [], "score" : 0.0 } { "title" : "The Giver", "year" : 2014, "highlights" : [], "score" : 0.0 } 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、constant
オプションを使用して、クエリ タームsnow
のスコアも変更します。
boost
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
compound-boost-example
という新しいディレクトリを作成し、dotnet new
コマンドでプロジェクトを初期化します。mkdir compound-boost-example cd compound-boost-example dotnet new console .NET/C# ドライバーを依存関係としてプロジェクトに追加します。
dotnet add package MongoDB.Driver Program.cs
ファイルの内容を、次のコードで置き換えます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
クエリは、次のパイプライン ステージを使用します。
$search
ステージを使用して、コレクションをクエリします。 クエリでは以下の操作が実行されます。次の
compound
演算子句を使用します。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
出力を10の結果に制限する$limitステージ
$projectステージから次の操作へ。
title
とyear
を除くすべてのフィールドを除外score
とhighlights
という名前の 2 つのフィールドを追加します
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundBoostSingleExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015))) 26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(2))), 27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title), 28 indexName: "compound-query-custom-score-tutorial") 29 .Project<MovieDocument>(Builders<MovieDocument>.Projection 30 .Include(movie => movie.Title) 31 .Include(movie => movie.Year) 32 .Exclude(movie => movie.Id) 33 .MetaSearchScore(movie => movie.Score) 34 .MetaSearchHighlights("highlights")) 35 .Limit(10) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string Title { get; set; } 52 public int Year { get; set; } 53 [ ]54 public List<SearchHighlight> Highlights { get; set; } 55 public double Score { get; set; } 56 } このクエリでは、次の
compound
演算子句をboost
オプションとともに使用して、一部のフィールドの優先順位が他のフィールドよりも高くなっています。must
句をテキスト演算子とともに使用すると、ジャンルcomedy
が最も優先度が高く、その後にtitle
フィールドの用語snow
が優先されます。boost
オプションはフィールドに重みを適用します。should
句を範囲演算子とともに使用すると、2013
から2015
年の間の映画が検索されます。
注意
boost
オプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundBoostMultipleExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "comedy", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(9))) 26 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(5))) 27 .Should(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015), score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(3))), 28 indexName: "compound-query-custom-score-tutorial") 29 .Project<MovieDocument>(Builders<MovieDocument>.Projection 30 .Include(movie => movie.Genres) 31 .Include(movie => movie.Title) 32 .Include(movie => movie.Year) 33 .Exclude(movie => movie.Id) 34 .MetaSearchScore(movie => movie.Score)) 35 .Limit(10) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string [] Genres { get; set; } 52 public string Title { get; set; } 53 public int Year { get; set; } 54 public double Score { get; set; } 55 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。Program.cs
ファイルをコンパイルして実行します。dotnet run compound-boost-example.csproj { "title" : "Snow in Paradise", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3828467130661011, "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " in Paradise" }] }], "score" : 6.7722930908203125 } { "title" : "Snow on the Blades", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3766303062438965, "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " on the Blades" }] }], "score" : 6.0634455680847168 } { "title" : "The Snow White Murder Case", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3525336980819702, "texts" : [{ "type" : "Text", "value" : "The " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " White Murder Case" }] }], "score" : 5.5096521377563477 } { "title" : "Dead Snow 2: Red vs. Dead", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3924485445022583, "texts" : [{ "type" : "Text", "value" : "Dead " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " 2: Red vs. " }] }], "score" : 5.0650539398193359 } { "title" : "The Secret Life of Walter Mitty", "year" : 2013, "highlights" : [], "score" : 1.0 } { "title" : "Jurassic World", "year" : 2015, "highlights" : [], "score" : 1.0 } { "title" : "Action Jackson", "year" : 2014, "highlights" : [], "score" : 1.0 } { "title" : "In Secret", "year" : 2013, "highlights" : [], "score" : 1.0 } { "title" : "The Stanford Prison Experiment", "year" : 2015, "highlights" : [], "score" : 1.0 } { "title" : "The Giver", "year" : 2014, "highlights" : [], "score" : 1.0 } 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、boost
オプションを使用して、クエリ タームsnow
のスコアも変更します。dotnet run compound-boost-example.csproj { "genres" : ["Comedy", "Horror"], "title" : "Dead Snow", "year" : 2009, "score" : 21.872983932495117 } { "genres" : ["Adventure", "Comedy", "Family"], "title" : "Snow Day", "year" : 2000, "score" : 21.043487548828125 } { "genres" : ["Adventure", "Comedy", "Family"], "title" : "Snow Dogs", "year" : 2002, "score" : 21.043487548828125 } { "genres" : ["Comedy", "Romance"], "title" : "Let It Snow", "year" : 1999, "score" : 19.523927688598633 } { "genres" : ["Action", "Comedy", "Horror"], "title" : "Dead Snow 2: Red vs. Dead", "year" : 2014, "score" : 17.426334381103516 } { "genres" : ["Comedy", "Drama"], "title" : "Snow White and Russian Red", "year" : 2009, "score" : 16.367326736450195 } { "genres" : ["Comedy", "Drama", "Romance"], "title" : "The Tiger and the Snow", "year" : 2005, "score" : 15.537829399108887 } { "genres" : ["Adventure", "Comedy", "Family"], "title" : "Snow White and the Three Stooges", "year" : 1961, "score" : 14.426333427429199 }
function
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
compound-function-example
という新しいディレクトリを作成し、dotnet new
コマンドでプロジェクトを初期化します。mkdir compound-function-example cd compound-function-example dotnet new console .NET/C# ドライバーを依存関係としてプロジェクトに追加します。
dotnet add package MongoDB.Driver Program.cs
ファイルの内容を、次のコードで置き換えます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のパイプライン ステージを使用して、コレクションをクエリします。
次のパイプライン ステージを使用します。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundFunctionExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 var scoreFunction = Builders<MovieDocument>.SearchScore.Function(Builders<MovieDocument>.SearchScoreFunction.Add(Builders<MovieDocument>.SearchScoreFunction.Path(movie => movie.Imdb.Rating, 2), Builders<MovieDocument>.SearchScoreFunction.Relevance())); 23 // define and run pipeline 24 var results = moviesCollection.Aggregate() 25 .Search(Builders<MovieDocument>.Search.Compound() 26 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015))) 27 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: scoreFunction)), 28 new SearchHighlightOptions<MovieDocument>(movie => movie.Title), 29 indexName: "compound-query-custom-score-tutorial") 30 .Project<MovieDocument>(Builders<MovieDocument>.Projection 31 .Include(movie => movie.Genres) 32 .Include(movie => movie.Title) 33 .Include(movie => movie.Year) 34 .Exclude(movie => movie.Id) 35 .MetaSearchScore(movie => movie.Score) 36 .MetaSearchHighlights("highlights")) 37 .Limit(10) 38 .ToList(); 39 40 // print results 41 foreach (var movie in results) 42 { 43 Console.WriteLine(movie.ToJson()); 44 } 45 } 46 } 47 48 [ ]49 public class MovieDocument 50 { 51 [ ]52 public ObjectId Id { get; set; } 53 public string [] Genres { get; set; } 54 public IMDB Imdb { get; set; } 55 public string Title { get; set; } 56 public int Year { get; set; } 57 [ ]58 public List<SearchHighlight> Highlights { get; set; } 59 public double Score { get; set; } 60 } 61 62 [ ]63 public class IMDB 64 { 65 public double Rating { get; set; } 66 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。Program.cs
ファイルをコンパイルして実行します。dotnet run compound-function-example.csproj { "genres" : ["Drama", "Mystery"], "title" : "The Snow White Murder Case", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3525336980819702, "texts" : [{ "type" : "Text", "value" : "The " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " White Murder Case" }] }], "score" : 10.454826354980469 } { "genres" : ["Action", "Drama", "History"], "title" : "Snow on the Blades", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3766303062438965, "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " on the Blades" }] }], "score" : 10.331723213195801 } { "genres" : ["Action", "Comedy", "Horror"], "title" : "Dead Snow 2: Red vs. Dead", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3924485445022583, "texts" : [{ "type" : "Text", "value" : "Dead " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " 2: Red vs. " }] }], "score" : 10.032526969909668 } { "genres" : ["Thriller"], "title" : "Snow in Paradise", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3828467130661011, "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " in Paradise" }] }], "score" : 8.3861465454101562 } { "genres" : ["Adventure", "Comedy", "Drama"], "title" : "The Secret Life of Walter Mitty", "year" : 2013, "highlights" : [], "score" : 1.0 } { "genres" : ["Action", "Adventure", "Sci-Fi"], "title" : "Jurassic World", "year" : 2015, "highlights" : [], "score" : 1.0 } { "genres" : ["Action", "Comedy", "Drama"], "title" : "Action Jackson", "year" : 2014, "highlights" : [], "score" : 1.0 } { "genres" : ["Crime", "Drama", "Thriller"], "title" : "In Secret", "year" : 2013, "highlights" : [], "score" : 1.0 } { "genres" : ["Drama", "Thriller"], "title" : "The Stanford Prison Experiment", "year" : 2015, "highlights" : [], "score" : 1.0 } { "genres" : ["Drama", "Sci-Fi"], "title" : "The Giver", "year" : 2014, "highlights" : [], "score" : 1.0 } 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、function
オプションを使用して、クエリ タームsnow
のスコアも変更します。
constant
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
compound-constant-query.go
という名前のファイルを作成します。コード例をコピーして、
compound-constant-query.go
ファイルに貼り付けます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次の複合句を使用して、コレクションをクエリします。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 func main() { 14 // connect to your Atlas cluster 15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 16 if err != nil { 17 panic(err) 18 } 19 defer client.Disconnect(context.TODO()) 20 21 // set namespace 22 collection := client.Database("sample_mflix").Collection("movies") 23 24 // define pipeline stages 25 searchStage := bson.D{{"$search", bson.M{ 26 "index": "compound-query-custom-score-tutorial", 27 "compound": bson.M{ 28 "filter": bson.M{ 29 "range": bson.M{ 30 "path": "year", "gte": 2013, "lte": 2015, 31 }, 32 }, 33 "should": bson.D{ 34 {"text", bson.M{ 35 "path": "title", "query": "snow", "score": bson.M{ 36 "constant": bson.D{{"value", 5}}, 37 }}}}, 38 }, 39 "highlight": bson.D{{"path", "title"}}, 40 }}} 41 limitStage := bson.D{{"$limit", 10}} 42 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}} 43 44 // specify the amount of time the operation can run on the server 45 opts := options.Aggregate().SetMaxTime(5 * time.Second) 46 47 // run pipeline 48 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 49 if err != nil { 50 panic(err) 51 } 52 53 // print results 54 var results []bson.D 55 if err = cursor.All(context.TODO(), &results); err != nil { 56 panic(err) 57 } 58 for _, result := range results { 59 fmt.Println(result) 60 } 61 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。次のコマンドを実行して、コレクションをクエリします。
go run compound-constant-query.go [{title Snow in Paradise} {year 2014} {score 5} {highlights [[{score 1.382846713066101} {path title} {texts [[{value Snow} {type hit}] [{value in Paradise} {type text}]]}]]}] [{title Dead Snow 2: Red vs. Dead} {year 2014} {score 5} {highlights [[{score 1.3924485445022583} {path title} {texts [[{value Dead } {type text}] [{value Snow} {type hit}] [{value 2: Red vs. } {type text}]]}]]}] [{title The Snow White Murder Case} {year 2014} {score 5} {highlights [[{score 1.3525336980819702} {path title} {texts [[{value The } {type text}] [{value Snow} {type hit}] [{value White Murder Case} {type text}]]}]]}] [{title Snow on the Blades} {year 2014} {score 5} {highlights [[{score 1.3766303062438965} {path title} {texts [[{value Snow} {type hit}] [{value on the Blades} {type text}]]}]]}] [{year 2013} {title The Secret Life of Walter Mitty} {score 0} {highlights []}] [{title Jurassic World} {year 2015} {score 0} {highlights []}] [{title Action Jackson} {year 2014} {score 0} {highlights []}] [{year 2013} {title In Secret} {score 0} {highlights []}] [{title The Stanford Prison Experiment} {year 2015} {score 0} {highlights []}] [{year 2014} {title The Giver} {score 0} {highlights []}] 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、constant
オプションを使用して、クエリ タームsnow
のスコアも変更します。
boost
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
compound-boost-query.go
という名前のファイルを作成します。コード例をコピーして、
compound-boost-query.go
ファイルに貼り付けます。コード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
クエリは、次のパイプライン ステージを使用します。
$search
ステージを使用して、コレクションをクエリします。 クエリでは以下の操作が実行されます。次の
compound
句を使用して、コレクションをクエリします。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
出力を10の結果に制限する$limitステージ
$projectステージから次の操作へ。
title
とyear
を除くすべてのフィールドを除外score
とhighlights
という名前の 2 つのフィールドを追加します
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 // define structure of movies collection 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 } 17 18 func main() { 19