結果内のドキュメントのスコアをカスタマイズする方法
結果内のドキュメントの スコアはカスタマイズできます。スコアの計算方法を調整することで、最も関連するドキュメントが検索結果で上位に表示されるようになります。スコアをカスタマイズするさまざまな方法の詳細については、「 結果内のドキュメントのスコアリング 」を参照してください。このページでは、結果内のドキュメントのスコアを変更して結果をブーストまたは埋め込みする方法と、次の段階で$search
0
から の範囲で1
クエリ スコアを正規化する方法を説明します。集計パイプライン。 。
結果内のドキュメントのスコアを変更する
Atlas Search クエリが返すすべてのドキュメントには、その関連性に基づいてスコアが割り当てられます。結果セットに含まれるドキュメントは、最高スコアから最低スコアの順に返されます。詳細については、「結果内のドキュメントにスコアを付ける」を参照してください。
デフォルトのスコアリング動作を変更するには、すべての演算子で次のオプションを使用できます。詳細と例については、次のいずれかのオプションをクリックしてください。
このセクションでは、検索フィールドに重みを追加して、結果または結果のカテゴリ内のドキュメントをブーストまたは埋め込みする方法を説明します。具体的には、フィールドに 1 つ以上の値を割り当てて、スコアが高いか低い結果を返す方法を示します。
サンプル インデックス
動的マッピングを有効にしてコレクション内のすべてのフィールドにインデックスを付けるか、クエリを実行して結果をソートするフィールドの静的マッピングを使用してインデックスを設定できます。 Atlas Search インデックスの作成の詳細については、「 Atlas Search インデックスの作成 」を参照してください。
サンプル クエリ
サンプルクエリは、結果内のドキュメントをブーストまたは埋め込む方法を示しています。複合演算子を使用して、2 つ以上の演算子を 1 つのクエリに結合します。
➤ [ 言語を選択 ]ドロップダウン メニューを使用して、使用するクライアントを設定して、このセクションの例を試します。
Atlas Search が返す関連性スコアを向上させるには、sample_mflix.movies
名前空間の title
フィールドと year
フィールドを使用して、snow
というタームを含む映画タイトルで Atlas Search が返す関連性スコアを強化します。 movies
コレクションにインデックスを設定すると、次のクエリを実行できます。
Atlas Atlasで、プロジェクトの {0 ページにGoします。GoClusters
警告
ナビゲーションの改善が進行中
現在、新しく改善されたナビゲーション エクスペリエンスを展開しています。次の手順が Atlas UIのビューと一致しない場合は、プレビュー ドキュメントの を参照してください。
まだ表示されていない場合は、希望するプロジェクトを含む組織を選択しますナビゲーション バーの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: "default", 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: "default", 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: "default", 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: "default", 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
のスコアも変更します。
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": "default", "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": "default", "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": "default", "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": "default", "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": "default", "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": "default", "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": "default", "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": "default", "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: "default") 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: "default") 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: "default") 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: "default") 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/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 func main() { 14 // connect to the Atlas cluster and set a maximum operation time 15 opts := options.Client(). 16 SetTimeout(5 * time.Second). 17 ApplyURI("<connection-string>") 18 19 client, err := mongo.Connect(opts) 20 if err != nil { 21 panic(err) 22 } 23 defer client.Disconnect(context.TODO()) 24 25 // set namespace 26 collection := client.Database("sample_mflix").Collection("movies") 27 28 // define pipeline stages 29 searchStage := bson.D{{"$search", bson.M{ 30 "index": "default", 31 "compound": bson.M{ 32 "filter": bson.M{ 33 "range": bson.M{ 34 "path": "year", "gte": 2013, "lte": 2015, 35 }, 36 }, 37 "should": bson.D{ 38 {"text", bson.M{ 39 "path": "title", "query": "snow", "score": bson.M{ 40 "constant": bson.D{{"value", 5}}, 41 }}}}, 42 }, 43 "highlight": bson.D{{"path", "title"}}, 44 }}} 45 limitStage := bson.D{{"$limit", 10}} 46 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}} 47 48 // run pipeline 49 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) 50 if err != nil { 51 panic(err) 52 } 53 54 // print results 55 var results []bson.D 56 if err = cursor.All(context.TODO(), &results); err != nil { 57 panic(err) 58 } 59 for _, result := range results { 60 fmt.Println(result) 61 } 62 } サンプルを実行する前に、
<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/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/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 var err error 20 // connect to the Atlas cluster and set a maximum operation time 21 ctx := context.Background() 22 opts := options.Client(). 23 SetTimeout(5 * time.Second). 24 ApplyURI("<connection-string>") 25 26 client, err := mongo.Connect(opts) 27 if err != nil { 28 panic(err) 29 } 30 defer client.Disconnect(ctx) 31 // set namespace 32 collection := client.Database("sample_mflix").Collection("movies") 33 // define pipeline 34 searchStage := bson.D{{"$search", bson.M{ 35 "index": "default", 36 "compound": bson.M{ 37 "must": bson.M{ 38 "range": bson.M{ 39 "path": "year", "gte": 2013, "lte": 2015, 40 }, 41 }, 42 "should": bson.D{ 43 {"text", bson.M{ 44 "path": "title", "query": "snow", "score": bson.M{ 45 "boost": bson.D{{"value", 2}}, 46 }, 47 }}, 48 }, 49 }, 50 }}} 51 limitStage := bson.D{{"$limit", 10}} 52 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 53 // run pipeline 54 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}) 55 if err != nil { 56 panic(err) 57 } 58 // print results 59 var results []bson.D 60 if err = cursor.All(context.TODO(), &results); err != nil { 61 panic(err) 62 } 63 for _, result := range results { 64 fmt.Println(result) 65 } 66 } このクエリでは、次のパイプライン ステージを使用します。
$search
ステージを使用して、コレクションをクエリします。 クエリでは以下の操作が実行されます。
出力を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/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/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 var err error 20 // connect to the Atlas cluster and set a maximum operation time 21 ctx := context.Background() 22 opts := options.Client(). 23 SetTimeout(5 * time.Second). 24 ApplyURI("<connection-string>") 25 26 client, err := mongo.Connect(opts) 27 if err != nil { 28 panic(err) 29 } 30 defer client.Disconnect(ctx) 31 // set namespace 32 collection := client.Database("sample_mflix").Collection("movies") 33 // define pipeline 34 searchStage := bson.D{{"$search", bson.M{ 35 "index": "default", 36 "compound": bson.M{ 37 "must": bson.A{ 38 bson.M{ 39 "text": bson.M{ 40 "path": "genres", "query": "comedy", "score": bson.M{ 41 "boost": bson.D{{"value", 9}}, 42 }, 43 }, 44 }, 45 bson.M{ 46 "text": bson.M{ 47 "path": "title", "query": "snow", "score": bson.M{ 48 "boost": bson.D{{"value", 5}}, 49 }, 50 }, 51 }, 52 }, 53 "should": bson.M{ 54 "range": bson.M{ 55 "path": "year", "gte": 2013, "lte": 2015, "score": bson.M{ 56 "boost": bson.D{{"value", 3}}, 57 }, 58 }, 59 }, 60 }, 61 }}} 62 limitStage := bson.D{{"$limit", 10}} 63 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"genres", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 64 // run pipeline 65 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}) 66 if err != nil { 67 panic(err) 68 } 69 // print results 70 var results []bson.D 71 if err = cursor.All(context.TODO(), &results); err != nil { 72 panic(err) 73 } 74 for _, result := range results { 75 fmt.Println(result) 76 } 77 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。次のコマンドを実行して、コレクションをクエリします。
go run compound-boost-query.go [{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
のスコアも変更します。go run compound-boost-query.go [ { 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 複合クエリを実行します。
compound-boost-query.go
という名前のファイルを作成します。コード例をコピーして、
compound-function-query.go
ファイルに貼り付けます。このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次の
compound
演算子句を使用します。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 func main() { 14 // connect to the Atlas cluster and set a maximum operation time 15 opts := options.Client(). 16 SetTimeout(5 * time.Second). 17 ApplyURI("<connection-string>") 18 19 client, err := mongo.Connect(opts) 20 if err != nil { 21 panic(err) 22 } 23 defer client.Disconnect(context.TODO()) 24 25 // set namespace 26 collection := client.Database("sample_mflix").Collection("movies") 27 28 // define pipeline 29 searchStage := bson.D{{"$search", bson.M{ 30 "index": "default", 31 "compound": bson.M{ 32 "must": bson.M{ 33 "range": bson.M{ 34 "path": "year", "gte": 2013, "lte": 2015, 35 }, 36 }, 37 "should": bson.D{ 38 {"text", bson.M{ 39 "path": "title", "query": "snow", "score": bson.M{ 40 "function": bson.D{{"add", bson.A{ 41 bson.D{{"path", bson.D{ 42 {"value", "imdb.rating"}, {"undefined", 2}, 43 }}}, 44 bson.D{{"score", "relevance"}}, 45 }}}, 46 }}}}, 47 }, 48 "highlight": bson.D{{"path", "title"}}, 49 }}} 50 limitStage := bson.D{{"$limit", 10}} 51 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}} 52 53 // run pipeline 54 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}) 55 if err != nil { 56 panic(err) 57 } 58 59 // print results 60 var results []bson.D 61 if err = cursor.All(context.TODO(), &results); err != nil { 62 panic(err) 63 } 64 for _, result := range results { 65 fmt.Println(result) 66 } 67 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。次のコマンドを実行して、コレクションをクエリします。
go run compound-function-query.go [{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 複合クエリを実行します。
CompoundConstantQuery.java
という名前のファイルを作成します。以下のコードをコピーして、 ファイルに貼り付けます。
このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次の複合句を使用して、コレクションをクエリします。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 12 import org.bson.Document; 13 14 public class CompoundConstantQuery { 15 public static void main( String[] args ) { 16 // define clauses 17 List<Document> mustClauses = 18 List.of( 19 new Document( 20 "range", new Document("path", "year") 21 .append("gte", 2013) 22 .append("lte", 2015))); 23 List<Document> shouldClauses = 24 List.of( 25 new Document("text", 26 new Document("query", "snow") 27 .append("path", "title") 28 .append("score", new Document("constant", new Document("value", 5))))); 29 Document highlightOption = new Document("path", "title"); 30 // define query 31 Document agg = 32 new Document("$search", 33 new Document("index", "default") 34 .append("compound", 35 new Document("must", mustClauses).append("should", shouldClauses)) 36 .append("highlight", highlightOption)); 37 // specify connection 38 String uri = "<connection-string>"; 39 // establish connection and set namespace 40 try (MongoClient mongoClient = MongoClients.create(uri)) { 41 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 42 MongoCollection<Document> collection = database.getCollection("movies"); 43 // run query and print results 44 collection.aggregate(Arrays.asList(agg, 45 limit(10), 46 project(fields( 47 excludeId(), 48 include("title", "year"), 49 computed("score", new Document("$meta", "searchScore")), 50 computed("highlights", new Document("$meta", "searchHighlights")))))) 51 .forEach(doc -> System.out.println(doc.toJson())); 52 } 53 } 54 } 注意
Maven 環境でサンプル コードを実行するには、 ファイルのインポート ステートメントの上に以下を追加します。
package com.mongodb.drivers; サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。CompoundConstantQuery.java
ファイルをコンパイルして実行します。javac CompoundConstantQuery.java java CompoundConstantQuery {"title": "Snow in Paradise", "year": 2014, "score": 5.0, "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.0, "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.0, "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.0, "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.0, "highlights": []} {"title": "Jurassic World", "year": 2015, "score": 0.0, "highlights": []} {"title": "Action Jackson", "year": 2014, "score": 0.0, "highlights": []} {"year": 2013, "title": "In Secret", "score": 0.0, "highlights": []} {"title": "The Stanford Prison Experiment", "year": 2015, "score": 0.0, "highlights": []} {"year": 2014, "title": "The Giver", "score": 0.0, "highlights": []} 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、constant
オプションを使用して、クエリ タームsnow
のスコアも変更します。
boost
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
CompoundBoostQuery.java
という名前のファイルを作成します。以下のコードをコピーして、 ファイルに貼り付けます。
このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
クエリは、次のパイプライン ステージを使用します。
$search
ステージを使用して、コレクションをクエリします。 クエリでは以下の操作が実行されます。次の
compound
演算子句を使用します。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
出力を10の結果に制限する$limitステージ
$projectステージから次の操作へ。
title
とyear
を除くすべてのフィールドを除外score
とhighlights
という名前の 2 つのフィールドを追加します
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 public class CompoundBoostQuery { 14 public static void main( String[] args ) { 15 // define clauses 16 List<Document> mustClauses = 17 List.of( 18 new Document( 19 "range", new Document("path", "year") 20 .append("gte", 2013) 21 .append("lte", 2015))); 22 List<Document> shouldClauses = 23 List.of( 24 new Document( 25 "text", 26 new Document("query", "snow") 27 .append("path", "title") 28 .append("score", new Document("boost", new Document("value", 2))))); 29 Document highlightOption = new Document("path", "title"); 30 // define query 31 Document agg = 32 new Document("$search", 33 new Document("index", "default") 34 .append("compound", 35 new Document("must", mustClauses).append("should", shouldClauses)) 36 .append("highlight", highlightOption)); 37 // specify connection 38 String uri = "<connection-string>"; 39 // establish connection and set namespace 40 try (MongoClient mongoClient = MongoClients.create(uri)) { 41 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 42 MongoCollection<Document> collection = database.getCollection("movies"); 43 // run query and print results 44 collection.aggregate(Arrays.asList(agg, 45 limit(10), 46 project(fields( 47 excludeId(), 48 include("title", "year"), 49 computed("score", new Document("$meta", "searchScore")), 50 computed("highlights", new Document("$meta", "searchHighlights")))))) 51 .forEach(doc -> System.out.println(doc.toJson())); 52 } 53 } 54 } このクエリでは、次の
compound
演算子句をboost
オプションとともに使用して、一部のフィールドの優先順位が他のフィールドよりも高くなっています。must
句をテキスト演算子とともに使用すると、ジャンルcomedy
が最も優先度が高く、その後にtitle
フィールドの用語snow
が優先されます。boost
オプションはフィールドに重みを適用します。should
句を範囲演算子とともに使用すると、2013
から2015
年の間の映画が検索されます。
注意
boost
オプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.computed; 6 import static com.mongodb.client.model.Projections.excludeId; 7 import static com.mongodb.client.model.Projections.fields; 8 import static com.mongodb.client.model.Projections.include; 9 import com.mongodb.client.MongoClient; 10 import com.mongodb.client.MongoClients; 11 import com.mongodb.client.MongoCollection; 12 import com.mongodb.client.MongoDatabase; 13 import org.bson.Document; 14 15 public class CompoundBoostQuery { 16 public static void main( String[] args ) { 17 Document agg = new Document("index", "default") 18 .append("must", Arrays.asList(new Document("text", 19 new Document("path", "genres") 20 .append("query", "comedy") 21 .append("score", 22 new Document("boost", 23 new Document("value", 9)))), 24 new Document("text", 25 new Document("path", "title") 26 .append("query", "snow") 27 .append("score", 28 new Document("boost", 29 new Document("value", 5)))))) 30 .append("should", Arrays.asList(new Document("range", 31 new Document("path", "year") 32 .append("gte", 2013) 33 .append("lte", 2015) 34 .append("score", 35 new Document("boost", 36 new Document("value", 3)))))); 37 38 String uri = "<connection-string>"; 39 40 try (MongoClient mongoClient = MongoClients.create(uri)) { 41 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 42 MongoCollection<Document> collection = database.getCollection("movies"); 43 44 collection.aggregate(Arrays.asList( 45 eq("$search", eq("compound", agg)), 46 limit(10), 47 project(fields(excludeId(), include("title", "year","genres"), computed("score", new Document("$meta", "searchScore"))))) 48 ).forEach(doc -> System.out.println(doc.toJson())); 49 } 50 } 51 } 注意
Maven 環境でサンプル コードを実行するには、 ファイルのインポート ステートメントの上に以下を追加します。
package com.mongodb.drivers; サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。CompoundBoostQuery.java
ファイルをコンパイルして実行します。javac CompoundBoostQuery.java java CompoundBoostQuery {"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.0, "highlights": []} {"title": "Jurassic World", "year": 2015, "score": 1.0, "highlights": []} {"title": "Action Jackson", "year": 2014, "score": 1.0, "highlights": []} {"year": 2013, "title": "In Secret", "score": 1.0, "highlights": []} {"title": "The Stanford Prison Experiment", "year": 2015, "score": 1.0, "highlights": []} {"year": 2014, "title": "The Giver", "score": 1.0, "highlights": []} 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、boost
オプションを使用して、クエリ タームsnow
のスコアも変更します。javac CompoundBoostQuery.java java CompoundBoostQuery { "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 複合クエリを実行します。
CompoundFunctionQuery.java
という名前のファイルを作成します。以下のコードをコピーして、 ファイルに貼り付けます。
このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のパイプライン ステージを使用して、コレクションをクエリします。
次のパイプライン ステージを使用します。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 public class CompoundFunctionQuery { 14 public static void main( String[] args ) { 15 // define clauses 16 List<Document> mustClauses = 17 List.of( 18 new Document("range", new Document("path", "year") 19 .append("gte", 2013) 20 .append("lte", 2015))); 21 List<Document> shouldClauses = 22 List.of( 23 new Document("text", 24 new Document("query", "snow") 25 .append("path", "title") 26 .append("score", new Document("function", 27 new Document("add", Arrays.asList( 28 new Document("path", new Document("value", "imdb.rating") 29 .append("undefined", 2)), new Document("score", "relevance"))))))); 30 Document highlightOption = new Document("path", "title"); 31 // define query 32 Document agg = 33 new Document("$search", 34 new Document("index", "default") 35 .append("compound", 36 new Document("must", mustClauses).append("should", shouldClauses)) 37 .append("highlight", highlightOption)); 38 // specify connection 39 String uri = "<connection-string>"; 40 // establish connection and set namespace 41 try (MongoClient mongoClient = MongoClients.create(uri)) { 42 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 43 MongoCollection<Document> collection = database.getCollection("movies"); 44 // run query and print results 45 collection.aggregate(Arrays.asList(agg, 46 limit(10), 47 project(fields( 48 excludeId(), 49 include("title", "year"), 50 computed("score", new Document("$meta", "searchScore")), 51 computed("highlights", new Document("$meta", "searchHighlights")))))) 52 .forEach(doc -> System.out.println(doc.toJson())); 53 } 54 } 55 } 注意
Maven 環境でサンプル コードを実行するには、 ファイルのインポート ステートメントの上に以下を追加します。
package com.mongodb.drivers; サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。CompoundFunctionQuery.java
ファイルをコンパイルして実行します。javac CompoundFunctionQuery.java java CompoundFunctionQuery {"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.0, "highlights": []} {"title": "Jurassic World", "year": 2015, "score": 1.0, "highlights": []} {"title": "Action Jackson", "year": 2014, "score": 1.0, "highlights": []} {"year": 2013, "title": "In Secret", "score": 1.0, "highlights": []} {"title": "The Stanford Prison Experiment", "year": 2015, "score": 1.0, "highlights": []} {"year": 2014, "title": "The Giver", "score": 1.0, "highlights": []} 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、function
オプションを使用して、クエリ タームsnow
のスコアも変更します。
constant
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
CompoundConstantQuery.kt
という名前のファイルを作成します。以下のコードをコピーして、 ファイルに貼り付けます。
このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次の複合句を使用して、コレクションをクエリします。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。次のパイプライン ステージを使用します。
クエリに一致するドキュメントを
AggregateFlow
インスタンスから出力します。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_mflix") 13 val collection = database.getCollection<Document>("movies") 14 15 runBlocking { 16 // define clauses 17 val mustClauses = listOf( 18 Document( 19 "range", Document("path", "year") 20 .append("gte", 2013) 21 .append("lte", 2015) 22 ) 23 ) 24 25 val shouldClauses = listOf( 26 Document( 27 "text", 28 Document("query", "snow") 29 .append("path", "title") 30 .append("score", Document("constant", Document("value", 5))) 31 ) 32 ) 33 34 val highlightOption = Document("path", "title") 35 36 // define pipeline 37 val agg = Document( 38 "\$search", 39 Document("index", "default") 40 .append( 41 "compound", 42 Document("must", mustClauses).append("should", shouldClauses) 43 ) 44 .append("highlight", highlightOption) 45 ) 46 47 val resultsFlow = collection.aggregate<Document>( 48 listOf( 49 agg, 50 limit(10), 51 project(fields( 52 excludeId(), 53 include("title", "year"), 54 computed("score", Document("\$meta", "searchScore")), 55 computed("highlights", Document("\$meta", "searchHighlights")) 56 )) 57 ) 58 ) 59 resultsFlow.collect { println(it) } 60 } 61 mongoClient.close() 62 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。CompoundConstantQuery.kt
ファイルを実行します。IDE で
CompoundConstantQuery.kt
プログラムを実行すると、次のドキュメントが出力されます。Document{{title=Snow in Paradise, year=2014, score=6.0, highlights=[Document{{score=1.382846713066101, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= in Paradise, type=text}}]}}]}} Document{{title=Dead Snow 2: Red vs. Dead, year=2014, score=6.0, highlights=[Document{{score=1.3924485445022583, path=title, texts=[Document{{value=Dead , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= 2: Red vs. , type=text}}]}}]}} Document{{title=The Snow White Murder Case, year=2014, score=6.0, highlights=[Document{{score=1.3525336980819702, path=title, texts=[Document{{value=The , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= White Murder Case, type=text}}]}}]}} Document{{title=Snow on the Blades, year=2014, score=6.0, highlights=[Document{{score=1.3766303062438965, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= on the Blades, type=text}}]}}]}} Document{{year=2013, title=The Secret Life of Walter Mitty, score=1.0, highlights=[]}} Document{{title=Jurassic World, year=2015, score=1.0, highlights=[]}} Document{{title=Action Jackson, year=2014, score=1.0, highlights=[]}} Document{{year=2013, title=In Secret, score=1.0, highlights=[]}} Document{{title=The Stanford Prison Experiment, year=2015, score=1.0, highlights=[]}} Document{{year=2014, title=The Giver, score=1.0, highlights=[]}} 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、constant
オプションを使用して、クエリ タームsnow
のスコアも変更します。
boost
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
CompoundBoostQuery.kt
という名前のファイルを作成します。以下のコードをコピーして、 ファイルに貼り付けます。
このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
クエリに一致するドキュメントを
AggregateFlow
インスタンスから出力します。
クエリは、次のパイプライン ステージを使用します。
$search
ステージを使用して、コレクションをクエリします。 クエリでは以下の操作が実行されます。次の
compound
演算子句を使用します。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
出力を10の結果に制限する$limitステージ
$projectステージから次の操作へ。
title
とyear
を除くすべてのフィールドを除外score
とhighlights
という名前の 2 つのフィールドを追加します
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define clauses 18 val mustClauses = listOf( 19 Document( 20 "range", Document("path", "year") 21 .append("gte", 2013) 22 .append("lte", 2015) 23 ) 24 ) 25 26 val shouldClauses = listOf( 27 Document( 28 "text", 29 Document("query", "snow") 30 .append("path", "title") 31 .append("score", Document("boost", Document("value", 2))) 32 ) 33 ) 34 35 val highlightOption = Document("path", "title") 36 37 // define pipeline 38 val agg = Document( 39 "\$search", 40 Document("index", "default") 41 .append( 42 "compound", 43 Document("must", mustClauses).append("should", shouldClauses) 44 ) 45 .append("highlight", highlightOption) 46 ) 47 48 // run query and print results 49 val resultsFlow = collection.aggregate<Document>( 50 listOf( 51 agg, 52 limit(10), 53 project(fields( 54 excludeId(), 55 include("title", "year"), 56 computed("score", Document("\$meta", "searchScore")), 57 computed("highlights", Document("\$meta", "searchHighlights")) 58 )) 59 ) 60 ) 61 resultsFlow.collect { println(it) } 62 } 63 mongoClient.close() 64 } このクエリでは、次の
compound
演算子句をboost
オプションとともに使用して、一部のフィールドの優先順位が他のフィールドよりも高くなっています。must
句をテキスト演算子とともに使用すると、ジャンルcomedy
が最も優先度が高く、その後にtitle
フィールドの用語snow
が優先されます。boost
オプションはフィールドに重みを適用します。should
句を範囲演算子とともに使用すると、2013
から2015
年の間の映画が検索されます。
注意
boost
オプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define pipeline 18 val agg = Document( 19 "\$search", 20 Document("index", "default") 21 .append( 22 "compound", 23 Document( 24 "must", listOf( 25 Document( 26 "text", 27 Document("path", "genres") 28 .append("query", "comedy") 29 .append( 30 "score", 31 Document( 32 "boost", 33 Document("value", 9) 34 ) 35 ) 36 ), 37 Document( 38 "text", 39 Document("path", "title") 40 .append("query", "snow") 41 .append( 42 "score", 43 Document( 44 "boost", 45 Document("value", 5) 46 ) 47 ) 48 ) 49 ) 50 ) 51 .append( 52 "should", listOf( 53 Document( 54 "range", 55 Document("path", "year") 56 .append("gte", 2013) 57 .append("lte", 2015) 58 .append( 59 "score", 60 Document( 61 "boost", 62 Document("value", 3) 63 ) 64 ) 65 ) 66 ) 67 ) 68 ) 69 ) 70 71 // run query and print results 72 val resultsFlow = collection.aggregate<Document>( 73 listOf( 74 agg, 75 limit(10), 76 project(fields( 77 excludeId(), 78 include("title", "year","genres"), 79 computed("score", Document("\$meta", "searchScore")) 80 )) 81 ) 82 ) 83 resultsFlow.collect { println(it) } 84 } 85 mongoClient.close() 86 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。CompoundBoostQuery.kt
ファイルを実行します。IDE で
CompoundBoostQuery.kt
プログラムを実行すると、次のドキュメントが出力されます。Document{{title=Snow in Paradise, year=2014, score=6.784297466278076, highlights=[Document{{score=1.382846713066101, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= in Paradise, type=text}}]}}]}} Document{{title=Snow on the Blades, year=2014, score=6.073266506195068, highlights=[Document{{score=1.3766303062438965, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= on the Blades, type=text}}]}}]}} Document{{title=The Snow White Murder Case, year=2014, score=5.517906188964844, highlights=[Document{{score=1.3525336980819702, path=title, texts=[Document{{value=The , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= White Murder Case, type=text}}]}}]}} Document{{title=Dead Snow 2: Red vs. Dead, year=2014, score=5.072136878967285, highlights=[Document{{score=1.3924485445022583, path=title, texts=[Document{{value=Dead , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= 2: Red vs. , type=text}}]}}]}} Document{{year=2013, title=The Secret Life of Walter Mitty, score=1.0, highlights=[]}} Document{{title=Jurassic World, year=2015, score=1.0, highlights=[]}} Document{{title=Action Jackson, year=2014, score=1.0, highlights=[]}} Document{{year=2013, title=In Secret, score=1.0, highlights=[]}} Document{{title=The Stanford Prison Experiment, year=2015, score=1.0, highlights=[]}} Document{{year=2014, title=The Giver, score=1.0, highlights=[]}} 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、boost
オプションを使用して、クエリ タームsnow
のスコアも変更します。IDE で
CompoundBoostQuery.kt
プログラムを実行すると、次のドキュメントが出力されます。Document{{year=2000, genres=[Adventure, Comedy, Family], title=Snow Day, score=20.998544692993164}} Document{{genres=[Adventure, Comedy, Family], title=Snow Dogs, year=2002, score=20.998544692993164}} Document{{year=1999, genres=[Comedy, Romance], title=Let It Snow, score=19.45327377319336}} Document{{genres=[Action, Comedy, Horror], title=Dead Snow 2: Red vs. Dead, year=2014, score=17.361087799072266}} Document{{genres=[Comedy, Drama], title=Snow White and Russian Red, year=2009, score=16.287294387817383}} Document{{genres=[Comedy, Drama, Romance], title=The Tiger and the Snow, year=2005, score=15.475509643554688}} Document{{genres=[Adventure, Comedy, Family], title=Snow White and the Three Stooges, year=1961, score=14.361087799072266}}
function
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
CompoundFunctionQuery.kt
という名前のファイルを作成します。以下のコードをコピーして、 ファイルに貼り付けます。
このコード例では、次のタスクを実行します。
mongodb
パッケージと依存関係をインポートします。Atlas クラスターへの接続を確立します。
次のパイプライン ステージを使用して、コレクションをクエリします。
次のパイプライン ステージを使用します。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。クエリに一致するドキュメントを
AggregateFlow
インスタンスから出力します。
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define clauses 18 val mustClauses = listOf( 19 Document( 20 "range", Document("path", "year") 21 .append("gte", 2013) 22 .append("lte", 2015) 23 ) 24 ) 25 26 val shouldClauses = listOf( 27 Document("text", Document("query", "snow") 28 .append("path", "title") 29 .append("score", 30 Document("function", Document("add", listOf( 31 Document("path", Document("value", "imdb.rating").append("undefined", 2)), 32 Document("score", "relevance") 33 ))) 34 ) 35 ) 36 ) 37 38 val highlightOption = Document("path", "title") 39 40 // define pipeline 41 val agg = Document( 42 "\$search", 43 Document("index", "default") 44 .append( 45 "compound", 46 Document("must", mustClauses).append("should", shouldClauses) 47 ) 48 .append("highlight", highlightOption) 49 ) 50 51 // run query and print results 52 val resultsFlow = collection.aggregate<Document>( 53 listOf( 54 agg, 55 limit(10), 56 project(fields( 57 excludeId(), 58 include("title", "year"), 59 computed("score", Document("\$meta", "searchScore")), 60 computed("highlights", Document("\$meta", "searchHighlights")) 61 )) 62 ) 63 ) 64 resultsFlow.collect { println(it) } 65 } 66 mongoClient.close() 67 } サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。CompoundFunctionQuery.kt
ファイルを実行します。IDE で
CompoundFunctionQuery.kt
プログラムを実行すると、次のドキュメントが出力されます。Document{{title=The Snow White Murder Case, year=2014, score=10.458952903747559, highlights=[Document{{score=1.3525336980819702, path=title, texts=[Document{{value=The , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= White Murder Case, type=text}}]}}]}} Document{{title=Snow on the Blades, year=2014, score=10.336633682250977, highlights=[Document{{score=1.3766303062438965, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= on the Blades, type=text}}]}}]}} Document{{title=Dead Snow 2: Red vs. Dead, year=2014, score=10.036067962646484, highlights=[Document{{score=1.3924485445022583, path=title, texts=[Document{{value=Dead , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= 2: Red vs. , type=text}}]}}]}} Document{{title=Snow in Paradise, year=2014, score=8.392148971557617, highlights=[Document{{score=1.382846713066101, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= in Paradise, type=text}}]}}]}} Document{{year=2013, title=The Secret Life of Walter Mitty, score=1.0, highlights=[]}} Document{{title=Jurassic World, year=2015, score=1.0, highlights=[]}} Document{{title=Action Jackson, year=2014, score=1.0, highlights=[]}} Document{{year=2013, title=In Secret, score=1.0, highlights=[]}} Document{{title=The Stanford Prison Experiment, year=2015, score=1.0, highlights=[]}} Document{{year=2014, title=The Giver, score=1.0, highlights=[]}} 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、function
オプションを使用して、クエリ タームsnow
のスコアも変更します。
constant
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
compound-constant-query.js
という名前のファイルを作成します。コード例をコピーして、
compound-constant-query.js
ファイルに貼り付けます。このコード例では、次のタスクを実行します。
MongoDB の Node.js ドライバーである
mongodb
をインポートします。Atlas クラスターへの接続を確立するための
MongoClient
クラスのインスタンスを作成します。次の複合句を使用して、コレクションをクエリします。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'default', 8 'compound': { 9 'filter': [ 10 { 11 'range': { 12 'path': 'year', 13 'gte': 2013, 14 'lte': 2015 15 } 16 } 17 ], 18 'should': [ 19 { 20 'text': { 21 'query': 'snow', 22 'path': 'title', 23 'score': { 24 'constant': { 25 'value': 5 26 } 27 } 28 } 29 } 30 ] 31 }, 32 'highlight': { 33 'path': 'title' 34 } 35 } 36 }, { 37 '$limit': 10 38 }, { 39 '$project': { 40 '_id': 0, 41 'title': 1, 42 'year': 1, 43 'score': { 44 '$meta': 'searchScore' 45 }, 46 'highlights': { 47 '$meta': 'searchHighlights' 48 } 49 } 50 } 51 ]; 52 53 MongoClient.connect( 54 "<connection-string>", 55 { useNewUrlParser: true, useUnifiedTopology: true }, 56 async function (connectErr, client) { 57 assert.equal(null, connectErr); 58 const coll = client.db("sample_mflix").collection("movies"); 59 let cursor = await coll.aggregate(agg); 60 await cursor.forEach((doc) => console.log(doc)); 61 client.close(); 62 } 63 ); サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。次のコマンドを実行して、コレクションをクエリします。
node compound-constant-query.js '{"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.js
という名前のファイルを作成します。コード例をコピーして、
compound-boost-query.js
ファイルに貼り付けます。このコード例では、次のタスクを実行します。
MongoDB の Node.js ドライバーである
mongodb
をインポートします。Atlas クラスターへの接続を確立するための
MongoClient
クラスのインスタンスを作成します。カーソルを反復処理して、クエリに一致するドキュメントを出力します。
クエリは、次のパイプライン ステージを使用します。
$search
ステージを使用して、コレクションをクエリします。 クエリでは以下の操作が実行されます。次の
compound
演算子句を使用します。クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
出力を10の結果に制限する$limitステージ
$projectステージから次の操作へ。
title
とyear
を除くすべてのフィールドを除外score
とhighlights
という名前の 2 つのフィールドを追加します
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'default', 8 'compound': { 9 'must': [ 10 { 11 'range': { 12 'path': 'year', 13 'gte': 2013, 14 'lte': 2015 15 } 16 } 17 ], 18 'should': [ 19 { 20 'text': { 21 'query': 'snow', 22 'path': 'title', 23 'score': { 24 'boost': { 25 'value': 2 26 } 27 } 28 } 29 } 30 ] 31 } 32 } 33 }, { 34 '$limit': 10 35 }, { 36 '$project': { 37 '_id': 0, 38 'title': 1, 39 'year': 1, 40 'score': { 41 '$meta': 'searchScore' 42 } 43 } 44 } 45 ]; 46 47 MongoClient.connect( 48 "<connection-string>", 49 { useNewUrlParser: true, useUnifiedTopology: true }, 50 async function (connectErr, client) { 51 assert.equal(null, connectErr); 52 const coll = client.db("sample_mflix").collection("movies"); 53 let cursor = await coll.aggregate(agg); 54 await cursor.forEach((doc) => console.log(doc)); 55 client.close(); 56 } 57 ); クエリは、次のパイプライン ステージを使用します。
$search
ステージを使用して、コレクションをクエリします。 クエリでは以下の操作が実行されます。
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'default', 8 'compound': { 9 'must': [ 10 { 11 'text': { 12 'path': 'genres', 13 'query': 'comedy', 14 'score': { 15 'boost': { 16 'value': 9 17 } 18 } 19 } 20 }, { 21 'text': { 22 'path': 'title', 23 'query': 'snow', 24 'score': { 25 'boost': { 26 'value': 5 27 } 28 } 29 } 30 } 31 ], 32 'should': [ 33 { 34 'range': { 35 'path': 'year', 36 'gte': 2013, 37 'lte': 2015, 38 'score': { 39 'boost': { 40 'value': 3 41 } 42 } 43 } 44 } 45 ] 46 } 47 } 48 }, { 49 '$limit': 10 50 }, { 51 '$project': { 52 '_id': 0, 53 'title': 1, 54 'year': 1, 55 'genres': 1, 56 'score': { 57 '$meta': 'searchScore' 58 } 59 } 60 } 61 ]; 62 63 MongoClient.connect( 64 "<connection-string>", 65 { useNewUrlParser: true, useUnifiedTopology: true }, 66 async function (connectErr, client) { 67 assert.equal(null, connectErr); 68 const coll = client.db("sample_mflix").collection("movies"); 69 let cursor = await coll.aggregate(agg); 70 await cursor.forEach((doc) => console.log(doc)); 71 client.close(); 72 } 73 ); サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。次のコマンドを実行して、コレクションをクエリします。
node compound-boost-query.js '{"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
のスコアも変更します。node compound-boost-query.js { 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 複合クエリを実行します。
compound-function-query.js
という名前のファイルを作成します。コード例をコピーして、
compound-function-query.js
ファイルに貼り付けます。このコード例では、次のタスクを実行します。
MongoDB の Node.js ドライバーである
mongodb
をインポートします。Atlas クラスターへの接続を確立するための
MongoClient
クラスのインスタンスを作成します。次の複合句を使用して、コレクションをクエリします。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'default', 8 'compound': { 9 'must': [ 10 { 11 'range': { 12 'path': 'year', 13 'gte': 2013, 14 'lte': 2015 15 } 16 } 17 ], 18 'should': [ 19 { 20 'text': { 21 'query': 'snow', 22 'path': 'title', 23 'score': { 24 'function': { 25 'add': [ 26 { 27 'path': { 28 'value': 'imdb.rating', 29 'undefined': 2 30 } 31 }, { 32 'score': 'relevance' 33 } 34 ] 35 } 36 } 37 } 38 } 39 ] 40 } 41 } 42 }, { 43 '$limit': 10 44 }, { 45 '$project': { 46 '_id': 0, 47 'title': 1, 48 'year': 1, 49 'score': { 50 '$meta': 'searchScore' 51 }, 52 'highlights': { 53 '$meta': 'searchHighlights' 54 } 55 } 56 } 57 ]; 58 59 MongoClient.connect( 60 "<connection-string>", 61 { useNewUrlParser: true, useUnifiedTopology: true }, 62 async function (connectErr, client) { 63 assert.equal(null, connectErr); 64 const coll = client.db("sample_mflix").collection("movies"); 65 let cursor = await coll.aggregate(agg); 66 await cursor.forEach((doc) => console.log(doc)); 67 client.close(); 68 } 69 ); サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。次のコマンドを実行して、コレクションをクエリします。
node compound-function-query.js '{"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-query.py
という名前のファイルを作成します。コード例をコピーして、
compound-constant.py
ファイルに貼り付けます。次のコード例では、次を行います。
pymongo
、MongoDB の Python ドライバー、およびDNSシード リスト接続文字列を使用してpymongo
をAtlas
に接続するために必要なdns
モジュールをインポートします。Atlas クラスターへの接続を確立するための
MongoClient
クラスのインスタンスを作成します。次の複合句を使用して、コレクションをクエリします。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 {'$search': { 9 'index': 'default', 10 'compound': { 11 'filter': [{'range': {'path': 'year', 'gte': 2013, 'lte': 2015}}], 12 'should': [{'text': {'query': 'snow', 'path': 'title', 'score': {'constant': {'value': 5}}}}]}, 13 'highlight': {'path': 'title'}}}, 14 {'$limit': 10}, 15 {'$project': {'_id': 0, 'title': 1, 'year': 1, 16 'score': {'$meta': 'searchScore'}, "highlights": {"$meta": "searchHighlights"}}} 17 ] 18 19 # run pipeline 20 result = client['sample_mflix']['movies'].aggregate(pipeline) 21 22 # print results 23 for i in result: 24 print(i) サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。次のコマンドを実行して、コレクションをクエリします。
python compound-constant-query.py {'highlights': [{'path': 'title', 'score': 1.382846713066101, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' in Paradise'}]}], 'year': 2014, 'score': 5.0, 'title': 'Snow in Paradise'} {'highlights': [{'path': 'title', 'score': 1.3924485445022583, 'texts': [{'type': 'text', 'value': 'Dead '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' 2: Red vs. '}]}], 'year': 2014, 'score': 5.0, 'title': 'Dead Snow 2: Red vs. Dead'} {'highlights': [{'path': 'title', 'score': 1.3525336980819702, 'texts': [{'type': 'text', 'value': 'The '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' White Murder Case'}]}], 'year': 2014, 'score': 5.0, 'title': 'The Snow White Murder Case'} {'highlights': [{'path': 'title', 'score': 1.3766303062438965, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' on the Blades'}]}], 'year': 2014, 'score': 5.0, 'title': 'Snow on the Blades'} {'highlights': [], 'title': 'The Secret Life of Walter Mitty', 'score': 0.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 0.0, 'title': 'Jurassic World'} {'highlights': [], 'year': 2014, 'score': 0.0, 'title': 'Action Jackson'} {'highlights': [], 'title': 'In Secret', 'score': 0.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 0.0, 'title': 'The Stanford Prison Experiment'} {'highlights': [], 'title': 'The Giver', 'score': 0.0, 'year': 2014} 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、constant
オプションを使用して、クエリ タームsnow
のスコアも変更します。
boost
オプションを使用してスコアを変更する Atlas Search 複合クエリを実行します。
compound-boost-query.py
という名前のファイルを作成します。コード例をコピーして、
compound-boost-query.py
ファイルに貼り付けます。次のコード例では、次を行います。
pymongo
、MongoDB の Python ドライバー、およびDNSシード リスト接続文字列を使用してpymongo
をAtlas
に接続するために必要なdns
モジュールをインポートします。Atlas クラスターへの接続を確立するための
MongoClient
クラスのインスタンスを作成します。カーソルを反復処理して、クエリに一致するドキュメントを出力します。
クエリは、次のパイプライン ステージを使用します。
$search
ステージを使用して、コレクションをクエリします。 クエリでは以下の操作が実行されます。次の
compound
演算子句を使用します。must
句を範囲演算子とともに使用すると、2013
から2015
年の間の映画が検索されます。should
句をテキスト演算子とともに使用して、title
フィールド内のsnow
というタームをクエリし、boost
オプションを使用してscore
を変更します。boost
オプションは、検索タームの結果の基本スコアに2
を乗じます。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。
出力を10の結果に制限する$limitステージ
$projectステージから次の操作へ。
title
とyear
を除くすべてのフィールドを除外score
とhighlights
という名前の 2 つのフィールドを追加します
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 {'$search': { 9 'index': 'default', 10 'compound': { 11 'must': [{'range': {'path': 'year', 'gte': 2013, 'lte': 2015}}], 12 'should': [{'text': {'query': 'snow', 'path': 'title', 'score': {'boost': {'value': 2}}}}]}, 13 'highlight': {'path': 'title'}}}, 14 {'$limit': 10}, 15 {'$project': {'_id': 0, 'title': 1, 'year': 1, 'score': {'$meta': 'searchScore'}, "highlights": {"$meta": "searchHighlights"}}} 16 ] 17 18 # run pipeline 19 result = client['sample_mflix']['movies'].aggregate(pipeline) 20 21 # print results 22 for i in result: 23 print(i) クエリは、次のパイプライン ステージを使用します。
コレクションをクエリするには、
$search
ステージを使用します。 クエリでは、次のcompound
演算子句をboost
オプションとともに使用して、一部のフィールドを他のフィールドよりも優先してください。must
句をテキスト演算子とともに使用すると、ジャンルcomedy
が最も優先度が高く、その後にtitle
フィールドの用語snow
が優先されます。boost
オプションはフィールドに重みを適用します。should
句を範囲演算子とともに使用すると、2013
から2015
年の間の映画が検索されます。
注意
boost
オプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。$limit
ステージを使用して、出力を10
の結果に制限します。$project
stageを次のように設定します。すべてのフィールドを除外
title
、year
、genres
次のフィールドを追加:
score
import pymongo import dns client = pymongo.MongoClient('<connection-string>') result = client['sample_mflix']['movies'].aggregate([ { '$search': { 'index': 'default', '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' } } } ]) for i in result: print(i) サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。次のコマンドを実行して、コレクションをクエリします。
python compound-boost-query.py {'highlights': [{'path': 'title', 'score': 1.382846713066101, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' in Paradise'}]}], 'year': 2014, 'score': 6.7722930908203125, 'title': 'Snow in Paradise'} {'highlights': [{'path': 'title', 'score': 1.3766303062438965, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' on the Blades'}]}], 'year': 2014, 'score': 6.063445568084717, 'title': 'Snow on the Blades'} {'highlights': [{'path': 'title', 'score': 1.3525336980819702, 'texts': [{'type': 'text', 'value': 'The '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' White Murder Case'}]}], 'year': 2014, 'score': 5.509652137756348, 'title': 'The Snow White Murder Case'} {'highlights': [{'path': 'title', 'score': 1.3924485445022583, 'texts': [{'type': 'text', 'value': 'Dead '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' 2: Red vs. '}]}], 'year': 2014, 'score': 5.065053939819336, 'title': 'Dead Snow 2: Red vs. Dead'} {'highlights': [], 'title': 'The Secret Life of Walter Mitty', 'score': 1.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'Jurassic World'} {'highlights': [], 'year': 2014, 'score': 1.0, 'title': 'Action Jackson'} {'highlights': [], 'title': 'In Secret', 'score': 1.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'The Stanford Prison Experiment'} {'highlights': [], 'title': 'The Giver', 'score': 1.0, 'year': 2014} 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、boost
オプションを使用して、クエリ タームsnow
のスコアも変更します。python compound-boost-query.py { '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 複合クエリを実行します。
compound-function-query.py
という名前のファイルを作成します。コード例をコピーして、
compound-function-query.py
ファイルに貼り付けます。次のコード例では、次を行います。
pymongo
、MongoDB の Python ドライバー、およびDNSシード リスト接続文字列を使用してpymongo
をAtlas
に接続するために必要なdns
モジュールをインポートします。Atlas クラスターへの接続を確立するための
MongoClient
クラスのインスタンスを作成します。次の複合句を使用して、コレクションをクエリします。
クエリに一致する
title
フィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、type: 'hit'
で指定された一致するテキストと、type: 'text'
で指定された連続したテキストが含まれます。次のパイプライン ステージを使用します。
カーソルを反復処理して、クエリに一致するドキュメントを出力します。
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 {'$search': { 9 'index': 'default', 10 'compound': { 11 'must': [{'range': {'path': 'year', 'gte': 2013, 'lte': 2015}}], 12 'should': [{'text': {'query': 'snow', 'path': 'title', 13 'score': {'function': { 14 'add': [{'path': {'value': 'imdb.rating','undefined': 2}}, {'score': 'relevance'}]}}}}]}, 15 'highlight': {'path': 'title'}}}, 16 {'$limit': 10}, 17 {'$project': {'_id': 0, 'title': 1, 'year': 1, 'score': {'$meta': 'searchScore'}, "highlights": {"$meta": "searchHighlights"}}} 18 ] 19 20 # run pipeline 21 result = client['sample_mflix']['movies'].aggregate(pipeline) 22 23 # print results 24 for i in result: 25 print(i) サンプルを実行する前に、
<connection-string>
をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。次のコマンドを実行して、コレクションをクエリします。
python compound-function-query.py {'highlights': [{'path': 'title', 'score': 1.3525336980819702, 'texts': [{'type': 'text', 'value': 'The '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' White Murder Case'}]}], 'year': 2014, 'score': 10.454826354980469, 'title': 'The Snow White Murder Case'} {'highlights': [{'path': 'title', 'score': 1.3766303062438965, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' on the Blades'}]}], 'year': 2014, 'score': 10.3317232131958, 'title': 'Snow on the Blades'} {'highlights': [{'path': 'title', 'score': 1.3924485445022583, 'texts': [{'type': 'text', 'value': 'Dead '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' 2: Red vs. '}]}], 'year': 2014, 'score': 10.032526969909668, 'title': 'Dead Snow 2: Red vs. Dead'} {'highlights': [{'path': 'title', 'score': 1.382846713066101, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' in Paradise'}]}], 'year': 2014, 'score': 8.386146545410156, 'title': 'Snow in Paradise'} {'highlights': [], 'title': 'The Secret Life of Walter Mitty', 'score': 1.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'Jurassic World'} {'highlights': [], 'year': 2014, 'score': 1.0, 'title': 'Action Jackson'} {'highlights': [], 'title': 'In Secret', 'score': 1.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'The Stanford Prison Experiment'} {'highlights': [], 'title': 'The Giver', 'score': 1.0, 'year': 2014} 結果の最初の 4 つのドキュメントは、クエリの
should
句によって、タイトルがsnow
を持つドキュメントの優先順位が指定されているため、スコアが高くなります。should
句は、function
オプションを使用して、クエリ タームsnow
のスコアも変更します。
次のサンプルクエリでは、sample_mflix.movies
名前空間の title
、plot
、genres
フィールドを使用して次の検索を実行します。
「ghost」という単語を含むすべての映画を検索しますが、コマンドライン映画のスコアを50 % 減らします
「ghost」という単語を含むすべての映画を検索しますが、
ObjectIds
が指定された映画のスコアを 50% ずつ減らします。
movies
コレクションに対して compound
演算子を使用して AtlasSearch クエリを実行します。
次のクエリをコピーして、 Query Editorに貼り付けます。
クエリは、
$search
compound
演算子should
句を使用して、次のアクションを実行するcompound
演算子クエリをネストします。プロットまたはタイトルに
ghost
というタームが含まれ(must
句)、かつcomedy
ジャンルではない映画を検索します(mustNot
句)。プロットまたはタイトルに
ghost
というタームが含まれている映画を検索します(must
句)が、comedy
ジャンルの映画について( 500.5
boost
スコアを減らしますタイトルまたはプロットのghost
というターム。
1 [ 2 { 3 "$search": { 4 "index": "default", 5 "compound": { 6 "should":[ { 7 "compound":{ 8 "must":[ 9 { 10 "text": { 11 "query": "ghost", 12 "path": ["plot","title"] 13 } 14 } 15 ], 16 "mustNot":[ 17 { 18 "text": { 19 "query": "Comedy", 20 "path": ["genres"] 21 } 22 } 23 ] 24 } 25 }, 26 { 27 "compound":{ 28 "must":[ 29 { 30 "text": { 31 "query": "ghost", 32 "path": ["plot","title"] 33 } 34 } 35 ], 36 "filter":[ 37 { 38 "text": { 39 "query": "Comedy", 40 "path": ["genres"] 41 } 42 } 43 ], 44 "score":{ "boost": { "value": 0.5} } 45 } 46 } 47 ] 48 } 49 } 50 } 51 ] クエリは、
$search
compound
演算子should
句を使用して、次のアクションを実行するcompound
演算子クエリをネストします。プロットまたはタイトルに
ghost
というタームが含まれ、かつ指定された ObjectId がない映画を検索します(must
mustNot
句)。プロットまたはタイトルに
ghost
というタームが含まれている映画を検索します(must
句)が、指定された ObjectId( 句)スコアを50 %(0.5
boost
減らしますfilter
句)。
1 [ 2 { 3 "$search": { 4 "index": "default", 5 "compound": { 6 "should":[ 7 { 8 "compound":{ 9 "must":[ 10 { 11 "text": { 12 "query": "ghost", 13 "path": ["plot","title"] 14 } 15 } 16 ], 17 "mustNot":[ 18 { 19 "in": { 20 "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')], 21 "path": "_id" 22 } 23 } 24 ] 25 } 26 }, 27 { 28 "compound":{ 29 "must":[ 30 { 31 "text": { 32 "query": "ghost", 33 "path": ["plot","title"] 34 } 35 } 36 ], 37 "filter":[ 38 { 39 "in": { 40 "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')], 41 "path": "_id" 42 } 43 } 44 ], 45 "score":{ "boost": { "value": 0.5} } 46 } 47 } 48 ] 49 } 50 } 51 } 52 ] Query EditorでSearchボタンをクリックします。
1 SCORE: 5.909613132476807 2 _id: “573a139af29313caabcefcce” 3 plot: "Adaption of the famous Oscar Wilde tale about a young American girl th…" 4 genres: Array (3) 5 runtime: 92 6 7 SCORE: 5.367666244506836 8 _id: “573a13d8f29313caabda5dc1” 9 plot: "The Little Ghost lives in the castle over looking a small town and awa…" 10 genres: Array (2) 11 runtime: 92 12 13 SCORE: 4.676314353942871 14 _id: “573a13c0f29313caabd6139d” 15 plot: "Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal …" 16 genres: Array (2) 17 runtime: 107 18 19 SCORE: 3.9638845920562744 20 _id: “573a1398f29313caabcebf6f” 21 plot: "After an accident leaves a young man dead, his spirit stays behind to …" 22 genres: Array (3) 23 runtime: 127 24 25 SCORE: 3.9638845920562744 26 _id: “573a13cdf29313caabd83c08” 27 plot: "A man tries to solve his lover's murder by communicating with her spir…" 28 genres: Array (3) 29 runtime: 115 30 31 SCORE: 3.9638845920562744 32 _id: “573a13cef29313caabd873a2” 33 plot: "A man tries to solve his lover's murder by communicating with her spir…" 34 genres: Array (3) 35 runtime: 115 36 37 SCORE: 3.526711940765381 38 _id: “573a13c3f29313caabd6a149” 39 plot: "What kind of scenes in a horror film scares you the most? When a ghost…" 40 genres: Array (2) 41 runtime: 95 42 43 SCORE: 3.3177831172943115 44 _id: “573a1397f29313caabce7ea1” 45 plot: "Four successful elderly gentlemen, members of the Chowder Society, sha…" 46 genres: Array (3) 47 runtime: 110 48 49 SCORE: 3.3177831172943115 50 _id: “573a13a4f29313caabd117df” 51 fullplot: "When the motorcyclist Johnny Blaze finds that his father Barton Blaze …" 52 imdb: Object 53 year: 2007 54 55 SCORE: 3.3177831172943115 56 _id: “573a13a6f29313caabd185dc” 57 fullplot: "After discovering a passenger ship missing since 1962 floating adrift …" 58 imdb: Object 59 year: 2002 結果内の映画ドキュメントの
ghost
plot
title
Comedy
フィールドまたは フィールドにクエリ用語 が含まれており、 ジャンルではありません。Atlas Search では、Comedy
フィールドまたはghost
plot
title
フィールドに10 というタームを含む50 ジャンルのドキュメントは返されませんでした。それらのドキュメントは上位の ドキュメントにランク付けされなかったためです。これらのドキュメントは % によって選出されます。1 SCORE: 5.909613132476807 2 _id: “573a139af29313caabcefcce” 3 plot: "Adaption of the famous Oscar Wilde tale about a young American girl th…" 4 genres: Array (3) 5 runtime: 92 6 7 SCORE: 5.367666244506836 8 _id: “573a13d8f29313caabda5dc1” 9 plot: "The Little Ghost lives in the castle over looking a small town and awa…" 10 genres: Array (2) 11 runtime: 92 12 13 SCORE: 4.676314353942871 14 _id: “573a13c0f29313caabd6139d” 15 plot: "Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal …" 16 genres: Array (2) 17 runtime: 107 18 19 SCORE: 3.9638845920562744 20 _id: “573a1398f29313caabcebf6f” 21 plot: "After an accident leaves a young man dead, his spirit stays behind to …" 22 genres: Array (3) 23 runtime: 127 24 25 SCORE: 3.526711940765381 26 _id: “573a13c3f29313caabd6a149” 27 plot: "What kind of scenes in a horror film scares you the most? When a ghost…" 28 genres:Array (2) 29 runtime: 95 30 31 SCORE: 3.5241782665252686 32 _id: “573a1398f29313caabce912c” 33 plot: "Three unemployed parapsychology professors set up shop as a unique gho…" 34 genres: Array (2) 35 runtime: 105 36 37 SCORE: 3.5241782665252686 38 _id: “573a139cf29313caabcf5a48” 39 plot: "Casper, a ghost, teams up with Wendy, a witch, against an evil warlock…" 40 genres: Array (3) 41 runtime: 90 42 43 SCORE: 3.4605300426483154 44 _id: “573a13bdf29313caabd58274” 45 plot: "Banku, his mother, Anjali Sharma and father move in to their new house…" 46 genres: Array (3) 47 runtime: 150 48 49 SCORE: 3.3177831172943115 50 _id: “573a1397f29313caabce7ea1” 51 plot: "Four successful elderly gentlemen, members of the Chowder Society, sha…" 52 genres: Array (3) 53 runtime: 110 54 55 SCORE: 3.3177831172943115 56 _id: “573a1398f29313caabcebf79” 57 plot: "Elliot Hopper is a widower with three children, he is currently workin…" 58 genres: Array (3) 59 runtime: 83 結果内の映画ドキュメントの、 フィールドまたは フィールドにクエリ用語
ghost
が含まれており、plot
title
フィールドに指定された ObjectId_id
がありません。Atlas Search では、指定された ObjectsId を含むドキュメントは、title
フィールドにクエリ用語ghost
が含まれているにもかかわらず、返されませんでした。クエリではこれらのドキュメントのスコアが50 % 減少し、これらのドキュメントは次のようになります上位の10ドキュメントにはランク付けされていない
mongosh
内のクラスターに接続します。
ターミナル ウィンドウでmongosh
を開き、クラスターに接続します。 接続の詳細な手順については、「 mongosh
経由での接続 」を参照してください。
movies
コレクションに対して次の compound
Atlas Search 演算子クエリを実行します。
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "index": "default", 5 "compound": { 6 "should": [ 7 { 8 "compound":{ 9 "must": [ 10 { 11 "text": { 12 "query": "ghost", 13 "path": ["plot","title"] 14 } 15 } 16 ], 17 "mustNot": [ 18 { 19 "text": { 20 "query": "Comedy", 21 "path": ["genres"] 22 } 23 } 24 ] 25 } 26 }, 27 { 28 "compound":{ 29 "must":[ 30 { 31 "text": { 32 "query": "ghost", 33 "path": ["plot","title"] 34 } 35 } 36 ], 37 "filter": [ 38 { 39 "text": { 40 "query": "Comedy", 41 "path": ["genres"] 42 } 43 } 44 ], 45 "score": { "boost": { "value": 0.5} } 46 } 47 } 48 ] 49 } 50 } 51 }, 52 { 53 "$limit": 10 54 }, 55 { 56 "$project": { 57 "_id": 1, 58 "title": 1, 59 "plot": 1, 60 "genres": 1, 61 "score": { "$meta": "searchScore" } 62 } 63 } 64 ])
1 [ 2 { 3 _id: ObjectId('573a139af29313caabcefcce'), 4 plot: 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.', 5 genres: [ 'Family', 'Drama', 'Fantasy' ], 6 title: 'The Canterville Ghost', 7 score: 5.909613132476807 8 }, 9 { 10 _id: ObjectId('573a13d8f29313caabda5dc1'), 11 plot: 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!', 12 genres: [ 'Family', 'Fantasy' ], 13 title: 'The Little Ghost', 14 score: 5.367666244506836 15 }, 16 { 17 _id: ObjectId('573a13c0f29313caabd6139d'), 18 plot: 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.', 19 genres: [ 'Horror', 'Thriller' ], 20 title: 'Death of a Ghost Hunter', 21 score: 4.676314353942871 22 }, 23 { 24 _id: ObjectId('573a1398f29313caabcebf6f'), 25 plot: 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.', 26 genres: [ 'Drama', 'Fantasy', 'Romance' ], 27 title: 'Ghost', 28 score: 3.9638845920562744 29 }, 30 { 31 _id: ObjectId('573a13cdf29313caabd83c08'), 32 plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", 33 genres: [ 'Drama', 'Fantasy', 'Mystery' ], 34 title: 'Ghost', 35 score: 3.9638845920562744 36 }, 37 { 38 _id: ObjectId('573a13cef29313caabd873a2'), 39 plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", 40 genres: [ 'Drama', 'Fantasy', 'Mystery' ], 41 title: 'Ghost', 42 score: 3.9638845920562744 43 }, 44 { 45 _id: ObjectId('573a13c3f29313caabd6a149'), 46 plot: 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...', 47 genres: [ 'Horror', 'Thriller' ], 48 title: 'Coming Soon', 49 score: 3.526711940765381 50 }, 51 { 52 _id: ObjectId('573a1397f29313caabce7ea1'), 53 plot: "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", 54 genres: [ 'Drama', 'Horror', 'Thriller' ], 55 title: 'Ghost Story', 56 score: 3.3177831172943115 57 }, 58 { 59 _id: ObjectId('573a13a4f29313caabd117df'), 60 plot: 'Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.', 61 genres: [ 'Action', 'Fantasy', 'Thriller' ], 62 title: 'Ghost Rider', 63 score: 3.3177831172943115 64 }, 65 { 66 _id: ObjectId('573a13a6f29313caabd185dc'), 67 plot: 'A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...', 68 genres: [ 'Horror', 'Mystery' ], 69 title: 'Ghost Ship', 70 score: 3.3177831172943115 71 } 72 ]
結果内の映画ドキュメントのghost
plot
title
Comedy
フィールドまたは フィールドにクエリ用語 が含まれており、 ジャンルではありません。Atlas Search では、Comedy
フィールドまたはghost
plot
title
フィールドに10 というタームを含む50 ジャンルのドキュメントは返されませんでした。それらのドキュメントは上位の ドキュメントにランク付けされなかったためです。これらのドキュメントは % によって選出されます。
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 db.movies.aggregate([ 2 { 3 "$search": { 4 "compound": { 5 "index": "default", 6 "should": [ 7 { 8 "compound": { 9 "must": [ 10 { 11 "text": { 12 "query": "ghost", 13 "path": ["plot","title"] 14 } 15 } 16 ], 17 "mustNot": [ 18 { 19 "in": { 20 "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')], 21 "path": "_id" 22 } 23 } 24 ] 25 } 26 }, 27 { 28 "compound": { 29 "must": [ 30 { 31 "text": { 32 "query": "ghost", 33 "path": ["plot","title"] 34 } 35 } 36 ], 37 "filter": [ 38 { 39 "in": { 40 "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')], 41 "path": "_id" 42 } 43 } 44 ], 45 "score": { "boost": { "value": 0.5} } 46 } 47 } 48 ] 49 } 50 } 51 }, 52 { 53 "$limit": 10 54 }, 55 { 56 "$project": { 57 "_id": 1, 58 "title": 1, 59 "plot": 1, 60 "score": { "$meta": "searchScore" } 61 } 62 } 63 ])
1 [ 2 { 3 _id: ObjectId('573a139af29313caabcefcce'), 4 plot: 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.', 5 genres: [ 'Family', 'Drama', 'Fantasy' ], 6 title: 'The Canterville Ghost', 7 score: 5.909613132476807 8 }, 9 { 10 _id: ObjectId('573a13d8f29313caabda5dc1'), 11 plot: 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!', 12 genres: [ 'Family', 'Fantasy' ], 13 title: 'The Little Ghost', 14 score: 5.367666244506836 15 }, 16 { 17 _id: ObjectId('573a13c0f29313caabd6139d'), 18 plot: 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.', 19 genres: [ 'Horror', 'Thriller' ], 20 title: 'Death of a Ghost Hunter', 21 score: 4.676314353942871 22 }, 23 { 24 _id: ObjectId('573a1398f29313caabcebf6f'), 25 plot: 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.', 26 genres: [ 'Drama', 'Fantasy', 'Romance' ], 27 title: 'Ghost', 28 score: 3.9638845920562744 29 }, 30 { 31 _id: ObjectId('573a13c3f29313caabd6a149'), 32 plot: 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...', 33 genres: [ 'Horror', 'Thriller' ], 34 title: 'Coming Soon', 35 score: 3.526711940765381 36 }, 37 { 38 _id: ObjectId('573a1398f29313caabce912c'), 39 plot: 'Three unemployed parapsychology professors set up shop as a unique ghost removal service.', 40 genres: [ 'Comedy', 'Fantasy' ], 41 title: 'Ghostbusters', 42 score: 3.5241782665252686 43 }, 44 { 45 _id: ObjectId('573a139cf29313caabcf5a48'), 46 plot: 'Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.', 47 genres: [ 'Adventure', 'Comedy', 'Family' ], 48 title: 'Casper Meets Wendy', 49 score: 3.5241782665252686 50 }, 51 { 52 _id: ObjectId('573a13bdf29313caabd58274'), 53 plot: 'Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...', 54 genres: [ 'Comedy', 'Drama', 'Fantasy' ], 55 title: 'Bhoothnath', 56 score: 3.4605300426483154 57 }, 58 { 59 _id: ObjectId('573a1397f29313caabce7ea1'), 60 plot: "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", 61 genres: [ 'Drama', 'Horror', 'Thriller' ], 62 title: 'Ghost Story', 63 score: 3.3177831172943115 64 }, 65 { 66 _id: ObjectId('573a1398f29313caabcebf79'), 67 plot: 'Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...', 68 genres: [ 'Comedy', 'Family', 'Fantasy' ], 69 title: 'Ghost Dad', 70 score: 3.3177831172943115 71 } 72 ]
結果内の映画ドキュメントの、 フィールドまたは フィールドにクエリ用語ghost
が含まれており、plot
title
フィールドに指定された ObjectId_id
がありません。Atlas Search では、指定された ObjectsId を含むドキュメントは、 title
フィールドにクエリ用語ghost
が含まれているにもかかわらず、返されませんでした。クエリではこれらのドキュメントのスコアが50 % 減少し、これらのドキュメントは次のようになります上位の10ドキュメントにはランク付けされていない
MongoDB Compass のクラスターに接続します。
MongoDB Compass を開き、クラスターに接続します。 接続の詳細な手順については、「 Compass 経由での接続 」を参照してください。
movies
コレクションに対して、以下のAtlas Search クエリを実行します。
このクエリでは、次のパイプライン ステージを使用します。
このクエリでは、次のパイプライン ステージを使用します。
このクエリを実行するには、MongoDB Compass で次の手順を実行します。
[Aggregations] タブをクリックします。
Select...をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプライン ステージを構成します。
Tip
ステージを追加するには、 Add Stageをクリックします。
パイプラインステージクエリ$search
{ "index": "default", "compound": { "should": [ { "compound":{ "must": [ { "text": { "query": "ghost", "path": ["plot","title"] } } ], "mustNot": [ { "text": { "query": "Comedy", "path": ["genres"] } } ] } }, { "compound":{ "must":[ { "text": { "query": "ghost", "path": ["plot","title"] } } ], "filter": [ { "text": { "query": "Comedy", "path": ["genres"] } } ], "score": { "boost": { "value": 0.5} } } } ] } } $limit
10 $project
{ "_id": 1, "title": 1, "plot": 1, "genres": 1, "score": { "$meta": "searchScore" } } Auto Previewを有効にした場合、MongoDB Compass は
$project
パイプライン ステージの横に次のドキュメントを表示します。1 _id: ObjectId('573a139af29313caabcefcce'), 2 plot: 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.', 3 genres: [ 'Family', 'Drama', 'Fantasy' ], 4 title: 'The Canterville Ghost', 5 score: 5.909613132476807 6 7 _id: ObjectId('573a13d8f29313caabda5dc1'), 8 plot: 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!', 9 genres: [ 'Family', 'Fantasy' ], 10 title: 'The Little Ghost', 11 score: 5.367666244506836 12 13 _id: ObjectId('573a13c0f29313caabd6139d'), 14 plot: 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.', 15 genres: [ 'Horror', 'Thriller' ], 16 title: 'Death of a Ghost Hunter', 17 score: 4.676314353942871 18 19 _id: ObjectId('573a1398f29313caabcebf6f'), 20 plot: 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.', 21 genres: [ 'Drama', 'Fantasy', 'Romance' ], 22 title: 'Ghost', 23 score: 3.9638845920562744 24 25 _id: ObjectId('573a13cdf29313caabd83c08'), 26 plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", 27 genres: [ 'Drama', 'Fantasy', 'Mystery' ], 28 title: 'Ghost', 29 score: 3.9638845920562744 30 31 _id: ObjectId('573a13cef29313caabd873a2'), 32 plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", 33 genres: [ 'Drama', 'Fantasy', 'Mystery' ], 34 title: 'Ghost', 35 score: 3.9638845920562744 36 37 _id: ObjectId('573a13c3f29313caabd6a149'), 38 plot: 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...', 39 genres: [ 'Horror', 'Thriller' ], 40 title: 'Coming Soon', 41 score: 3.526711940765381 42 43 _id: ObjectId('573a1397f29313caabce7ea1'), 44 plot: "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", 45 genres: [ 'Drama', 'Horror', 'Thriller' ], 46 title: 'Ghost Story', 47 score: 3.3177831172943115 48 49 _id: ObjectId('573a13a4f29313caabd117df'), 50 plot: 'Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.', 51 genres: [ 'Action', 'Fantasy', 'Thriller' ], 52 title: 'Ghost Rider', 53 score: 3.3177831172943115 54 55 _id: ObjectId('573a13a6f29313caabd185dc'), 56 plot: 'A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...', 57 genres: [ 'Horror', 'Mystery' ], 58 title: 'Ghost Ship', 59 score: 3.3177831172943115 結果内の映画ドキュメントの
ghost
plot
title
Comedy
フィールドまたは フィールドにクエリ用語 が含まれており、 ジャンルではありません。Atlas Search では、Comedy
フィールドまたはghost
plot
title
フィールドに10 というタームを含む50 ジャンルのドキュメントは返されませんでした。それらのドキュメントは上位の ドキュメントにランク付けされなかったためです。これらのドキュメントは % によって選出されます。パイプラインステージクエリ$search
{ "index": "default", "compound": { "should": [ { "compound":{ "must": [ { "text": { "query": "ghost", "path": ["plot","title"] } } ], "mustNot": [ { "in": { "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')], "path": "_id" } } ] } }, { "compound":{ "must":[ { "text": { "query": "ghost", "path": ["plot","title"] } } ], "filter": [ { "in": { "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')], "path": "_id" } } ], "score": { "boost": { "value": 0.5} } } } ] } } $limit
10 $project
{ "_id": 1, "title": 1, "plot": 1, "score": { "$meta": "searchScore" } } Auto Previewを有効にした場合、MongoDB Compass は
$project
パイプライン ステージの横に次のドキュメントを表示します。1 _id: ObjectId('573a139af29313caabcefcce'), 2 plot: 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.', 3 title: 'The Canterville Ghost', 4 score: 5.909613132476807 5 6 _id: ObjectId('573a13d8f29313caabda5dc1'), 7 plot: 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!', 8 title: 'The Little Ghost', 9 score: 5.367666244506836 10 11 _id: ObjectId('573a13c0f29313caabd6139d'), 12 plot: 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.', 13 title: 'Death of a Ghost Hunter', 14 score: 4.676314353942871 15 16 _id: ObjectId('573a1398f29313caabcebf6f'), 17 plot: 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.', 18 title: 'Ghost', 19 score: 3.9638845920562744 20 21 _id: ObjectId('573a13c3f29313caabd6a149'), 22 plot: 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...', 23 title: 'Coming Soon', 24 score: 3.526711940765381 25 26 _id: ObjectId('573a1398f29313caabce912c'), 27 plot: 'Three unemployed parapsychology professors set up shop as a unique ghost removal service.', 28 title: 'Ghostbusters', 29 score: 3.5241782665252686 30 31 _id: ObjectId('573a139cf29313caabcf5a48'), 32 plot: 'Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.', 33 title: 'Casper Meets Wendy', 34 score: 3.5241782665252686 35 36 _id: ObjectId('573a13bdf29313caabd58274'), 37 plot: 'Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...', 38 title: 'Bhoothnath', 39 score: 3.4605300426483154 40 41 _id: ObjectId('573a1397f29313caabce7ea1'), 42 plot: "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", 43 title: 'Ghost Story', 44 score: 3.3177831172943115 45 46 _id: ObjectId('573a1398f29313caabcebf79'), 47 plot: 'Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...', 48 title: 'Ghost Dad', 49 score: 3.3177831172943115 結果内の映画ドキュメントの、 フィールドまたは フィールドにクエリ用語
ghost
が含まれており、plot
title
フィールドに指定された ObjectId_id
がありません。Atlas Search では、指定された ObjectsId を含むドキュメントは、title
フィールドにクエリ用語ghost
が含まれているにもかかわらず、返されませんでした。クエリではこれらのドキュメントのスコアが50 % 減少し、これらのドキュメントは次のようになります上位の10ドキュメントにはランク付けされていない
クエリをコピーして Program.cs
ファイルに貼り付けます。
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
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 BuryGenreCompoundExample 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 .Should(Builders<MovieDocument>.Search.Compound() 26 .Must(Builders<MovieDocument>.Search.Text( 27 Builders<MovieDocument>.SearchPath.Multi(movie => movie.Title, movie => movie.Plot), "ghost")) 28 .MustNot(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Comedy")) 29 ) 30 .Should(Builders<MovieDocument>.Search.Compound() 31 .Must(Builders<MovieDocument>.Search.Text( 32 Builders<MovieDocument>.SearchPath.Multi(movie => movie.Title, movie => movie.Plot), "ghost")) 33 .Filter(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Comedy", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(0.5))) 34 ), 35 indexName: "default") 36 .Project<MovieDocument>(Builders<MovieDocument>.Projection 37 .Include(movie => movie.Plot) 38 .Include(movie => movie.Title) 39 .Include(movie => movie.Id) 40 .Include(movie => movie.Genres) 41 .MetaSearchScore("score")) 42 .Limit(10) 43 .ToList(); 44 45 // print results 46 foreach (var movie in results) 47 { 48 Console.WriteLine(movie.ToJson()); 49 } 50 } 51 } 52 53 [ ]54 public class MovieDocument 55 { 56 [ ]57 public ObjectId Id { get; set; } 58 public string Plot { get; set; } 59 public string Title { get; set; } 60 public string[] Genres { get; set; } 61 public double Score { get; set; } 62 }
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
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 BuryDocumentCompoundExample 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 string id1 = "573a13cef29313caabd873a2"; 23 string id2 = "573a13cdf29313caabd83c08"; 24 25 // define and run pipeline 26 var results = moviesCollection.Aggregate() 27 .Search(Builders<MovieDocument>.Search.Compound() 28 .Should(Builders<MovieDocument>.Search.Compound() 29 .Must(Builders<MovieDocument>.Search.Text( 30 Builders<MovieDocument>.SearchPath.Multi(movie => movie.Title, movie => movie.Plot), "ghost")) 31 .MustNot(Builders<MovieDocument>.Search.In(movie => movie.Id, new[] {ObjectId.Parse(id1), ObjectId.Parse(id2)})) 32 ) 33 .Should(Builders<MovieDocument>.Search.Compound() 34 .Must(Builders<MovieDocument>.Search.Text( 35 Builders<MovieDocument>.SearchPath.Multi(movie => movie.Title, movie => movie.Plot), "ghost")) 36 .Filter(Builders<MovieDocument>.Search.In(movie => movie.Id, new[] {ObjectId.Parse(id1), ObjectId.Parse(id2)}, score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(0.5))) 37 ), 38 indexName: "default") 39 .Project<MovieDocument>(Builders<MovieDocument>.Projection 40 .Include(movie => movie.Plot) 41 .Include(movie => movie.Title) 42 .Include(movie => movie.Id) 43 .MetaSearchScore("score")) 44 .Limit(10) 45 .ToList(); 46 47 // print results 48 foreach (var movie in results) 49 { 50 Console.WriteLine(movie.ToJson()); 51 } 52 } 53 } 54 55 [ ]56 public class MovieDocument 57 { 58 [ ]59 public ObjectId Id { get; set; } 60 public string Plot { get; set; } 61 public string Title { get; set; } 62 public double Score { get; set; } 63 }
クエリ内の <connection-string>
を置き換え、ファイルを保存します。
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
Program.cs
ファイルをコンパイルして実行します。
dotnet run compound-bury-results.csproj
{ "_id" : ObjectId("573a139af29313caabcefcce"), "plot" : "Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.", "title" : "The Canterville Ghost", "genres" : ["Family", "Drama", "Fantasy"], "score" : 5.9096131324768066 } { "_id" : ObjectId("573a13d8f29313caabda5dc1"), "plot" : "The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!", "title" : "The Little Ghost", "genres" : ["Family", "Fantasy"], "score" : 5.3676662445068359 } { "_id" : ObjectId("573a13c0f29313caabd6139d"), "plot" : "Renowned \"ghost hunter\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.", "title" : "Death of a Ghost Hunter", "genres" : ["Horror", "Thriller"], "score" : 4.6763143539428711 } { "_id" : ObjectId("573a1398f29313caabcebf6f"), "plot" : "After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.", "title" : "Ghost", "genres" : ["Drama", "Fantasy", "Romance"], "score" : 3.9638845920562744 } { "_id" : ObjectId("573a13cdf29313caabd83c08"), "plot" : "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "title" : "Ghost", "genres" : ["Drama", "Fantasy", "Mystery"], "score" : 3.9638845920562744 } { "_id" : ObjectId("573a13cef29313caabd873a2"), "plot" : "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "title" : "Ghost", "genres" : ["Drama", "Fantasy", "Mystery"], "score" : 3.9638845920562744 } { "_id" : ObjectId("573a13c3f29313caabd6a149"), "plot" : "What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...", "title" : "Coming Soon", "genres" : ["Horror", "Thriller"], "score" : 3.5267119407653809 } { "_id" : ObjectId("573a1398f29313caabce912c"), "plot" : "Three unemployed parapsychology professors set up shop as a unique ghost removal service.", "title" : "Ghostbusters", "genres" : ["Comedy", "Fantasy"], "score" : 3.5241782665252686 } { "_id" : ObjectId("573a139cf29313caabcf5a48"), "plot" : "Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.", "title" : "Casper Meets Wendy", "genres" : ["Adventure", "Comedy", "Family"], "score" : 3.5241782665252686 } { "_id" : ObjectId("573a13bdf29313caabd58274"), "plot" : "Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...", "title" : "Bhoothnath", "genres" : ["Comedy", "Drama", "Fantasy"], "score" : 3.4605300426483154 }
結果内の映画ドキュメントのghost
plot
title
Comedy
フィールドまたは フィールドにクエリ用語 が含まれており、 ジャンルではありません。Atlas Search では、Comedy
フィールドまたはghost
plot
title
フィールドに10 というタームを含む50 ジャンルのドキュメントは返されませんでした。それらのドキュメントは上位の ドキュメントにランク付けされなかったためです。これらのドキュメントは % によって選出されます。
dotnet run compound-bury-results.csproj
{ "_id" : ObjectId("573a139af29313caabcefcce"), "plot" : "Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.", "title" : "The Canterville Ghost", "score" : 5.9096131324768066 } { "_id" : ObjectId("573a13d8f29313caabda5dc1"), "plot" : "The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!", "title" : "The Little Ghost", "score" : 5.3676662445068359 } { "_id" : ObjectId("573a13c0f29313caabd6139d"), "plot" : "Renowned \"ghost hunter\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.", "title" : "Death of a Ghost Hunter", "score" : 4.6763143539428711 } { "_id" : ObjectId("573a1398f29313caabcebf6f"), "plot" : "After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.", "title" : "Ghost", "score" : 3.9638845920562744 } { "_id" : ObjectId("573a13cdf29313caabd83c08"), "plot" : "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "title" : "Ghost", "score" : 3.9638845920562744 } { "_id" : ObjectId("573a13cef29313caabd873a2"), "plot" : "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "title" : "Ghost", "score" : 3.9638845920562744 } { "_id" : ObjectId("573a13c3f29313caabd6a149"), "plot" : "What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...", "title" : "Coming Soon", "score" : 3.5267119407653809 } { "_id" : ObjectId("573a1398f29313caabce912c"), "plot" : "Three unemployed parapsychology professors set up shop as a unique ghost removal service.", "title" : "Ghostbusters", "score" : 3.5241782665252686 } { "_id" : ObjectId("573a139cf29313caabcf5a48"), "plot" : "Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.", "title" : "Casper Meets Wendy", "score" : 3.5241782665252686 } { "_id" : ObjectId("573a13bdf29313caabd58274"), "plot" : "Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...", "title" : "Bhoothnath", "score" : 3.4605300426483154 }
結果内の映画ドキュメントの、 フィールドまたは フィールドにクエリ用語ghost
が含まれており、plot
title
フィールドに指定された ObjectId_id
がありません。Atlas Search では、指定された ObjectsId を含むドキュメントは、 title
フィールドにクエリ用語ghost
が含まれているにもかかわらず、返されませんでした。クエリではこれらのドキュメントのスコアが50 % 減少し、これらのドキュメントは次のようになります上位の10ドキュメントにはランク付けされていない
クエリをコピーして compound-bury-results.go
ファイルに貼り付けます。
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 // define structure of movies collection 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 plot string `bson:"Plot,omitempty"` 17 } 18 19 func main() { 20 var err error 21 // connect to the Atlas cluster and set a maximum operation time 22 ctx := context.Background() 23 opts := options.Client(). 24 SetTimeout(5 * time.Second). 25 ApplyURI("<connection-string>") 26 27 client, err := mongo.Connect(opts) 28 if err != nil { 29 panic(err) 30 } 31 defer client.Disconnect(ctx) 32 // set namespace 33 collection := client.Database("sample_mflix").Collection("movies") 34 // define pipeline 35 searchStage := bson.D{{"$search", bson.D{ 36 {"index", "default"}, 37 {"compound", bson.D{ 38 {"should", bson.A{ 39 bson.D{{"compound", bson.D{ 40 {"must", bson.A{ 41 bson.D{{"text", bson.D{ 42 {"query", "ghost"}, 43 {"path", bson.A{"plot", "title"}}, 44 }}}, 45 }}, 46 {"mustNot", bson.A{ 47 bson.D{{"text", bson.D{ 48 {"query", "Comedy"}, 49 {"path", bson.A{"genres"}}, 50 }}}, 51 }}, 52 }}}, 53 bson.D{{"compound", bson.D{ 54 {"must", bson.A{ 55 bson.D{{"text", bson.D{ 56 {"query", "ghost"}, 57 {"path", bson.A{"plot", "title"}}, 58 }}}, 59 }}, 60 {"filter", bson.A{ 61 bson.D{{"text", bson.D{ 62 {"query", "Comedy"}, 63 {"path", bson.A{"genres"}}, 64 }}}, 65 }}, 66 {"score", bson.D{{"boost", bson.D{{"value", 0.5}}}}}, 67 }}}, 68 }}, 69 }}, 70 }}} 71 limitStage := bson.D{{"$limit", 10}} 72 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 73 // run pipeline 74 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}) 75 if err != nil { 76 panic(err) 77 } 78 // print results 79 var results []bson.D 80 if err = cursor.All(context.TODO(), &results); err != nil { 81 panic(err) 82 } 83 for _, result := range results { 84 fmt.Println(result) 85 } 86 }
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "time" 8 9 "go.mongodb.org/mongo-driver/v2/bson" 10 "go.mongodb.org/mongo-driver/v2/mongo" 11 "go.mongodb.org/mongo-driver/v2/mongo/options" 12 ) 13 14 // define structure of movies collection 15 type MovieCollection struct { 16 title string `bson:"Title,omitempty"` 17 plot string `bson:"Plot,omitempty"` 18 } 19 20 func main() { 21 var err error 22 // connect to the Atlas cluster and set a maximum operation time 23 ctx := context.Background() 24 opts := options.Client(). 25 SetTimeout(5 * time.Second). 26 ApplyURI("<connection-string>") 27 28 client, err := mongo.Connect(opts) 29 if err != nil { 30 panic(err) 31 } 32 defer client.Disconnect(ctx) 33 // set namespace 34 collection := client.Database("sample_mflix").Collection("movies") 35 // define variable 36 var objectIDFromHex = func(hex string) bson.ObjectID { 37 objectID, err := bson.ObjectIDFromHex(hex) 38 if err != nil { 39 log.Fatal(err) 40 } 41 return objectID 42 } 43 // define pipeline 44 searchStage := bson.D{{"$search", bson.D{ 45 {"index", "default"}, 46 {"compound", bson.D{ 47 {"should", bson.A{ 48 bson.D{{"compound", bson.D{ 49 {"must", bson.A{ 50 bson.D{{"text", bson.D{ 51 {"query", "ghost"}, 52 {"path", bson.A{"plot", "title"}}, 53 }}}, 54 }}, 55 {"mustNot", bson.A{ 56 bson.D{{"in", bson.D{ 57 {"value", bson.A{objectIDFromHex("573a13cdf29313caabd83c08"), objectIDFromHex("573a13cef29313caabd873a2")}}, 58 {"path", "_id"}, 59 }}}, 60 }}, 61 }}}, 62 bson.D{{"compound", bson.D{ 63 {"must", bson.A{ 64 bson.D{{"text", bson.D{ 65 {"query", "ghost"}, 66 {"path", bson.A{"plot", "title"}}, 67 }}}, 68 }}, 69 {"filter", bson.A{ 70 bson.D{{"in", bson.D{ 71 {"value", bson.A{objectIDFromHex("573a13cdf29313caabd83c08"), objectIDFromHex("573a13cef29313caabd873a2")}}, 72 {"path", "_id"}, 73 }}}, 74 }}, 75 {"score", bson.D{{"boost", bson.D{{"value", 0.5}}}}}, 76 }}}, 77 }}, 78 }}, 79 }}} 80 81 limitStage := bson.D{{"$limit", 10}} 82 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 83 // run pipeline 84 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}) 85 if err != nil { 86 panic(err) 87 } 88 // print results 89 var results []bson.D 90 if err = cursor.All(context.TODO(), &results); err != nil { 91 panic(err) 92 } 93 for _, result := range results { 94 fmt.Println(result) 95 } 96 }
クエリ内の <connection-string>
を置き換え、ファイルを保存します。
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
コマンドを実行して、コレクションをクエリします。
go run compound-bury-results.go
[{plot Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.} {genres [Family Drama Fantasy]} {title The Canterville Ghost} {score 5.909613132476807}] [{plot The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!} {genres [Family Fantasy]} {title The Little Ghost} {score 5.367666244506836}] [{plot Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.} {genres [Horror Thriller]} {title Death of a Ghost Hunter} {score 4.676314353942871}] [{plot After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.} {genres [Drama Fantasy Romance]} {title Ghost} {score 3.9638845920562744}] [{plot A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.} {genres [Drama Fantasy Mystery]} {title Ghost} {score 3.9638845920562744}] [{plot A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.} {genres [Drama Fantasy Mystery]} {title Ghost} {score 3.9638845920562744}] [{plot What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...} {genres [Horror Thriller]} {title Coming Soon} {score 3.526711940765381}] [{plot Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...} {genres [Drama Horror Thriller]} {title Ghost Story} {score 3.3177831172943115}] [{plot Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.} {genres [Action Fantasy Thriller]} {title Ghost Rider} {score 3.3177831172943115}] [{plot A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...} {genres [Horror Mystery]} {title Ghost Ship} {score 3.3177831172943115}]
結果内の映画ドキュメントのghost
plot
title
Comedy
フィールドまたは フィールドにクエリ用語 が含まれており、 ジャンルではありません。Atlas Search では、Comedy
フィールドまたはghost
plot
title
フィールドに10 というタームを含む50 ジャンルのドキュメントは返されませんでした。それらのドキュメントは上位の ドキュメントにランク付けされなかったためです。これらのドキュメントは % によって選出されます。
go run compound-bury-results.go
[{plot Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.} {title The Canterville Ghost} {score 5.909613132476807}] [{plot The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!} {title The Little Ghost} {score 5.367666244506836}] [{plot Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.} {title Death of a Ghost Hunter} {score 4.676314353942871}] [{plot After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.} {title Ghost} {score 3.9638845920562744}] [{plot What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...} {title Coming Soon} {score 3.526711940765381}] [{plot Three unemployed parapsychology professors set up shop as a unique ghost removal service.} {title Ghostbusters} {score 3.5241782665252686}] [{plot Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.} {title Casper Meets Wendy} {score 3.5241782665252686}] [{plot Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...} {title Bhoothnath} {score 3.4605300426483154}] [{plot Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...} {title Ghost Story} {score 3.3177831172943115}] [{plot Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...} {title Ghost Dad} {score 3.3177831172943115}]
結果内の映画ドキュメントの、 フィールドまたは フィールドにクエリ用語ghost
が含まれており、plot
title
フィールドに指定された ObjectId_id
がありません。Atlas Search では、指定された ObjectsId を含むドキュメントは、 title
フィールドにクエリ用語ghost
が含まれているにもかかわらず、返されませんでした。クエリではこれらのドキュメントのスコアが50 % 減少し、これらのドキュメントは次のようになります上位の10ドキュメントにはランク付けされていない
クエリをコピーして CompoundBuryQuery.java
ファイルに貼り付けます。
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Aggregates.limit; 3 import static com.mongodb.client.model.Aggregates.project; 4 import static com.mongodb.client.model.Projections.*; 5 import com.mongodb.client.MongoClient; 6 import com.mongodb.client.MongoClients; 7 import com.mongodb.client.MongoCollection; 8 import com.mongodb.client.MongoDatabase; 9 10 import org.bson.Document; 11 12 public class CompoundBuryQuery { 13 public static void main( String[] args ) { 14 // define query 15 Document agg = 16 new Document("$search", 17 new Document("index", "default") 18 .append("compound", 19 new Document("should", Arrays.asList(new Document("compound", 20 new Document("must", Arrays.asList(new Document("text", 21 new Document("query", "ghost") 22 .append("path", Arrays.asList("plot", "title"))))) 23 .append("mustNot", Arrays.asList(new Document("text", 24 new Document("query", "Comedy") 25 .append("path", Arrays.asList("genres"))))) 26 ), 27 new Document("compound", 28 new Document("must", Arrays.asList(new Document("text", 29 new Document("query", "ghost") 30 .append("path", Arrays.asList("plot", "title"))))) 31 .append("filter", Arrays.asList(new Document("text", 32 new Document("query", "Comedy") 33 .append("path", Arrays.asList("genres"))))) 34 .append("score", new Document("boost", 35 new Document("value", 0.5d)))))) 36 ) 37 ); 38 // specify connection 39 String uri = "<connection-string>"; 40 // establish connection and set namespace 41 try (MongoClient mongoClient = MongoClients.create(uri)) { 42 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 43 MongoCollection<Document> collection = database.getCollection("movies"); 44 // run query and print results 45 collection.aggregate(Arrays.asList(agg, 46 limit(10), 47 project(fields( 48 include("title", "plot", "genres", "_id"), 49 computed("score", new Document("$meta", "searchScore")))))) 50 .forEach(doc -> System.out.println(doc.toJson())); 51 } 52 } 53 }
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 import java.util.Arrays; 2 import static com.mongodb.client.model.Aggregates.limit; 3 import static com.mongodb.client.model.Aggregates.project; 4 import static com.mongodb.client.model.Projections.*; 5 import com.mongodb.client.MongoClient; 6 import com.mongodb.client.MongoClients; 7 import com.mongodb.client.MongoCollection; 8 import com.mongodb.client.MongoDatabase; 9 import org.bson.types.ObjectId; 10 11 import org.bson.Document; 12 13 public class CompoundBuryQuery { 14 public static void main( String[] args ) { 15 // define query 16 Document agg = 17 new Document("$search", 18 new Document("index", "default") 19 .append("compound", 20 new Document("should", Arrays.asList( 21 new Document("compound", 22 new Document("must", Arrays.asList(new Document("text", 23 new Document("query", "ghost") 24 .append("path", Arrays.asList("plot", "title"))))) 25 .append("mustNot", Arrays.asList(new Document("in", 26 new Document("value", Arrays.asList(new ObjectId("573a13cdf29313caabd83c08"), 27 new ObjectId("573a13cef29313caabd873a2"))) 28 .append("path", "_id"))))), 29 new Document("compound", 30 new Document("must", Arrays.asList(new Document("text", 31 new Document("query", "ghost") 32 .append("path", Arrays.asList("plot", "title"))))) 33 .append("filter", Arrays.asList(new Document("in", 34 new Document("value", Arrays.asList(new ObjectId("573a13cdf29313caabd83c08"), 35 new ObjectId("573a13cef29313caabd873a2"))) 36 .append("path", "_id")))) 37 .append("score", new Document("boost", 38 new Document("value", 0.5d))))) 39 ) 40 ) 41 ); 42 // specify connection 43 String uri = "<connection-string>"; 44 // establish connection and set namespace 45 try (MongoClient mongoClient = MongoClients.create(uri)) { 46 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 47 MongoCollection<Document> collection = database.getCollection("movies"); 48 // run query and print results 49 collection.aggregate(Arrays.asList(agg, 50 limit(10), 51 project(fields( 52 include("title", "plot", "_id"), 53 computed("score", new Document("$meta", "searchScore")))))) 54 .forEach(doc -> System.out.println(doc.toJson())); 55 } 56 } 57 }
クエリ内の <connection-string>
を置き換え、ファイルを保存します。
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
CompoundBuryQuery.java
ファイルをコンパイルして実行します。
javac CompoundBuryQuery.java
{"_id": {"$oid": "573a139af29313caabcefcce"}, "plot": "Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.", "genres": ["Family", "Drama", "Fantasy"], "title": "The Canterville Ghost", "score": 5.909613132476807} {"_id": {"$oid": "573a13d8f29313caabda5dc1"}, "plot": "The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!", "genres": ["Family", "Fantasy"], "title": "The Little Ghost", "score": 5.367666244506836} {"_id": {"$oid": "573a13c0f29313caabd6139d"}, "plot": "Renowned \"ghost hunter\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.", "genres": ["Horror", "Thriller"], "title": "Death of a Ghost Hunter", "score": 4.676314353942871} {"_id": {"$oid": "573a1398f29313caabcebf6f"}, "plot": "After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.", "genres": ["Drama", "Fantasy", "Romance"], "title": "Ghost", "score": 3.9638845920562744} {"_id": {"$oid": "573a13cdf29313caabd83c08"}, "plot": "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "genres": ["Drama", "Fantasy", "Mystery"], "title": "Ghost", "score": 3.9638845920562744} {"_id": {"$oid": "573a13cef29313caabd873a2"}, "plot": "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "genres": ["Drama", "Fantasy", "Mystery"], "title": "Ghost", "score": 3.9638845920562744} {"_id": {"$oid": "573a13c3f29313caabd6a149"}, "plot": "What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...", "genres": ["Horror", "Thriller"], "title": "Coming Soon", "score": 3.526711940765381} {"_id": {"$oid": "573a1397f29313caabce7ea1"}, "plot": "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", "genres": ["Drama", "Horror", "Thriller"], "title": "Ghost Story", "score": 3.3177831172943115} {"_id": {"$oid": "573a13a4f29313caabd117df"}, "plot": "Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.", "genres": ["Action", "Fantasy", "Thriller"], "title": "Ghost Rider", "score": 3.3177831172943115} {"_id": {"$oid": "573a13a6f29313caabd185dc"}, "plot": "A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that \"strange things\" happen...", "genres": ["Horror", "Mystery"], "title": "Ghost Ship", "score": 3.3177831172943115}
結果内の映画ドキュメントのghost
plot
title
Comedy
フィールドまたは フィールドにクエリ用語 が含まれており、 ジャンルではありません。Atlas Search では、Comedy
フィールドまたはghost
plot
title
フィールドに10 というタームを含む50 ジャンルのドキュメントは返されませんでした。それらのドキュメントは上位の ドキュメントにランク付けされなかったためです。これらのドキュメントは % によって選出されます。
javac CompoundBuryQuery.java
{"_id": {"$oid": "573a139af29313caabcefcce"}, "plot": "Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.", "title": "The Canterville Ghost", "score": 5.909613132476807} {"_id": {"$oid": "573a13d8f29313caabda5dc1"}, "plot": "The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!", "title": "The Little Ghost", "score": 5.367666244506836} {"_id": {"$oid": "573a13c0f29313caabd6139d"}, "plot": "Renowned \"ghost hunter\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.", "title": "Death of a Ghost Hunter", "score": 4.676314353942871} {"_id": {"$oid": "573a1398f29313caabcebf6f"}, "plot": "After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.", "title": "Ghost", "score": 3.9638845920562744} {"_id": {"$oid": "573a13c3f29313caabd6a149"}, "plot": "What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...", "title": "Coming Soon", "score": 3.526711940765381} {"_id": {"$oid": "573a1398f29313caabce912c"}, "plot": "Three unemployed parapsychology professors set up shop as a unique ghost removal service.", "title": "Ghostbusters", "score": 3.5241782665252686} {"_id": {"$oid": "573a139cf29313caabcf5a48"}, "plot": "Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.", "title": "Casper Meets Wendy", "score": 3.5241782665252686} {"_id": {"$oid": "573a13bdf29313caabd58274"}, "plot": "Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...", "title": "Bhoothnath", "score": 3.4605300426483154} {"_id": {"$oid": "573a1397f29313caabce7ea1"}, "plot": "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", "title": "Ghost Story", "score": 3.3177831172943115} {"_id": {"$oid": "573a1398f29313caabcebf79"}, "plot": "Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...", "title": "Ghost Dad", "score": 3.3177831172943115}
結果内の映画ドキュメントの、 フィールドまたは フィールドにクエリ用語ghost
が含まれており、plot
title
フィールドに指定された ObjectId_id
がありません。Atlas Search では、指定された ObjectsId を含むドキュメントは、 title
フィールドにクエリ用語ghost
が含まれているにもかかわらず、返されませんでした。クエリではこれらのドキュメントのスコアが50 % 減少し、これらのドキュメントは次のようになります上位の10ドキュメントにはランク付けされていない
以下のコードをコピーして、CompoundBuryQuery.kt
ファイルに貼り付けます。
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_mflix") 13 val collection = database.getCollection<Document>("movies") 14 15 runBlocking { 16 // define clauses 17 val mustClause = listOf( 18 Document("text", 19 Document("query", "ghost") 20 .append("path", listOf("plot","title")) 21 ) 22 ) 23 24 val mustNotClauseAndFilterClause = listOf( 25 Document("text", 26 Document("query", "Comedy") 27 .append("path", listOf("genres")) 28 ) 29 ) 30 31 val compound1 = Document("must", mustClause) 32 .append("mustNot", mustNotClauseAndFilterClause) 33 34 val compound2 = Document("must", mustClause) 35 .append("filter", mustNotClauseAndFilterClause) 36 .append("score", 37 Document("boost", 38 Document("value", 0.5) 39 ) 40 ) 41 42 val agg = Document("\$search", 43 Document("index", "default") 44 .append("compound", Document("should", listOf( 45 Document("compound", compound1), 46 Document("compound", compound2) 47 ))) 48 ) 49 50 val resultsFlow = collection.aggregate<Document>( 51 listOf( 52 agg, 53 limit(10), 54 project(fields( 55 include("title", "plot", "genres"), 56 computed("score", Document("\$meta", "searchScore")) 57 )) 58 ) 59 ) 60 resultsFlow.collect { println(it) } 61 } 62 mongoClient.close() 63 }
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 import org.bson.types.ObjectId 8 9 fun main() { 10 // establish connection and set namespace 11 val uri = "<connection-string>" 12 val mongoClient = MongoClient.create(uri) 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define clauses 18 val mustClause = listOf( 19 Document("text", 20 Document("query", "ghost") 21 .append("path", listOf("plot","title")) 22 ) 23 ) 24 25 val mustNotClauseAndFilterClause = listOf( 26 Document("in", 27 Document("value", listOf(ObjectId("573a13cdf29313caabd83c08"), ObjectId("573a13cef29313caabd873a2"))) 28 .append("path", "_id") 29 ) 30 ) 31 32 val compound1 = Document("must", mustClause) 33 .append("mustNot", mustNotClauseAndFilterClause) 34 35 val compound2 = Document("must", mustClause) 36 .append("filter", mustNotClauseAndFilterClause) 37 .append("score", 38 Document("boost", 39 Document("value", 0.5) 40 ) 41 ) 42 43 val agg = Document("\$search", 44 Document("index", "default") 45 .append("compound", Document("should", listOf( 46 Document("compound", compound1), 47 Document("compound", compound2) 48 ))) 49 ) 50 51 val resultsFlow = collection.aggregate<Document>( 52 listOf( 53 agg, 54 limit(10), 55 project(fields( 56 include("title", "plot", "_id"), 57 computed("score", Document("\$meta", "searchScore")) 58 )) 59 ) 60 ) 61 resultsFlow.collect { println(it) } 62 } 63 mongoClient.close() 64 }
クエリ内の <connection-string>
を置き換え、ファイルを保存します。
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
CompoundBuryQuery.kt
ファイルを実行します。
IDE でCompoundBuryQuery.kt
プログラムを実行すると、次のドキュメントが出力されます。
dotnet run compound-bury-results.csproj
Document{{_id=573a139af29313caabcefcce, plot=Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness., genres=[Family, Drama, Fantasy], title=The Canterville Ghost, score=5.909613132476807}} Document{{_id=573a13d8f29313caabda5dc1, plot=The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!, genres=[Family, Fantasy], title=The Little Ghost, score=5.367666244506836}} Document{{_id=573a13c0f29313caabd6139d, plot=Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror., genres=[Horror, Thriller], title=Death of a Ghost Hunter, score=4.676314353942871}} Document{{_id=573a1398f29313caabcebf6f, plot=After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic., genres=[Drama, Fantasy, Romance], title=Ghost, score=3.9638845920562744}} Document{{_id=573a13cdf29313caabd83c08, plot=A man tries to solve his lover's murder by communicating with her spirit through the help of a medium., genres=[Drama, Fantasy, Mystery], title=Ghost, score=3.9638845920562744}} Document{{_id=573a13cef29313caabd873a2, plot=A man tries to solve his lover's murder by communicating with her spirit through the help of a medium., genres=[Drama, Fantasy, Mystery], title=Ghost, score=3.9638845920562744}} Document{{_id=573a13c3f29313caabd6a149, plot=What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ..., genres=[Horror, Thriller], title=Coming Soon, score=3.526711940765381}} Document{{_id=573a1397f29313caabce7ea1, plot=Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ..., genres=[Drama, Horror, Thriller], title=Ghost Story, score=3.3177831172943115}} Document{{_id=573a13a4f29313caabd117df, plot=Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself., genres=[Action, Fantasy, Thriller], title=Ghost Rider, score=3.3177831172943115}} Document{{_id=573a13a6f29313caabd185dc, plot=A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen..., genres=[Horror, Mystery], title=Ghost Ship, score=3.3177831172943115}}
結果内の映画ドキュメントのghost
plot
title
Comedy
フィールドまたは フィールドにクエリ用語 が含まれており、 ジャンルではありません。Atlas Search では、Comedy
フィールドまたはghost
plot
title
フィールドに10 というタームを含む50 ジャンルのドキュメントは返されませんでした。それらのドキュメントは上位の ドキュメントにランク付けされなかったためです。これらのドキュメントは % によって選出されます。
dotnet run compound-bury-results.csproj
Document{{_id=573a139af29313caabcefcce, plot=Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness., title=The Canterville Ghost, score=5.909613132476807}} Document{{_id=573a13d8f29313caabda5dc1, plot=The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!, title=The Little Ghost, score=5.367666244506836}} Document{{_id=573a13c0f29313caabd6139d, plot=Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror., title=Death of a Ghost Hunter, score=4.676314353942871}} Document{{_id=573a1398f29313caabcebf6f, plot=After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic., title=Ghost, score=3.9638845920562744}} Document{{_id=573a13c3f29313caabd6a149, plot=What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ..., title=Coming Soon, score=3.526711940765381}} Document{{_id=573a1398f29313caabce912c, plot=Three unemployed parapsychology professors set up shop as a unique ghost removal service., title=Ghostbusters, score=3.5241782665252686}} Document{{_id=573a139cf29313caabcf5a48, plot=Casper, a ghost, teams up with Wendy, a witch, against an evil warlock., title=Casper Meets Wendy, score=3.5241782665252686}} Document{{_id=573a13bdf29313caabd58274, plot=Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy..., title=Bhoothnath, score=3.4605300426483154}} Document{{_id=573a1397f29313caabce7ea1, plot=Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ..., title=Ghost Story, score=3.3177831172943115}} Document{{_id=573a1398f29313caabcebf79, plot=Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ..., title=Ghost Dad, score=3.3177831172943115}}
結果内の映画ドキュメントの、 フィールドまたは フィールドにクエリ用語ghost
が含まれており、plot
title
フィールドに指定された ObjectId_id
がありません。Atlas Search では、指定された ObjectsId を含むドキュメントは、 title
フィールドにクエリ用語ghost
が含まれているにもかかわらず、返されませんでした。クエリではこれらのドキュメントのスコアが50 % 減少し、これらのドキュメントは次のようになります上位の10ドキュメントにはランク付けされていない
サンプルクエリをコピーして compound-bury-results.js
ファイルに貼り付けます。
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas cluster 4 const uri = "<connection-string>"; 5 const client = new MongoClient(uri); 6 7 async function run() { 8 try { 9 await client.connect(); 10 11 // set namespace 12 const database = client.db("sample_mflix"); 13 const coll = database.collection("movies"); 14 15 // define pipeline 16 const agg = [ 17 { 18 "$search": { 19 "index": "default", 20 "compound": { 21 "should": [ 22 { 23 "compound": { 24 "must": [ 25 { 26 "text": { 27 "query": "ghost", 28 "path": [ 29 "plot", "title" 30 ] 31 } 32 } 33 ], 34 "mustNot": [ 35 { 36 "text": { 37 "query": "Comedy", 38 "path": [ 39 "genres" 40 ] 41 } 42 } 43 ] 44 } 45 }, { 46 "compound": { 47 "must": [ 48 { 49 "text": { 50 "query": "ghost", 51 "path": [ 52 "plot", "title" 53 ] 54 } 55 } 56 ], 57 "filter": [ 58 { 59 "text": { 60 "query": "Comedy", 61 "path": [ 62 "genres" 63 ] 64 } 65 } 66 ], 67 "score": { "boost": { "value": 0.5 } } 68 } 69 } 70 ] 71 } 72 } 73 }, { 74 "$limit": 10 75 }, { 76 "$project": { 77 "_id": 1, 78 "title": 1, 79 "plot": 1, 80 "genres": 1, 81 "score": { "$meta": "searchScore" } 82 } 83 } 84 ]; 85 86 // run pipeline 87 const result = coll.aggregate(agg); 88 89 // print results 90 await result.forEach((doc) => console.dir(JSON.stringify(doc))); 91 } finally { 92 await client.close(); 93 } 94 } 95 run().catch(console.dir);
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 const { MongoClient } = require("mongodb"); 2 const { ObjectId } = require("mongodb"); 3 4 // connect to your Atlas cluster 5 const uri = "<connection-string>"; 6 const client = new MongoClient(uri); 7 8 async 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 '$search': { 20 'index': 'default', 21 'compound': { 22 'should': [ 23 { 24 'compound': { 25 'must': [ 26 { 27 'text': { 28 'query': 'ghost', 29 'path': [ 'plot', 'title' ] 30 } 31 } 32 ], 33 'mustNot': [ 34 { 35 'in': { 36 'value': [ new ObjectId('573a13cdf29313caabd83c08'), new ObjectId('573a13cef29313caabd873a2') ], 37 'path': '_id' 38 } 39 } 40 ] 41 } 42 }, { 43 'compound': { 44 'must': [ 45 { 46 'text': { 47 'query': 'ghost', 48 'path': [ 'plot', 'title' ] 49 } 50 } 51 ], 52 'filter': [ 53 { 54 'in': { 55 'value': [ new ObjectId('573a13cdf29313caabd83c08'), new ObjectId('573a13cef29313caabd873a2') ], 56 'path': '_id' 57 } 58 } 59 ], 60 'score': { 61 'boost': { 'value': 0.5 } 62 } 63 } 64 } 65 ] 66 } 67 } 68 }, { 69 '$limit': 10 70 }, { 71 '$project': { 72 '_id': 1, 73 'title': 1, 74 'plot': 1, 75 'score': { '$meta': 'searchScore' } 76 } 77 } 78 ]; 79 80 // run pipeline 81 const result = coll.aggregate(agg); 82 83 // print results 84 await result.forEach((doc) => console.dir(JSON.stringify(doc))); 85 } finally { 86 await client.close(); 87 } 88 } 89 run().catch(console.dir);
クエリ内の <connection-string>
を置き換え、ファイルを保存します。
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
コレクションをクエリします。
次のコマンドを実行して、コレクションをクエリします。
node compound-bury-results.js
{"_id":"573a139af29313caabcefcce","plot":"Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.","genres":["Family","Drama","Fantasy"],"title":"The Canterville Ghost","score":5.909613132476807} {"_id":"573a13d8f29313caabda5dc1","plot":"The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!","genres":["Family","Fantasy"],"title":"The Little Ghost","score":5.367666244506836} {"_id":"573a13c0f29313caabd6139d","plot":"Renowned \\"ghost hunter\\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.","genres":["Horror","Thriller"],"title":"Death of a Ghost Hunter","score":4.676314353942871} {"_id":"573a1398f29313caabcebf6f","plot":"After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.","genres":["Drama","Fantasy","Romance"],"title":"Ghost","score":3.9638845920562744} {"_id":"573a13cdf29313caabd83c08","plot":"A man tries to solve his lovers murder by communicating with her spirit through the help of a medium.","genres":["Drama","Fantasy","Mystery"],"title":"Ghost","score":3.9638845920562744} {"_id":"573a13cef29313caabd873a2","plot":"A man tries to solve his lovers murder by communicating with her spirit through the help of a medium.","genres":["Drama","Fantasy","Mystery"],"title":"Ghost","score":3.9638845920562744} {"_id":"573a13c3f29313caabd6a149","plot":"What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...","genres":["Horror","Thriller"],"title":"Coming Soon","score":3.526711940765381} {"_id":"573a1397f29313caabce7ea1","plot":"Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderleys twin sons dies in a bizarre accident, the group ...","genres":["Drama","Horror","Thriller"],"title":"Ghost Story","score":3.3177831172943115} {"_id":"573a13a4f29313caabd117df","plot":"Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.","genres":["Action","Fantasy","Thriller"],"title":"Ghost Rider","score":3.3177831172943115} {"_id":"573a13a6f29313caabd185dc","plot":"A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that \\"strange things\\" happen...","genres":["Horror","Mystery"],"title":"Ghost Ship","score":3.3177831172943115}
結果内の映画ドキュメントのghost
plot
title
Comedy
フィールドまたは フィールドにクエリ用語 が含まれており、 ジャンルではありません。Atlas Search では、Comedy
フィールドまたはghost
plot
title
フィールドに10 というタームを含む50 ジャンルのドキュメントは返されませんでした。それらのドキュメントは上位の ドキュメントにランク付けされなかったためです。これらのドキュメントは % によって選出されます。
node compound-bury-results.js
{"_id":"573a139af29313caabcefcce","plot":"Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.","title":"The Canterville Ghost","score":5.909613132476807} {"_id":"573a13d8f29313caabda5dc1","plot":"The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!","title":"The Little Ghost","score":5.367666244506836} {"_id":"573a13c0f29313caabd6139d","plot":"Renowned \\"ghost hunter\\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.","title":"Death of a Ghost Hunter","score":4.676314353942871} {"_id":"573a1398f29313caabcebf6f","plot":"After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.","title":"Ghost","score":3.9638845920562744} {"_id":"573a13c3f29313caabd6a149","plot":"What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...","title":"Coming Soon","score":3.526711940765381} {"_id":"573a1398f29313caabce912c","plot":"Three unemployed parapsychology professors set up shop as a unique ghost removal service.","title":"Ghostbusters","score":3.5241782665252686} {"_id":"573a139cf29313caabcf5a48","plot":"Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.","title":"Casper Meets Wendy","score":3.5241782665252686} {"_id":"573a13bdf29313caabd58274","plot":"Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...","title":"Bhoothnath","score":3.4605300426483154} {"_id":"573a1397f29313caabce7ea1","plot":"Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderleys twin sons dies in a bizarre accident, the group ...","title":"Ghost Story","score":3.3177831172943115} {"_id":"573a1398f29313caabcebf79","plot":"Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...","title":"Ghost Dad","score":3.3177831172943115}
結果内の映画ドキュメントの、 フィールドまたは フィールドにクエリ用語ghost
が含まれており、plot
title
フィールドに指定された ObjectId_id
がありません。Atlas Search では、指定された ObjectsId を含むドキュメントは、 title
フィールドにクエリ用語ghost
が含まれているにもかかわらず、返されませんでした。クエリではこれらのドキュメントのスコアが50 % 減少し、これらのドキュメントは次のようになります上位の10ドキュメントにはランク付けされていない
クエリをコピーして compound-bury-results.py
ファイルに貼り付けます。
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 import pymongo 2 import dns 3 4 client = pymongo.MongoClient('<connection-string>') 5 result = client['sample_mflix']['movies'].aggregate([ 6 { 7 '$search': { 8 'index': 'default', 9 'compound': { 10 'should': [ 11 { 12 'compound': { 13 'must': [ 14 { 15 'text': { 16 'query': 'ghost', 17 'path': [ 'plot', 'title' ] 18 } 19 } 20 ], 21 'mustNot': [ 22 { 23 'text': { 24 'query': 'Comedy', 25 'path': [ 'genres' ] 26 } 27 } 28 ] 29 } 30 }, { 31 'compound': { 32 'must': [ 33 { 34 'text': { 35 'query': 'ghost', 36 'path': [ 'plot', 'title' ] 37 } 38 } 39 ], 40 'filter': [ 41 { 42 'text': { 43 'query': 'Comedy', 44 'path': [ 'genres' ] 45 } 46 } 47 ], 48 'score': { 'boost': { 'value': 0.5 } } 49 } 50 } 51 ] 52 } 53 } 54 }, { 55 '$limit': 10 56 }, { 57 '$project': { 58 '_id': 1, 59 'title': 1, 60 'plot': 1, 61 'genres': 1, 62 'score': { '$meta': 'searchScore' } 63 } 64 } 65 ]) 66 67 for i in result: 68 print(i)
このクエリでは、次のパイプライン ステージを使用します。
| |
結果数を | |
|
1 import pymongo 2 import dns 3 from bson import ObjectId 4 5 client = pymongo.MongoClient('<connection-string>') 6 result = client['sample_mflix']['movies'].aggregate([ 7 { 8 '$search': { 9 'index': 'default', 10 'compound': { 11 'should': [ 12 { 13 'compound': { 14 'must': [ 15 { 16 'text': { 17 'query': 'ghost', 18 'path': [ 'plot', 'title' ] 19 } 20 } 21 ], 22 'mustNot': [ 23 { 24 'in': { 25 'value': [ ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2') ], 26 'path': '_id' 27 } 28 } 29 ] 30 } 31 }, { 32 'compound': { 33 'must': [ 34 { 35 'text': { 36 'query': 'ghost', 37 'path': [ 'plot', 'title' ] 38 } 39 } 40 ], 41 'filter': [ 42 { 43 'in': { 44 'value': [ ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2') ], 45 'path': '_id' 46 } 47 } 48 ], 49 'score': { 'boost': { 'value': 0.5 } } 50 } 51 } 52 ] 53 } 54 } 55 }, { 56 '$limit': 10 57 }, { 58 '$project': { 59 '_id': 1, 60 'title': 1, 61 'plot': 1, 62 'score': { '$meta': 'searchScore' } 63 } 64 } 65 ]) 66 67 for i in result: 68 print(i)
クエリ内の <connection-string>
を置き換え、ファイルを保存します。
接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。
コマンドを実行して、コレクションをクエリします。
python compound-bury-results.csproj
{'_id': ObjectId('573a139af29313caabcefcce'), 'plot': 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.', 'genres': ['Family', 'Drama', 'Fantasy'], 'title': 'The Canterville Ghost', 'score': 5.909613132476807} {'_id': ObjectId('573a13d8f29313caabda5dc1'), 'plot': 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!', 'genres': ['Family', 'Fantasy'], 'title': 'The Little Ghost', 'score': 5.367666244506836} {'_id': ObjectId('573a13c0f29313caabd6139d'), 'plot': 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.', 'genres': ['Horror', 'Thriller'], 'title': 'Death of a Ghost Hunter', 'score': 4.676314353942871} {'_id': ObjectId('573a1398f29313caabcebf6f'), 'plot': 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.', 'genres': ['Drama', 'Fantasy', 'Romance'], 'title': 'Ghost', 'score': 3.9638845920562744} {'_id': ObjectId('573a13cdf29313caabd83c08'), 'plot': "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", 'genres': ['Drama', 'Fantasy', 'Mystery'], 'title': 'Ghost', 'score': 3.9638845920562744} {'_id': ObjectId('573a13cef29313caabd873a2'), 'plot': "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", 'genres': ['Drama', 'Fantasy', 'Mystery'], 'title': 'Ghost', 'score': 3.9638845920562744} {'_id': ObjectId('573a13c3f29313caabd6a149'), 'plot': 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...', 'genres': ['Horror', 'Thriller'], 'title': 'Coming Soon', 'score': 3.526711940765381} {'_id': ObjectId('573a1397f29313caabce7ea1'), 'plot': "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", 'genres': ['Drama', 'Horror', 'Thriller'], 'title': 'Ghost Story', 'score': 3.3177831172943115} {'_id': ObjectId('573a13a4f29313caabd117df'), 'plot': 'Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.', 'genres': ['Action', 'Fantasy', 'Thriller'], 'title': 'Ghost Rider', 'score': 3.3177831172943115} {'_id': ObjectId('573a13a6f29313caabd185dc'), 'plot': 'A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...', 'genres': ['Horror', 'Mystery'], 'title': 'Ghost Ship', 'score': 3.3177831172943115}
結果内の映画ドキュメントのghost
plot
title
Comedy
フィールドまたは フィールドにクエリ用語 が含まれており、 ジャンルではありません。Atlas Search では、Comedy
フィールドまたはghost
plot
title
フィールドに10 というタームを含む50 ジャンルのドキュメントは返されませんでした。それらのドキュメントは上位の ドキュメントにランク付けされなかったためです。これらのドキュメントは % によって選出されます。
python compound-bury-results.csproj
{'_id': ObjectId('573a139af29313caabcefcce'), 'plot': 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.', 'title': 'The Canterville Ghost', 'score': 5.909613132476807} {'_id': ObjectId('573a13d8f29313caabda5dc1'), 'plot': 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!', 'title': 'The Little Ghost', 'score': 5.367666244506836} {'_id': ObjectId('573a13c0f29313caabd6139d'), 'plot': 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.', 'title': 'Death of a Ghost Hunter', 'score': 4.676314353942871} {'_id': ObjectId('573a1398f29313caabcebf6f'), 'plot': 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.', 'title': 'Ghost', 'score': 3.9638845920562744} {'_id': ObjectId('573a13c3f29313caabd6a149'), 'plot': 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...', 'title': 'Coming Soon', 'score': 3.526711940765381} {'_id': ObjectId('573a1398f29313caabce912c'), 'plot': 'Three unemployed parapsychology professors set up shop as a unique ghost removal service.', 'title': 'Ghostbusters', 'score': 3.5241782665252686} {'_id': ObjectId('573a139cf29313caabcf5a48'), 'plot': 'Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.', 'title': 'Casper Meets Wendy', 'score': 3.5241782665252686} {'_id': ObjectId('573a13bdf29313caabd58274'), 'plot': 'Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...', 'title': 'Bhoothnath', 'score': 3.4605300426483154} {'_id': ObjectId('573a1397f29313caabce7ea1'), 'plot': "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", 'title': 'Ghost Story', 'score': 3.3177831172943115} {'_id': ObjectId('573a1398f29313caabcebf79'), 'plot': 'Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...', 'title': 'Ghost Dad', 'score': 3.3177831172943115}
結果内の映画ドキュメントの、 フィールドまたは フィールドにクエリ用語ghost
が含まれており、plot
title
フィールドに指定された ObjectId_id
がありません。Atlas Search では、指定された ObjectsId を含むドキュメントは、 title
フィールドにクエリ用語ghost
が含まれているにもかかわらず、返されませんでした。クエリではこれらのドキュメントのスコアが50 % 減少し、これらのドキュメントは次のようになります上位の10ドキュメントにはランク付けされていない
スコアを正規化する
集計パイプラインのその後の段階で、 0
から1
の範囲で$search
クエリ スコアを正規化できます。 スコアを正規化するには、 $search
ステージの後に以下のステージを次の順序で使用できます。
{ "$addFields": { "score": { "$meta": "searchScore" } } } { "$setWindowFields": { "output": { "maxScore": { "$max": "$score" } } } } { "$addFields": { "normalizedScore": { "$divide": [ "$score", "$maxScore" ] } } }
1 db.movies.aggregate([{ 2 "$search": { 3 "text": { 4 "query": "Helsinki", 5 "path": "plot" 6 } 7 } 8 }, 9 { 10 "$limit": 5 11 }, 12 { 13 "$project": { 14 "_id": 0, 15 "title": 1, 16 "score": 1, 17 "maxScore": 1, 18 "normalizedScore": 1 19 } 20 }, 21 { 22 "$addFields": { 23 "score": { 24 "$meta": "searchScore" 25 } 26 } 27 }, 28 { 29 "$setWindowFields": { 30 "output": { 31 "maxScore": { 32 "$max": "$score" 33 } 34 } 35 } 36 }, 37 { 38 "$addFields": { 39 "normalizedScore": { 40 "$divide": [ 41 "$score", "$maxScore" 42 ] 43 } 44 } 45 }])
1 [ 2 { 3 title: 'Drifting Clouds', 4 score: 4.5660295486450195, 5 maxScore: 4.5660295486450195, 6 normalizedScore: 1 7 }, 8 { 9 title: 'Sairaan kaunis maailma', 10 score: 4.041563034057617, 11 maxScore: 4.5660295486450195, 12 normalizedScore: 0.8851372929150143 13 }, 14 { 15 title: 'Bad Luck Love', 16 score: 3.6251673698425293, 17 maxScore: 4.5660295486450195, 18 normalizedScore: 0.79394303764817 19 }, 20 { 21 title: 'Bad Luck Love', 22 score: 3.6251673698425293, 23 maxScore: 4.5660295486450195, 24 normalizedScore: 0.79394303764817 25 }, 26 { 27 title: 'Forbidden Fruit', 28 score: 3.6251673698425293, 29 maxScore: 4.5660295486450195, 30 normalizedScore: 0.79394303764817 31 } 32 ]
1 db.movies.aggregate([{ 2 "$search": { 3 "text": { 4 "path": "title", 5 "query": "men", 6 "score": { 7 "function":{ 8 "multiply":[ 9 { 10 "path": { 11 "value": "imdb.rating", 12 "undefined": 2 13 } 14 }, 15 { 16 "score": "relevance" 17 } 18 ] 19 } 20 } 21 } 22 } 23 }, 24 { 25 "$limit": 5 26 }, 27 { 28 "$addFields": { 29 "score": { 30 "$meta": "searchScore" 31 } 32 } 33 }, 34 { 35 "$setWindowFields": { 36 "output": { 37 "maxScore": { 38 "$max": "$score" 39 } 40 } 41 } 42 }, 43 { 44 "$addFields": { 45 "normalizedScore": { 46 "$divide": [ 47 "$score", "$maxScore" 48 ] 49 } 50 } 51 }, 52 { 53 "$project": { 54 "_id": 0, 55 "title": 1, 56 "score": 1, 57 "maxScore": 1, 58 "normalizedScore": 1 59 } 60 }])
1 [ 2 { 3 title: 'Men...', 4 score: 23.431293487548828, 5 maxScore: 23.431293487548828, 6 normalizedScore: 1 7 }, 8 { 9 title: '12 Angry Men', 10 score: 22.080968856811523, 11 maxScore: 23.431293487548828, 12 normalizedScore: 0.9423708882544255 13 }, 14 { 15 title: 'X-Men', 16 score: 21.34803581237793, 17 maxScore: 23.431293487548828, 18 normalizedScore: 0.911090795039637 19 }, 20 { 21 title: 'X-Men', 22 score: 21.34803581237793, 23 maxScore: 23.431293487548828, 24 normalizedScore: 0.911090795039637 25 }, 26 { 27 title: 'Matchstick Men', 28 score: 21.05954933166504, 29 maxScore: 23.431293487548828, 30 normalizedScore: 0.8987787781692841 31 } 32 ]
1 db.movies.aggregate([{ 2 "$search": { 3 "text": { 4 "path": "title", 5 "query": "shop", 6 "score": { 7 "function":{ 8 "gauss": { 9 "path": { 10 "value": "imdb.rating", 11 "undefined": 4.6 12 }, 13 "origin": 9.5, 14 "scale": 5, 15 "offset": 0, 16 "decay": 0.5 17 } 18 } 19 } 20 } 21 } 22 }, 23 { 24 "$limit": 5 25 }, 26 { 27 "$addFields": { 28 "score": { 29 "$meta": "searchScore" 30 } 31 } 32 }, 33 { 34 "$setWindowFields": { 35 "output": { 36 "maxScore": { 37 "$max": "$score" 38 } 39 } 40 } 41 }, 42 { 43 "$addFields": { 44 "normalizedScore": { 45 "$divide": [ 46 "$score", "$maxScore" 47 ] 48 } 49 } 50 }, 51 { 52 "$project": { 53 "_id": 0, 54 "title": 1, 55 "score": 1, 56 "maxScore": 1, 57 "normalizedScore": 1 58 } 59 }])
1 [ 2 { 3 title: 'The Shop Around the Corner', 4 score: 0.9471074342727661, 5 maxScore: 0.9471074342727661, 6 normalizedScore: 1 7 }, 8 { 9 title: 'Exit Through the Gift Shop', 10 score: 0.9471074342727661, 11 maxScore: 0.9471074342727661, 12 normalizedScore: 1 13 }, 14 { 15 title: 'The Shop on Main Street', 16 score: 0.9395227432250977, 17 maxScore: 0.9471074342727661, 18 normalizedScore: 0.9919917310611205 19 }, 20 { 21 title: 'Chop Shop', 22 score: 0.8849083781242371, 23 maxScore: 0.9471074342727661, 24 normalizedScore: 0.9343273488331464 25 }, 26 { 27 title: 'Little Shop of Horrors', 28 score: 0.8290896415710449, 29 maxScore: 0.9471074342727661, 30 normalizedScore: 0.8753913353110349 31 } 32 ]
1 db.movies.aggregate([{ 2 "$search": { 3 "text": { 4 "path": "title", 5 "query": "men", 6 "score": { 7 "function":{ 8 "path": { 9 "value": "imdb.rating", 10 "undefined": 4.6 11 } 12 } 13 } 14 } 15 } 16 }, 17 { 18 "$limit": 5 19 }, 20 { 21 "$addFields": { 22 "score": { 23 "$meta": "searchScore" 24 } 25 } 26 }, 27 { 28 "$setWindowFields": { 29 "output": { 30 "maxScore": { 31 "$max": "$score" 32 } 33 } 34 } 35 }, 36 { 37 "$addFields": { 38 "normalizedScore": { 39 "$divide": [ 40 "$score", "$maxScore" 41 ] 42 } 43 } 44 }, 45 { 46 "$project": { 47 "_id": 0, 48 "title": 1, 49 "score": 1, 50 "maxScore": 1, 51 "normalizedScore": 1 52 } 53 }])
1 [ 2 { 3 title: '12 Angry Men', 4 score: 8.899999618530273, 5 maxScore: 8.899999618530273, 6 normalizedScore: 1 7 }, 8 { 9 title: 'The Men Who Built America', 10 score: 8.600000381469727, 11 maxScore: 8.899999618530273, 12 normalizedScore: 0.9662922191102197 13 }, 14 { 15 title: 'No Country for Old Men', 16 score: 8.100000381469727, 17 maxScore: 8.899999618530273, 18 normalizedScore: 0.9101124414213563 19 }, 20 { 21 title: 'X-Men: Days of Future Past', 22 score: 8.100000381469727, 23 maxScore: 8.899999618530273, 24 normalizedScore: 0.9101124414213563 25 }, 26 { 27 title: 'The Best of Men', 28 score: 8.100000381469727, 29 maxScore: 8.899999618530273, 30 normalizedScore: 0.9101124414213563 31 } 32 ]
1 db.movies.aggregate([{ 2 "$search": { 3 "text": { 4 "path": "title", 5 "query": "men", 6 "score": { 7 "function": { 8 "log": { 9 "path": { 10 "value": "imdb.rating", 11 "undefined": 10 12 } 13 } 14 } 15 } 16 } 17 } 18 }, 19 { 20 "$limit": 5 21 }, 22 { 23 "$addFields": { 24 "score": { 25 "$meta": "searchScore" 26 } 27 } 28 }, 29 { 30 "$setWindowFields": { 31 "output": { 32 "maxScore": { 33 "$max": "$score" 34 } 35 } 36 } 37 }, 38 { 39 "$addFields": { 40 "normalizedScore": { 41 "$divide": [ 42 "$score", "$maxScore" 43 ] 44 } 45 } 46 }, 47 { 48 "$project": { 49 "_id": 0, 50 "title": 1, 51 "score": 1, 52 "maxScore": 1, 53 "normalizedScore": 1 54 } 55 } 56 ])
1 [ 2 { 3 title: '12 Angry Men', 4 score: 0.9493899941444397, 5 maxScore: 0.9493899941444397, 6 normalizedScore: 1 7 }, 8 { 9 title: 'The Men Who Built America', 10 score: 0.9344984292984009, 11 maxScore: 0.9493899941444397, 12 normalizedScore: 0.9843145968064908 13 }, 14 { 15 title: 'No Country for Old Men', 16 score: 0.9084849953651428, 17 maxScore: 0.9493899941444397, 18 normalizedScore: 0.9569144408182233 19 }, 20 { 21 title: 'X-Men: Days of Future Past', 22 score: 0.9084849953651428, 23 maxScore: 0.9493899941444397, 24 normalizedScore: 0.9569144408182233 25 }, 26 { 27 title: 'The Best of Men', 28 score: 0.9084849953651428, 29 maxScore: 0.9493899941444397, 30 normalizedScore: 0.9569144408182233 31 } 32 ]
Atlas Search 結果には次のスコアが含まれています。
$search
score
$addFields
ステージからの フィールドの クエリの変更されたスコア。内のドキュメントに割り当てられる最大スコアは、
$setWindowFields
ステージのmaxScore
フィールドに表示されます。$addFields
ステージからのnormalizedScore
フィールドの正規化されたスコア。これは、 $divideを使用して、$score
の変更されたスコアを$maxScore
の最大スコアで除算して計算されます。
学び続ける
Atlas Search を使用して複合クエリについて詳しくは、 MongoDB University の Intro To MongoDB コースユニット9を受講してください。 1.5時間のユニットには、Atlas Search の概要、Atlas Search インデックスの作成、複合演算子を使用した$search
クエリの実行、ファセット を使用した結果のグループ化に関するレッスンが含まれています。