Docs Menu
Docs Home
/
MongoDB Atlas
/ /

加重フィールドを使用した Atlas Search 複合クエリの実行方法

項目一覧

  • 動的マッピングを使用した Atlas Search インデックスの作成
  • 複合クエリの実行
  • 複合クエリを実行して結果をブースト
  • 複合クエリを実行して結果を埋め込む
  • 学び続ける

このチュートリアルでは、検索フィールドに重みを追加して、結果または結果のカテゴリ内のドキュメントをブーストまたは埋め込みする方法を説明します。 フィールドに 1 つ以上の値を割り当てて、スコアの高い結果または低い結果を返す方法を示します。

具体的には、チュートリアルでは、 sample_mflix.moviesコレクションに 動的マッピングを使用してインデックスを作成する 方法を示します。 複合クエリを実行し、 constantfunctionboostを使用してスコアを変更する方法を示します。 次の手順が必要です。

  1. sample_mflix.moviesコレクションの 動的マッピング を使用して Atlas Search インデックスを設定します。

  2. 次の Atlas Search クエリを実行します。

    • yearフィールドをクエリし、title フィールドの特定の単語を使用してスコアを変更して、結果内のドキュメントをブーストします。

    • titleフィールドとplotフィールドをクエリし、 genresフィールドの特定のジャンルに基づいてスコアを変更して、そのジャンルの結果を埋め込みます。

開始する前に、Atlas クラスターが前提条件 に記載されている要件を満たしていることを確認してください。

Atlas Search インデックスを作成するには、プロジェクトに対するProject Data Access Admin以上のアクセス権が必要です。

このセクションでは、動的マッピングを使用してsample_mflix.moviesコレクション内のフィールドにインデックスを付けるための Atlas Search インデックスを作成します。

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

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

  3. まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。

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

2

GoAtlas Searchページには、サイドバー、Data Explorer 、またはクラスターの詳細ページから できます。

  1. サイドバーで、 Services見出しの下のAtlas Searchをクリックします。

  2. [ Select data sourceドロップダウンからクラスターを選択し、[ Go to Atlas Search ] をクリックします。

    Atlas Searchページが表示されます。

  1. クラスターの [Browse Collections] ボタンをクリックします。

  2. データベースを展開し、コレクションを選択します。

  3. コレクションのSearch Indexesタブをクリックします。

    Atlas Searchページが表示されます。

  1. クラスタの名前をクリックします。

  2. [Atlas Search] タブをクリックします。

    Atlas Searchページが表示されます。

3
4
  • ガイドを利用する場合は、Atlas Search Visual Editor を選択します。

  • Raw インデックス定義を編集するには、Atlas Search JSON Editor を選択します。

5
  1. Index Nameフィールドにcompound-query-custom-score-tutorialと入力します。

    インデックスにdefaultと名付けると、 $searchパイプライン ステージでindexパラメータを指定する必要がなくなります。 インデックスにカスタム名を付ける場合は、 indexパラメータでこの名前を指定する必要があります。

  2. Database and Collectionセクションで、 sample_mflixデータベースを検索し、 moviesコレクションを選択します。

6

動的マッピングまたは静的マッピングを使用する Atlas Search インデックスを作成できます。 動的マッピングと静的マッピングについて詳しくは、「静的マッピングと動的マッピング 」を参照してください。

次のインデックス定義は、 moviesコレクション内のサポートされている型のフィールドを動的にインデックス化します。 Atlas Search Visual Editor またはAtlas Search JSON Editor を使用して、 Atlas userインターフェースでインデックスを作成できます。

  1. [Next] をクリックします。

  2. moviesコレクションの"default"インデックス定義を確認します。

  1. [Next] をクリックします。

  2. インデックスの定義を確認します。

    インデックス定義は、次のようになります。

    {
    "mappings": {
    "dynamic": true
    }
    }

    上記のインデックス定義は、 moviesコレクション内の各ドキュメントでサポートされているタイプのフィールドを動的にインデックス化します。

  3. [Next] をクリックします。

7
8

インデックスが作成中であることを知らせるモーダル ウィンドウが表示されます。Close ボタンをクリックします。

9

インデックスの構築には約 1 分かかります。 作成している間、 Status列にはBuild in Progressと表示されます。 作成が完了すると、 Status列にはActiveと表示されます。

複合演算子 を使用して、2 つ以上の演算子を 1 つのクエリに結合します。 Atlas Search は、クエリで返される各ドキュメントに対して、関連性に基づいて最高スコアから最低スコアの順にスコアを割り当てます。 クエリは、結果内のドキュメントをブーストまたは埋め込む方法を示します。


➤ [言語の選択]ドロップダウン メニューを使用して、このセクション内の例の言語を設定します。


Tip

Atlas Search には、ガイダンス付きのサンプル複合クエリ テンプレートが用意されています。詳細については、「クエリ ガイダンス テンプレートの表示」を参照してください。

このセクションでは、Atlas クラスターに接続し、 titleyearsample_mflix.moviesコレクションの フィールドと フィールドに対して 複合 演算子を使用してサンプル クエリを実行します。サンプル クエリはカスタム スコアリングを使用して、 snowというタームを含む映画タイトルの Atlas Search によって返される関連性スコアを変更します。

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

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

  3. まだ表示されていない場合は、サイドバーの [Clusters] をクリックします。

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

2

GoAtlas Searchページには、サイドバー、Data Explorer 、またはクラスターの詳細ページから できます。

  1. サイドバーで、 Services見出しの下のAtlas Searchをクリックします。

  2. [ Select data sourceドロップダウンからクラスターを選択し、[ Go to Atlas Search ] をクリックします。

    Atlas Searchページが表示されます。

  1. クラスターの [Browse Collections] ボタンをクリックします。

  2. データベースを展開し、コレクションを選択します。

  3. コレクションのSearch Indexesタブをクリックします。

    Atlas Searchページが表示されます。

  1. クラスタの名前をクリックします。

  2. [Atlas Search] タブをクリックします。

    Atlas Searchページが表示されます。

3

クエリするインデックスの右側にある [ Query ] ボタンをクリックします。

4

Edit Queryをクリックすると、 JSON形式のデフォルトのクエリ構文サンプルが表示されます。

5

次のクエリをコピーして、 Query Editorに貼り付け、 Query EditorSearchボタンをクリックします。

次の例では、サブクエリとともにcompound演算子を使用して、 titleフィールドにsnowというタームを含む、 2013から2015年の間の映画を検索します。

以下のクエリでは、

  • 次のcompound演算子句を使用します。

    • filter 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

    • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 constantオプションを使用してscoreを変更します。 constantオプションは、検索タームのすべてのスコア結果を5に置き換えます。

  • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

[
{
$search: {
index: "compound-query-custom-score-tutorial",
compound: {
filter: [{
range: {
path: "year",
gte: 2013,
lte: 2015
}
}],
should: [{
text: {
query: "snow",
path: "title",
score: {constant: {value: 5}}
}
}]
},
highlight:{
path: "title"
}
}
}
]
SCORE: 5 _id: "573a13d7f29313caabda38ad"
Snow in Paradise
Matching fields: title
SCORE: 5 _id: "573a13e2f29313caabdbeded"
Dead Snow 2: red vs.
Matching fields: title
SCORE: 5 _id: "573a13e6f29313caabdc66c4"
The Snow White Murder Case
Matching fields: title
SCORE: 5 _id: "573a13edf29313caabdd37bd"
Snow on the Blades
Matching fields: title
SCORE: 0 _id: "573a13acf29313caabd29366"
No highlights found.
Matching fields: unknown
SCORE: 0 _id: "573a13adf29313caabd2b765"
No highlights found.
Matching fields: unknown
SCORE: 0 _id: "573a13b0f29313caabd333e7"
No highlights found.
Matching fields: unknown
SCORE: 0 _id: "573a13b0f29313caabd3486a"
No highlights found.
Matching fields: unknown
SCORE: 0 _id: "573a13b1f29313caabd3719d"
No highlights found.
Matching fields: unknown
SCORE: 0 _id: "573a13b2f29313caabd3abb9"
No highlights found.
Matching fields: unknown

結果の最初の 4 つのドキュメントは、クエリのshould句によって、タイトルがsnowを持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should句は、 constantオプションを使用して、クエリ タームsnowのスコアも変更します。

以下のクエリでは、

  • 次のcompound演算子句を使用します。

    • must 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

    • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 boostオプションを使用してscoreを変更します。 boostオプションは、検索タームの結果の基本スコアに2を乗じます。

  • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

[
{
$search: {
index: "compound-query-custom-score-tutorial",
compound: {
must: [{
range: {
path: "year",
gte: 2013,
lte: 2015
}
}],
should: [{
text: {
query: "snow",
path: "title",
score: {boost: {value: 2}}
}
}]
},
highlight:{
path: "title"
}
}
}
]
SCORE: 6.7722930908203125 _id: "573a13d7f29313caabda38ad"
Snow in Paradise
Matching fields: title
SCORE: 6.063445568084717 _id: "573a13edf29313caabdd37bd"
Snow on the Blades
Matching fields: title
SCORE: 5.509652137756348 _id: "573a13e6f29313caabdc66c4"
The Snow White Murder Case
Matching fields: title
SCORE: 5.065053939819336 _id: "573a13e2f29313caabdbeded"
Dead Snow 2: Red vs.
Matching fields: title
SCORE: 1 _id: "573a13acf29313caabd29366"
No highlights found.
Matching fields: unknown
SCORE: 1 _id: "573a13adf29313caabd2b765"
No highlights found.
Matching fields: unknown
SCORE: 1 _id: "573a13b0f29313caabd333e7"
No highlights found.
Matching fields: unknown
SCORE: 1 _id: "573a13b0f29313caabd3486a"
No highlights found.
Matching fields: unknown
SCORE: 1 _id: "573a13b1f29313caabd3719d"
No highlights found.
Matching fields: unknown
SCORE: 1 _id: "573a13b2f29313caabd3abb9"
No highlights found.
Matching fields: unknown

結果の最初の 4 つのドキュメントは、クエリのshould句によって、タイトルがsnowを持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should句は、 boostオプションを使用して、クエリ タームsnowのスコアも変更します。

以下のクエリでは、

  • 次のcompound演算子句をboostオプションとともに使用して、一部のフィールドを他のフィールドよりも優先するようにします。

    • must 句をテキスト演算子とともに使用すると、ジャンルcomedyが最も優先度が高く、その後にtitleフィールドの用語snowが優先されます。 boostオプションはフィールドに重みを適用します。

    • should 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

    注意

    boostオプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。

[
{
$search: {
index: "compound-query-custom-score-tutorial",
compound: {
must: [{
text: {
query: "comedy",
path: "genres",
score: {boost: {value: 9}}
}
},
{
text: {
query: "snow",
path: "title",
score: {boost: {value: 5}}
}
}],
should: [{
range: {
path: "year",
gte: 2013,
lte: 2015,
score: {boost: {value: 3}}
}
}]
}
}
}
]
SCORE: 21.872983932495117 _id: "573a13c2f29313caabd6874c"
plot: "A ski vacation turns horrific for a group of medical students, as they…"
genres: Array
runtime: 91
SCORE: 21.043487548828125 _id: "573a139ff29313caabcffff8"
fullplot: "When an entire town in upstate New York is closed down by an unexpecte…"
imdb: Object
year: 2000
SCORE: 21.043487548828125 _id: "573a13a6f29313caabd16b02"
plot: "When a Miami dentist inherits a team of sled dogs, he's got to learn t…"
genres: Array
runtime: 99
SCORE: 19.523927688598633 _id: "573a13a1f29313caabd06765"
fullplot: "Our two young lovers meet on a series of snowy days in high school. Ye…"
imdb: Object
runtime: 1999
SCORE: 17.426334381103516 _id: "573a13e2f29313caabdbeded"
plot: "Still on the run from a group of Nazi zombies, a man seeks the aid of …"
genres: Array
runtime: 100
SCORE: 16.367326736450195 _id: "573a13c2f29313caabd6688e"
countries: Array
genres: Array
runtime: 108
SCORE: 15.537829399108887 _id: "573a13b1f29313caabd36d7d"
plot: "A love-struck Italian poet is stuck in Iraq at the onset of an America…"
genres: Array
runtime: 110
SCORE: 14.4263334274292 _id: "573a1395f29313caabce1925"
plot: "An ice-skating Snow White finds refuge from the Wicked Queen with the …"
genres: Array
runtime: 107

以下のクエリでは、

  • 次のcompound演算子句を使用します。

    • must 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

    • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 functionオプションを使用してscoreを変更します。 functionオプションは、算術式を使用して以下を追加します。

      • 検索タームのクエリの関連性スコア

      • imdb.ratingという名前の数値フィールドの値、またはimdb.ratingフィールドがないドキュメントの数値2

  • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

[
{
$search: {
index: "compound-query-custom-score-tutorial",
compound: {
must: [{
range: {
path: "year",
gte: 2013,
lte: 2015,
}
}],
should: [{
text: {
query: "snow",
path: "title",
score: {
function: {
add: [{
path: {
value: "imdb.rating",
undefined: 2
}
},
{
score: "relevance"
}]
}
}
}
}]
},
highlight: {
path: "title"
}
}
}
]
SCORE: 10.454826354980469 _id: "573a13e6f29313caabdc66c4"
The Snow White Murder Case
Matching fields: title
SCORE: 10.3317232131958 _id: "573a13edf29313caabdd37bd"
Snow on the Blades
Matching fields: title
SCORE: 10.032526969909668 _id: "573a13e2f29313caabdbeded"
Dead Snow 2: Red vs.
Matching fields: title
SCORE: 8.386146545410156 _id: "573a13d7f29313caabda38ad"
Snow in Paradise
Matching fields: title
SCORE: 1 _id: "573a13acf29313caabd29366"
No highlights found.
Matching fields: unknown
SCORE: 1 _id: "573a13adf29313caabd2b765"
No highlights found.
Matching fields: unknown
SCORE: 1 _id: "573a13b0f29313caabd333e7"
No highlights found.
Matching fields: unknown
SCORE: 1 _id: "573a13b0f29313caabd3486a"
No highlights found.
Matching fields: unknown
SCORE: 1 _id: "573a13b1f29313caabd3719d"
No highlights found.
Matching fields: unknown
SCORE: 1 _id: "573a13b2f29313caabd3abb9"
No highlights found.
Matching fields: unknown

結果の最初の 4 つのドキュメントは、クエリのshould句によって、タイトルがsnowを持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should句は、 functionオプションを使用して、クエリ タームsnowのスコアも変更します。

6

Search Testerでは、返されるドキュメント内のすべてのフィールドが表示されない場合があります。 クエリパスで指定したフィールドを含むすべてのフィールドを表示するには、結果内のドキュメントを展開します。

1

ターミナル ウィンドウでmongoshを開き、クラスターに接続します。 接続の詳細な手順については、「 mongosh経由での接続 」を参照してください。

2

mongoshプロンプトで次のコマンドを実行します。

use sample_mflix
3

次の例では、サブクエリとともにcompound演算子を使用して、 titleフィールドにsnowというタームを含む、 2013から2015年の間の映画を検索します。

このクエリでは、次のパイプライン ステージを使用します。

  • $search コレクションをクエリします。 クエリでは以下の操作が実行されます。

    • 次のcompound演算子句を使用します。

      • filter 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

      • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 constantオプションを使用してscoreを変更します。 constantオプションは、検索タームのすべてのスコア結果を5に置き換えます。

    • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

  • $limitステージを使用して、出力を10の結果に制限します。

  • $project stageを次のように設定します。

    • titleyearを除くすべてのフィールドを除外

    • scoreフィールドを追加する

db.movies.aggregate([
{
"$search": {
"index": "compound-query-custom-score-tutorial",
"compound": {
"filter": [{
"range": {
"path": "year",
"gte": 2013,
"lte": 2015
}
}],
"should": [{
"text": {
"query": "snow",
"path": "title",
"score": {"constant": {"value": 5}}
}
}]
},
"highlight": {
"path": "title"
}
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1,
"year": 1,
"score": { "$meta": "searchScore" },
"highlights": { "$meta": "searchHighlights" }
}
}
])

Atlas Search により、 constantについて次の結果が返されます。

[
{
title: 'Snow in Paradise',
year: 2014,
score: 5,
highlights: [
{
score: 1.382846713066101,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' in Paradise', type: 'text' }
]
}
]
},
{
title: 'Dead Snow 2: Red vs. Dead',
year: 2014,
score: 5,
highlights: [
{
score: 1.3924485445022583,
path: 'title',
texts: [
{ value: 'Dead ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' 2: Red vs. ', type: 'text' }
]
}
]
},
{
title: 'The Snow White Murder Case',
year: 2014,
score: 5,
highlights: [
{
score: 1.3525336980819702,
path: 'title',
texts: [
{ value: 'The ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' White Murder Case', type: 'text' }
]
}
]
},
{
title: 'Snow on the Blades',
year: 2014,
score: 5,
highlights: [
{
score: 1.3766303062438965,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' on the Blades', type: 'text' }
]
}
]
},
{ year: 2013, title: 'The Secret Life of Walter Mitty', score: 0, highlights: [] },
{ title: 'Jurassic World', year: 2015, score: 0, highlights: [] },
{ title: 'Action Jackson', year: 2014, score: 0, highlights: [] },
{ year: 2013, title: 'In Secret', score: 0, highlights: [] },
{ title: 'The Stanford Prison Experiment', year: 2015, score: 0, highlights: [] },
{ year: 2014, title: 'The Giver', score: 0, highlights: [] }
]

結果の最初の 4 つのドキュメントは、クエリのshould句によって、タイトルがsnowを持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should句は、 constantオプションを使用して、クエリ タームsnowのスコアも変更します。

このクエリでは、次のパイプライン ステージを使用します。

  • $search コレクションをクエリします。 クエリでは以下の操作が実行されます。

    • 次のcompound演算子句を使用します。

      • must 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

      • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 boostオプションを使用してscoreを変更します。 boostオプションは、検索タームの結果の基本スコアに2を乗じます。

    • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

  • $limitステージを使用して、出力を10の結果に制限します。

  • $project stageを次のように設定します。

    • titleyearを除くすべてのフィールドを除外

    • scoreフィールドを追加する

db.movies.aggregate([
{
"$search": {
"index": "compound-query-custom-score-tutorial",
"compound": {
"must": [{
"range": {
"path": "year",
"gte": 2013,
"lte": 2015
}
}],
"should": [{
"text": {
"query": "snow",
"path": "title",
"score": {"boost": {"value": 2}}
}
}]
},
"highlight": {
"path": "title"
}
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1,
"year": 1,
"score": { "$meta": "searchScore" },
"highlights": { "$meta": "searchHighlights" }
}
}
])

Atlas Search により、 boostについて次の結果が返されます。

[
{
title: 'Snow in Paradise',
year: 2014,
score: 6.7722930908203125,
highlights: [
{
score: 1.382846713066101,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' in Paradise', type: 'text' }
]
}
]
},
{
title: 'Snow on the Blades',
year: 2014,
score: 6.063445568084717,
highlights: [
{
score: 1.3766303062438965,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' on the Blades', type: 'text' }
]
}
]
},
{
title: 'The Snow White Murder Case',
year: 2014,
score: 5.509652137756348,
highlights: [
{
score: 1.3525336980819702,
path: 'title',
texts: [
{ value: 'The ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' White Murder Case', type: 'text' }
]
}
]
},
{
title: 'Dead Snow 2: Red vs. Dead',
year: 2014,
score: 5.065053939819336,
highlights: [
{
score: 1.3924485445022583,
path: 'title',
texts: [
{ value: 'Dead ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' 2: Red vs. ', type: 'text' }
]
}
]
},
{ year: 2013, title: 'The Secret Life of Walter Mitty', score: 1, highlights: [] },
{ title: 'Jurassic World', year: 2015, score: 1, highlights: [] },
{ title: 'Action Jackson', year: 2014, score: 1, highlights: [] },
{ year: 2013, title: 'In Secret', score: 1, highlights: [] },
{ title: 'The Stanford Prison Experiment', year: 2015, score: 1, highlights: [] },
{ year: 2014, title: 'The Giver', score: 1, highlights: [] }
]

結果の最初の 4 つのドキュメントは、クエリのshould句によって、タイトルがsnowを持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should句は、 boostオプションを使用して、クエリ タームsnowのスコアも変更します。

このクエリでは、次のパイプライン ステージを使用します。

  • $searchを使用してコレクションをクエリします。 クエリでは、次のcompound演算子句をboostオプションとともに使用して、一部のフィールドを他のフィールドよりも優先してください。

    • must 句をテキスト演算子とともに使用すると、ジャンルcomedyが最も優先度が高く、その後にtitleフィールドの用語snowが優先されます。 boostオプションはフィールドに重みを適用します。

    • should 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

    注意

    boostオプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。

  • $limitステージを使用して、出力を10の結果に制限します。

  • $project stageを次のように設定します。

    • すべてのフィールドを除外titleyeargenres

    • scoreフィールドを追加する

db.movies.aggregate([
{
"$search": {
"index": "compound-query-custom-score-tutorial",
"compound": {
"must": [{
"text": {
"path": "genres",
"query": "comedy",
"score": {"boost": {"value": 9}}
}
},
{
"text": {
"path": "title",
"query": "snow",
"score": {"boost": {"value": 5}}
}
}],
"should": [{
"range": {
"path": "year",
"gte": 2013,
"lte": 2015,
"score": {"boost": {"value": 3}}
}
}]
}
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1,
"year": 1,
"genres": 1,
"score": { "$meta": "searchScore" }
}
}
])
[
{
genres: [ 'Comedy', 'Horror' ],
title: 'Dead Snow',
year: 2009,
score: 21.872983932495117
},
{
year: 2000,
genres: [ 'Adventure', 'Comedy', 'Family' ],
title: 'Snow Day',
score: 21.043487548828125
},
{
genres: [ 'Adventure', 'Comedy', 'Family' ],
title: 'Snow Dogs',
year: 2002,
score: 21.043487548828125
},
{
year: 1999,
genres: [ 'Comedy', 'Romance' ],
title: 'Let It Snow',
score: 19.523927688598633
},
{
genres: [ 'Action', 'Comedy', 'Horror' ],
title: 'Dead Snow 2: Red vs. Dead',
year: 2014,
score: 17.426334381103516
},
{
genres: [ 'Comedy', 'Drama' ],
title: 'Snow White and Russian Red',
year: 2009,
score: 16.367326736450195
},
{
genres: [ 'Comedy', 'Drama', 'Romance' ],
title: 'The Tiger and the Snow',
year: 2005,
score: 15.537829399108887
},
{
genres: [ 'Adventure', 'Comedy', 'Family' ],
title: 'Snow White and the Three Stooges',
year: 1961,
score: 14.4263334274292
}
]

このクエリでは、次のパイプライン ステージを使用します。

  • $search コレクションをクエリします。 クエリでは以下の操作が実行されます。

    • 次のcompound演算子句を使用します。

      • must 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

      • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 functionオプションを使用してscoreを変更します。 functionオプションは、算術式を使用して以下を追加します。

        • 検索タームのクエリの関連性スコア

        • imdb.ratingという名前の数値フィールドの値、またはimdb.ratingフィールドがないドキュメントの数値2

    • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

  • $limitステージを使用して、出力を10の結果に制限します。

  • $project stageを次のように設定します。

    • titleyearを除くすべてのフィールドを除外

    • scoreフィールドを追加する

db.movies.aggregate([
{
"$search": {
"index": "compound-query-custom-score-tutorial",
"compound": {
"must": [{
"range": {
"path": "year",
"gte": 2013,
"lte": 2015
}
}],
"should": [{
"text": {
"query": "snow",
"path": "title",
"score": {
"function": {
"add": [{
"path": {
"value": "imdb.rating",
"undefined": 2
}
},
{
"score": "relevance"
}]
}
}
}
}]
},
"highlight": {
"path": "title"
}
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1,
"year": 1,
"score": { "$meta": "searchScore" },
"highlights": { "$meta": "searchHighlights" }
}
}
])

Atlas Search により、 functionについて次の結果が返されます。

[
{
title: 'The Snow White Murder Case',
year: 2014,
score: 10.454826354980469,
highlights: [
{
score: 1.3525336980819702,
path: 'title',
texts: [
{ value: 'The ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' White Murder Case', type: 'text' }
]
}
]
},
{
title: 'Snow on the Blades',
year: 2014,
score: 10.3317232131958,
highlights: [
{
score: 1.3766303062438965,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' on the Blades', type: 'text' }
]
}
]
},
{
title: 'Dead Snow 2: Red vs. Dead',
year: 2014,
score: 10.032526969909668,
highlights: [
{
score: 1.3924485445022583,
path: 'title',
texts: [
{ value: 'Dead ', type: 'text' },
{ value: 'Snow', type: 'hit' },
{ value: ' 2: Red vs. ', type: 'text' }
]
}
]
},
{
title: 'Snow in Paradise',
year: 2014,
score: 8.386146545410156,
highlights: [
{
score: 1.382846713066101,
path: 'title',
texts: [
{ value: 'Snow', type: 'hit' },
{ value: ' in Paradise', type: 'text' }
]
}
]
},
{ year: 2013, title: 'The Secret Life of Walter Mitty', score: 1, highlights: [] },
{ title: 'Jurassic World', year: 2015, score: 1, highlights: [] },
{ title: 'Action Jackson', year: 2014, score: 1, highlights: [] },
{ year: 2013, title: 'In Secret', score: 1, highlights: [] },
{ title: 'The Stanford Prison Experiment', year: 2015, score: 1, highlights: [] },
{ year: 2014, title: 'The Giver', score: 1, highlights: [] }
]

結果の最初の 4 つのドキュメントは、クエリのshould句によって、タイトルがsnowを持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should句は、 functionオプションを使用して、クエリ タームsnowのスコアも変更します。

1

MongoDB Compass を開き、クラスターに接続します。 接続の詳細な手順については、「 Compass 経由での接続 」を参照してください。

2

Database画面で、 sample_mflixデータベースをクリックし、 moviesコレクションをクリックします。

3

クエリは、次のタスクを実行します。

  • 次のcompound演算子句を使用します。

    • filter 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

    • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 constantオプションを使用してscoreを変更します。 constantオプションは、検索タームのすべてのスコア結果を5に置き換えます。

  • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

  • 次のパイプライン ステージを使用します。

    • 出力を10の結果に制限する$limitステージ

    • $projectステージから次の操作へ。

      • titleyearを除くすべてのフィールドを除外

      • scorehighlightsという名前の 2 つのフィールドを追加します

MongoDB Compass でこのクエリを実行するには:

  1. [Aggregations] タブをクリックします。

  2. Select...をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプライン ステージを構成します。 ステージを追加するには、 Add Stageをクリックします。

    パイプラインステージ
    クエリ

    $search

    {
    "index": "compound-query-custom-score-tutorial",
    "compound": {
    "filter": [{
    "range": {
    "path": "year",
    "gte": 2013,
    "lte": 2015
    }
    }],
    "should": [{
    "text": {
    "query": "snow",
    "path": "title",
    "score": {"constant": {"value": 5}}
    }
    }]
    },
    "highlight": { "path": "title" }
    }

    $limit

    10

    $project

    {
    "_id": 0,
    "title": 1,
    "year": 1,
    "score": { "$meta": "searchScore" },
    "highlights": { "$meta": "searchHighlights" }
    }

    Auto Preview有効にした場合、MongoDB Compass は$projectパイプライン ステージの横に次のドキュメントを表示します。

    {
    title: 'Snow in Paradise',
    year: 2014,
    score: 5,
    highlights: [{
    score: 1.382846713066101,
    path: 'title',
    texts: [
    { value: 'Snow', type: 'hit' },
    { value: ' in Paradise', type: 'text' }
    ]
    }]
    },
    {
    title: 'Dead Snow 2: Red vs. Dead',
    year: 2014,
    score: 5,
    highlights: [{
    score: 1.3924485445022583,
    path: 'title',
    texts: [
    { value: 'Dead ', type: 'text' },
    { value: 'Snow', type: 'hit' },
    { value: ' 2: Red vs. ', type: 'text' }
    ]
    }]
    },
    {
    title: 'The Snow White Murder Case',
    year: 2014,
    score: 5,
    highlights: [{
    score: 1.3525336980819702,
    path: 'title',
    texts: [
    { value: 'The ', type: 'text' },
    { value: 'Snow', type: 'hit' },
    { value: ' White Murder Case', type: 'text' }
    ]
    }]
    },
    {
    title: 'Snow on the Blades',
    year: 2014,
    score: 5,
    highlights: [{
    score: 1.3766303062438965,
    path: 'title',
    texts: [
    { value: 'Snow', type: 'hit' },
    { value: ' on the Blades', type: 'text' }
    ]
    }]
    },
    { year: 2013, title: 'The Secret Life of Walter Mitty', score: 0, highlights: [] },
    { title: 'Jurassic World', year: 2015, score: 0, highlights: [] },
    { title: 'Action Jackson', year: 2014, score: 0, highlights: [] },
    { year: 2013, title: 'In Secret', score: 0, highlights: [] },
    { title: 'The Stanford Prison Experiment', year: 2015, score: 0, highlights: [] },
    { year: 2014, title: 'The Giver', score: 0, highlights: [] }

    結果の最初の 4 つのドキュメントは、クエリのshould句によって、タイトルがsnowを持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should句は、 constantオプションを使用して、クエリ タームsnowのスコアも変更します。

4
  1. [Aggregations] タブをクリックします。

  2. Select...をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプライン ステージを構成します。 ステージを追加するには、 Add Stageをクリックします。

    クエリは、次のパイプライン ステージを使用します。

    • $search 次のタスクを実行する必要があります。

      • 次のcompound演算子句を使用するクエリ。

        • must 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

        • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 boostオプションを使用してscoreを変更します。 boostオプションは、検索タームの結果の基本スコアに2を乗じます。

      • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

    • 出力を10の結果に制限する$limitステージ

    • $projectステージから次の操作へ。

      • titleyearを除くすべてのフィールドを除外

      • scorehighlightsという名前の 2 つのフィールドを追加します

    パイプラインステージ
    クエリ

    $search

    {
    "index": "compound-query-custom-score-tutorial",
    "compound": {
    "must": [{
    "range": {
    "path": "year",
    "gte": 2013,
    "lte": 2015
    }
    }],
    "should": [{
    "text": {
    "query": "snow",
    "path": "title",
    "score": {"boost": {"value": 2}}
    }
    }]
    },
    "highlight": { "path": "title" }
    }

    $limit

    10

    $project

    {
    "_id": 0,
    "title": 1,
    "year": 1,
    "score": { "$meta": "searchScore" },
    "highlights": { "$meta": "searchHighlights" }
    }

    このクエリでは、次のパイプライン ステージを使用します。

    • $search 次のタスクを実行する必要があります。

      • boostオプションとともにcompound演算子句を使用して、一部のフィールドを他のフィールドよりも優先するクエリ。

        • must 句をテキスト演算子とともに使用すると、ジャンルcomedyが最も優先度が高く、その後にtitleフィールドの用語snowが優先されます。 boostオプションはフィールドに重みを適用します。

        • should 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

        注意

        boostオプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。

    • 出力を10の結果に制限する$limitステージ

    • $projectステージから次の操作へ。

      • titleyearを除くすべてのフィールドを除外

      • scorehighlightsという名前の 2 つのフィールドを追加します

    • must 句をテキスト演算子とともに使用すると、ジャンルcomedyが最も優先度が高く、その後にtitleフィールドの用語snowが優先されます。 boostオプションはフィールドに重みを適用します。

    • should 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

    注意

    boostオプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。

    パイプラインステージ
    クエリ

    $search

    {
    "index": "compound-query-custom-score-tutorial",
    "compound": {
    "must": [{
    "text": {
    "path": "genres",
    "query": "comedy",
    "score": {"boost": {"value": 9}}
    }
    },
    {
    "text": {
    "path": "title",
    "query": "snow",
    "score": {"boost": {"value": 5}}
    }
    }],
    "should": [{
    "range": {
    "path": "year",
    "gte": 2013,
    "lte": 2015,
    "score": {"boost": {"value": 3}}
    }
    }]
    }
    }

    $limit

    10

    $project

    {
    "_id": 0,
    "title": 1,
    "year": 1,
    "genres": 1,
    "score": { "$meta": "searchScore" }
    }

    Auto Preview有効にした場合、MongoDB Compass は$projectパイプライン ステージの横に次のドキュメントを表示します。

    {
    title: 'Snow in Paradise',
    year: 2014,
    score: 6.7722930908203125,
    highlights: [{
    score: 1.382846713066101,
    path: 'title',
    texts: [
    { value: 'Snow', type: 'hit' },
    { value: ' in Paradise', type: 'text' }
    ]
    }]
    },
    {
    title: 'Snow on the Blades',
    year: 2014,
    score: 6.063445568084717,
    highlights: [{
    score: 1.3766303062438965,
    path: 'title',
    texts: [
    { value: 'Snow', type: 'hit' },
    { value: ' on the Blades', type: 'text' }
    ]
    }]
    },
    {
    title: 'The Snow White Murder Case',
    year: 2014,
    score: 5.509652137756348,
    highlights: [{
    score: 1.3525336980819702,
    path: 'title',
    texts: [
    { value: 'The ', type: 'text' },
    { value: 'Snow', type: 'hit' },
    { value: ' White Murder Case', type: 'text' }
    ]
    }]
    },
    {
    title: 'Dead Snow 2: Red vs. Dead',
    year: 2014,
    score: 5.065053939819336,
    highlights: [{
    score: 1.3924485445022583,
    path: 'title',
    texts: [
    { value: 'Dead ', type: 'text' },
    { value: 'Snow', type: 'hit' },
    { value: ' 2: Red vs. ', type: 'text' }
    ]
    }]
    },
    { year: 2013, title: 'The Secret Life of Walter Mitty',score: 1, highlights: [] },
    { title: 'Jurassic World', year: 2015, score: 1, highlights: [] },
    { title: 'Action Jackson', year: 2014, score: 1, highlights: [] },
    { year: 2013, title: 'In Secret', score: 1, highlights: [] },
    { title: 'The Stanford Prison Experiment', year: 2015, score: 1, highlights: [] },
    { year: 2014, title: 'The Giver', score: 1, highlights: [] }

    結果の最初の 4 つのドキュメントは、クエリのshould句によって、タイトルがsnowを持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should句は、 boostオプションを使用して、クエリ タームsnowのスコアも変更します。

    [
    {
    genres: [ 'Comedy', 'Horror' ],
    title: 'Dead Snow',
    year: 2009,
    score: 21.872983932495117
    },
    {
    year: 2000,
    genres: [ 'Adventure', 'Comedy', 'Family' ],
    title: 'Snow Day',
    score: 21.043487548828125
    },
    {
    genres: [ 'Adventure', 'Comedy', 'Family' ],
    title: 'Snow Dogs',
    year: 2002,
    score: 21.043487548828125
    },
    {
    year: 1999,
    genres: [ 'Comedy', 'Romance' ],
    title: 'Let It Snow',
    score: 19.523927688598633
    },
    {
    genres: [ 'Action', 'Comedy', 'Horror' ],
    title: 'Dead Snow 2: Red vs. Dead',
    year: 2014,
    score: 17.426334381103516
    },
    {
    genres: [ 'Comedy', 'Drama' ],
    title: 'Snow White and Russian Red',
    year: 2009,
    score: 16.367326736450195
    },
    {
    genres: [ 'Comedy', 'Drama', 'Romance' ],
    title: 'The Tiger and the Snow',
    year: 2005,
    score: 15.537829399108887
    },
    {
    genres: [ 'Adventure', 'Comedy', 'Family' ],
    title: 'Snow White and the Three Stooges',
    year: 1961,
    score: 14.4263334274292
    }
    ]
5

クエリは、次のパイプライン ステージを使用します。

  • $search ステージでは、次のタスクを実行します。

    • 次のcompound演算子句を使用するクエリ。

      • must 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

      • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 functionオプションを使用してscoreを変更します。 functionオプションは、算術式を使用して以下を追加します。

        • 検索タームのクエリの関連性スコア

        • imdb.ratingという名前の数値フィールドの値、またはimdb.ratingフィールドがないドキュメントの数値2

    • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

  • 出力を10の結果に制限する$limitステージ

  • $projectステージから次の操作へ。

    • titleyearを除くすべてのフィールドを除外

    • scorehighlightsという名前の 2 つのフィールドを追加します

MongoDB Compass でこのクエリを実行するには:

  1. [Aggregations] タブをクリックします。

  2. Select...をクリックし、ドロップダウンからステージを選択し、そのステージのクエリを追加して、次の各パイプライン ステージを構成します。 ステージを追加するには、 Add Stageをクリックします。

    パイプラインステージ
    クエリ

    $search

    {
    "index": "compound-query-custom-score-tutorial",
    "compound": {
    "must": [{
    "range": {
    "path": "year",
    "gte": 2013,
    "lte": 2015
    }
    }],
    "should": [{
    "text": {
    "query": "snow",
    "path": "title",
    "score": {
    "function": {
    "add": [{
    "path": {
    "value": "imdb.rating",
    "undefined": 2
    }
    },
    {
    "score": "relevance"
    }]
    }
    }
    }
    }]},
    "highlight":{ "path": "title" }
    }

    $limit

    10

    $project

    {
    "_id": 0,
    "title": 1,
    "year": 1,
    "score": { "$meta": "searchScore" },
    "highlights": { "$meta": "searchHighlights" }
    }

    Auto Preview有効にした場合、MongoDB Compass は$projectパイプライン ステージの横に次のドキュメントを表示します。

    {
    title: 'The Snow White Murder Case',
    year: 2014,
    score: 10.454826354980469,
    highlights: [{
    score: 1.3525336980819702,
    path: 'title',
    texts: [
    { value: 'The ', type: 'text' },
    { value: 'Snow', type: 'hit' },
    { value: ' White Murder Case', type: 'text' }
    ]
    }]
    },
    {
    title: 'Snow on the Blades',
    year: 2014,
    score: 10.3317232131958,
    highlights: [{
    score: 1.3766303062438965,
    path: 'title',
    texts: [
    { value: 'Snow', type: 'hit' },
    { value: ' on the Blades', type: 'text' }
    ]
    }]
    },
    {
    title: 'Dead Snow 2: Red vs. Dead',
    year: 2014,
    score: 10.032526969909668,
    highlights: [{
    score: 1.3924485445022583,
    path: 'title',
    texts: [
    { value: 'Dead ', type: 'text' },
    { value: 'Snow', type: 'hit' },
    { value: ' 2: Red vs. ', type: 'text' }
    ]
    }]
    },
    {
    title: 'Snow in Paradise',
    year: 2014,
    score: 8.386146545410156,
    highlights: [{
    score: 1.382846713066101,
    path: 'title',
    texts: [
    { value: 'Snow', type: 'hit' },
    { value: ' in Paradise', type: 'text' }
    ]
    }]
    },
    { year: 2013, title: 'The Secret Life of Walter Mitty', score: 1, highlights: [] },
    { title: 'Jurassic World', year: 2015, score: 1, highlights: [] },
    { title: 'Action Jackson', year: 2014, score: 1, highlights: [] },
    { year: 2013, title: 'In Secret', score: 1, highlights: [] },
    { title: 'The Stanford Prison Experiment', year: 2015, score: 1, highlights: [] },
    { year: 2014, title: 'The Giver', score: 1, highlights: [] }

    結果の最初の 4 つのドキュメントは、クエリのshould句によって、タイトルがsnowを持つドキュメントの優先順位が指定されているため、スコアが高くなります。 should句は、 functionオプションを使用して、クエリ タームsnowのスコアも変更します。

1
  1. compound-constant-example という新しいディレクトリを作成し、dotnet new コマンドでプロジェクトを初期化します。

    mkdir compound-constant-example
    cd compound-constant-example
    dotnet new console
  2. .NET/C# ドライバーを依存関係としてプロジェクトに追加します。

    dotnet add package MongoDB.Driver
  3. Program.cs ファイルの内容を、次のコードで置き換えます。

    このコード例では、次のタスクを実行します。

    • mongodb パッケージと依存関係をインポートします。

    • Atlas クラスターへの接続を確立します。

    • 次の複合句を使用して、コレクションをクエリします。

      • filter 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

      • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 constantオプションを使用してscoreを変更します。 constantオプションは、検索タームのすべてのスコア結果を5に置き換えます。

    • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

    • 次のパイプライン ステージを使用します。

      • 出力を10の結果に制限する$limitステージ

      • $projectステージから次の操作へ。

        • titleyearを除くすべてのフィールドを除外

        • scorehighlightsという名前の 2 つのフィールドを追加します

    • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundConstantExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // define and run pipeline
    23 var results = moviesCollection.Aggregate()
    24 .Search(Builders<MovieDocument>.Search.Compound()
    25 .Filter(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015)))
    26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Constant(5))),
    27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title),
    28 indexName: "compound-query-custom-score-tutorial")
    29 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    30 .Include(movie => movie.Title)
    31 .Include(movie => movie.Year)
    32 .Exclude(movie => movie.Id)
    33 .MetaSearchScore(movie => movie.Score)
    34 .MetaSearchHighlights("highlights"))
    35 .Limit(10)
    36 .ToList();
    37
    38 // print results
    39 foreach (var movie in results)
    40 {
    41 Console.WriteLine(movie.ToJson());
    42 }
    43 }
    44}
    45
    46[BsonIgnoreExtraElements]
    47public class MovieDocument
    48{
    49 [BsonIgnoreIfDefault]
    50 public ObjectId Id { get; set; }
    51 public string Title { get; set; }
    52 public int Year { get; set; }
    53 [BsonElement("highlights")]
    54 public List<SearchHighlight> Highlights { get; set; }
    55 public double Score { get; set; }
    56}
  4. サンプルを実行する前に、<connection-string> をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。

  5. 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のスコアも変更します。

2
  1. compound-boost-example という新しいディレクトリを作成し、dotnet new コマンドでプロジェクトを初期化します。

    mkdir compound-boost-example
    cd compound-boost-example
    dotnet new console
  2. .NET/C# ドライバーを依存関係としてプロジェクトに追加します。

    dotnet add package MongoDB.Driver
  3. Program.cs ファイルの内容を、次のコードで置き換えます。

    このコード例では、次のタスクを実行します。

    • mongodb パッケージと依存関係をインポートします。

    • Atlas クラスターへの接続を確立します。

    • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

    クエリは、次のパイプライン ステージを使用します。

    • $search ステージを使用して、コレクションをクエリします。 クエリでは以下の操作が実行されます。

      • 次のcompound演算子句を使用します。

        • must 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

        • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 boostオプションを使用してscoreを変更します。 boostオプションは、検索タームの結果の基本スコアに2を乗じます。

      クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

    • 出力を10の結果に制限する$limitステージ

    • $projectステージから次の操作へ。

      • titleyearを除くすべてのフィールドを除外

      • scorehighlightsという名前の 2 つのフィールドを追加します

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundBoostSingleExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // define and run pipeline
    23 var results = moviesCollection.Aggregate()
    24 .Search(Builders<MovieDocument>.Search.Compound()
    25 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015)))
    26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(2))),
    27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title),
    28 indexName: "compound-query-custom-score-tutorial")
    29 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    30 .Include(movie => movie.Title)
    31 .Include(movie => movie.Year)
    32 .Exclude(movie => movie.Id)
    33 .MetaSearchScore(movie => movie.Score)
    34 .MetaSearchHighlights("highlights"))
    35 .Limit(10)
    36 .ToList();
    37
    38 // print results
    39 foreach (var movie in results)
    40 {
    41 Console.WriteLine(movie.ToJson());
    42 }
    43 }
    44}
    45
    46[BsonIgnoreExtraElements]
    47public class MovieDocument
    48{
    49 [BsonIgnoreIfDefault]
    50 public ObjectId Id { get; set; }
    51 public string Title { get; set; }
    52 public int Year { get; set; }
    53 [BsonElement("highlights")]
    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オプションは、フィールドにさまざまな重みを適用して、フィールドを優先します。

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundBoostMultipleExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // define and run pipeline
    23 var results = moviesCollection.Aggregate()
    24 .Search(Builders<MovieDocument>.Search.Compound()
    25 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "comedy", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(9)))
    26 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(5)))
    27 .Should(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015), score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(3))),
    28 indexName: "compound-query-custom-score-tutorial")
    29 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    30 .Include(movie => movie.Genres)
    31 .Include(movie => movie.Title)
    32 .Include(movie => movie.Year)
    33 .Exclude(movie => movie.Id)
    34 .MetaSearchScore(movie => movie.Score))
    35 .Limit(10)
    36 .ToList();
    37
    38 // print results
    39 foreach (var movie in results)
    40 {
    41 Console.WriteLine(movie.ToJson());
    42 }
    43 }
    44}
    45
    46[BsonIgnoreExtraElements]
    47public class MovieDocument
    48{
    49 [BsonIgnoreIfDefault]
    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}
  4. サンプルを実行する前に、<connection-string> をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。

  5. 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 }
3
  1. compound-function-example という新しいディレクトリを作成し、dotnet new コマンドでプロジェクトを初期化します。

    mkdir compound-function-example
    cd compound-function-example
    dotnet new console
  2. .NET/C# ドライバーを依存関係としてプロジェクトに追加します。

    dotnet add package MongoDB.Driver
  3. Program.cs ファイルの内容を、次のコードで置き換えます。

    このコード例では、次のタスクを実行します。

    • mongodb パッケージと依存関係をインポートします。

    • Atlas クラスターへの接続を確立します。

    • 次のパイプライン ステージを使用して、コレクションをクエリします。

      • must 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

      • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 functionオプションを使用してscoreを変更します。 functionオプションは、算術式を使用して以下を追加します。

        • 検索タームのクエリの関連性スコア

        • imdb.ratingという名前の数値フィールドの値、またはimdb.ratingフィールドがないドキュメントの数値2

    • 次のパイプライン ステージを使用します。

      • 出力を10の結果に制限する$limitステージ

      • $projectステージから次の操作へ。

        • titleyearを除くすべてのフィールドを除外

        • scorehighlightsという名前の 2 つのフィールドを追加します

    • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

    • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundFunctionExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 var scoreFunction = Builders<MovieDocument>.SearchScore.Function(Builders<MovieDocument>.SearchScoreFunction.Add(Builders<MovieDocument>.SearchScoreFunction.Path(movie => movie.Imdb.Rating, 2), Builders<MovieDocument>.SearchScoreFunction.Relevance()));
    23 // define and run pipeline
    24 var results = moviesCollection.Aggregate()
    25 .Search(Builders<MovieDocument>.Search.Compound()
    26 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015)))
    27 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: scoreFunction)),
    28 new SearchHighlightOptions<MovieDocument>(movie => movie.Title),
    29 indexName: "compound-query-custom-score-tutorial")
    30 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    31 .Include(movie => movie.Genres)
    32 .Include(movie => movie.Title)
    33 .Include(movie => movie.Year)
    34 .Exclude(movie => movie.Id)
    35 .MetaSearchScore(movie => movie.Score)
    36 .MetaSearchHighlights("highlights"))
    37 .Limit(10)
    38 .ToList();
    39
    40 // print results
    41 foreach (var movie in results)
    42 {
    43 Console.WriteLine(movie.ToJson());
    44 }
    45 }
    46}
    47
    48[BsonIgnoreExtraElements]
    49public class MovieDocument
    50{
    51 [BsonIgnoreIfDefault]
    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 [BsonElement("highlights")]
    58 public List<SearchHighlight> Highlights { get; set; }
    59 public double Score { get; set; }
    60}
    61
    62[BsonIgnoreExtraElements]
    63public class IMDB
    64{
    65 public double Rating { get; set; }
    66}
  4. サンプルを実行する前に、<connection-string> をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。

  5. 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のスコアも変更します。

1
  1. compound-constant-query.goという名前のファイルを作成します。

  2. コード例をコピーして、 compound-constant-query.goファイルに貼り付けます。

    このコード例では、次のタスクを実行します。

    • mongodb パッケージと依存関係をインポートします。

    • Atlas クラスターへの接続を確立します。

    • 次の複合句を使用して、コレクションをクエリします。

      • filter 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

      • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 constantオプションを使用してscoreを変更します。 constantオプションは、検索タームのすべてのスコア結果を5に置き換えます。

    • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

    • 次のパイプライン ステージを使用します。

      • 出力を10の結果に制限する$limitステージ

      • $projectステージから次の操作へ。

        • titleyearを除くすべてのフィールドを除外

        • scorehighlightsという名前の 2 つのフィールドを追加します

    • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13func main() {
    14 // connect to your Atlas cluster
    15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
    16 if err != nil {
    17 panic(err)
    18 }
    19 defer client.Disconnect(context.TODO())
    20
    21 // set namespace
    22 collection := client.Database("sample_mflix").Collection("movies")
    23
    24 // define pipeline stages
    25 searchStage := bson.D{{"$search", bson.M{
    26 "index": "compound-query-custom-score-tutorial",
    27 "compound": bson.M{
    28 "filter": bson.M{
    29 "range": bson.M{
    30 "path": "year", "gte": 2013, "lte": 2015,
    31 },
    32 },
    33 "should": bson.D{
    34 {"text", bson.M{
    35 "path": "title", "query": "snow", "score": bson.M{
    36 "constant": bson.D{{"value", 5}},
    37 }}}},
    38 },
    39 "highlight": bson.D{{"path", "title"}},
    40 }}}
    41 limitStage := bson.D{{"$limit", 10}}
    42 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}}
    43
    44 // specify the amount of time the operation can run on the server
    45 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    46
    47 // run pipeline
    48 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    49 if err != nil {
    50 panic(err)
    51 }
    52
    53 // print results
    54 var results []bson.D
    55 if err = cursor.All(context.TODO(), &results); err != nil {
    56 panic(err)
    57 }
    58 for _, result := range results {
    59 fmt.Println(result)
    60 }
    61}
  3. サンプルを実行する前に、<connection-string> をAtlas接続stringに置き換えます。 接続stringにデータベースユーザーの認証情報が含まれていることを確認します。 詳しくは、「ドライバーによる接続 」を参照してください。

  4. 次のコマンドを実行して、コレクションをクエリします。

    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のスコアも変更します。

2
  1. compound-boost-query.goという名前のファイルを作成します。

  2. コード例をコピーして、 compound-boost-query.goファイルに貼り付けます。

    コード例では、次のタスクを実行します。

    • mongodb パッケージと依存関係をインポートします。

    • Atlas クラスターへの接続を確立します。

    • カーソルを反復処理して、クエリに一致するドキュメントを出力します。

    クエリは、次のパイプライン ステージを使用します。

    • $search ステージを使用して、コレクションをクエリします。 クエリでは以下の操作が実行されます。

      • 次のcompound句を使用して、コレクションをクエリします。

        • must 句を範囲演算子とともに使用すると、 2013から2015年の間の映画が検索されます。

        • should 句をテキスト演算子とともに使用して、 titleフィールド内のsnowというタームをクエリし、 boostオプションを使用してscoreを変更します。 boostオプションは、検索タームの結果の基本スコアに2を乗じます。

      • クエリに一致するtitleフィールドからテキスト スニペットを返すには、ハイライトオプションを指定します。 スニペットには、 type: 'hit'で指定された一致するテキストと、 type: 'text'で指定された連続したテキストが含まれます。

    • 出力を10の結果に制限する$limitステージ

    • $projectステージから次の操作へ。

      • titleyearを除くすべてのフィールドを除外

      • scorehighlightsという名前の 2 つのフィールドを追加します

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13// define structure of movies collection
    14type MovieCollection struct {
    15 title string `bson:"Title,omitempty"`
    16}
    17
    18func main() {
    19