Docs 菜单
Docs 主页
/
MongoDB Atlas
/ /

如何使用加权字段运行 Atlas Search 复合查询

在此页面上

  • 使用动态映射创建 Atlas Search 索引
  • 运行复合查询
  • 运行复合查询以提升结果
  • 运行复合查询以隐藏结果
  • 继续学习

本教程演示了如何为搜索字段添加权重,以提升或隐藏结果或结果类别中的文档。它演示了如何将一个或多个值分配给字段,以返回得分较高或较低的结果。

具体而言,本教程演示了如何在 sample_mflix.movies 集合上创建具有动态映射的索引。它展示了如何使用 constantfunctionboost 运行复合查询并更改分数。它将引导您完成以下步骤:

  1. sample_mflix.movies集合设置具有动态映射的 Atlas Search 索引。

  2. 运行以下 Atlas Search 查询:

    • 查询 year 字段,并使用 title 字段中的特定单词更改分数,以提高文档在结果中的排名。

    • 查询 titleplot 字段,并根据 genres 字段中的特定类型更改分数,以隐藏该类型中的结果。

开始之前,请确保 Atlas 集群满足先决条件中所述的要求。

要创建 Atlas Search 索引,您必须拥有 Project Data Access Admin 或更高的项目访问权限。

在本部分中,我们将创建一个 Atlas Search 索引,该索引使用动态映射为 sample_mflix.movies 集合的字段编制索引。

1
  1. 如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果尚未出现,请单击侧边栏中的 Clusters(集群)。

    显示 集群页面。

2

您可以从侧边栏、 Data Explorer 或集群详细信息页面转到 Atlas Search 页面。

  1. 在侧边栏中,单击 Services 标题下的 Atlas Search

    注意

    如果您没有集群,请单击 Create cluster 来创建一个。如需了解详情,请参阅 创建集群。

  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

在页面上进行以下选择,然后单击 Next

Search Type

选择 Atlas Search 索引类型。

Index Name and Data Source

指定以下信息:

  • Index Name: compound-query-custom-score-tutorial

  • Database and Collection:

    • sample_mflix database

    • movies 集合

Configuration Method

For a guided experience, select Visual Editor.

To edit the raw index definition, select JSON Editor.
5

您可以创建使用动态映射静态映射的 Atlas Search 索引。要了解有关动态和静态映射的更多信息,请参阅静态和动态映射

以下索引定义对 movies 集合中的支持类型字段动态创建索引。您可以使用 Atlas Search Visual Editor 或 Atlas Search JSON Editor 在 Atlas 用户界面中创建索引。

查看 movies 集合的 "default" 索引定义。

  1. 查看索引定义。

    索引定义应类似于以下内容:

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

    上述索引定义对 movies 集合中每个文档中的支持类型字段动态创建索引。

  2. 单击 Next(连接)。

6
7

此时将显示一个模态窗口,让您知道索引正在构建中。点击 Close 按钮。

8

构建索引大约需要一分钟时间。在构建时,Status 列显示 Build in Progress。构建完成后,Status 列显示 Active

您可以使用复合操作符将两个或多个操作符组合成一个查询。Atlas Search 会根据相关性,按照从高分到低分的顺序,为查询返回的每个文档分配分数。这些查询演示了如何在结果中提升或隐藏文档。


➤ 使用选择语言下拉菜单设置本节中示例的语言。


提示

Atlas Search 提供一个包含指导的示例复合查询模板。要了解更多信息,请参阅查看查询指导模板

在本节中,您将连接到 Atlas 集群,并使用复合操作符针对 sample_mflix.movies 集合中的 titleyear 字段运行示例查询。示例查询使用自定义评分来更改 Atlas Search 对包含 snow 一词的电影标题返回的相关性分数。

1
  1. 如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。

  2. 如果尚未显示,请从导航栏的Projects菜单中选择所需的项目。

  3. 如果尚未出现,请单击侧边栏中的 Clusters(集群)。

    会显示集群页面。

2

您可以从侧边栏、 Data Explorer 或集群详细信息页面转到 Atlas Search 页面。

  1. 在侧边栏中,单击 Services 标题下的 Atlas Search

    注意

    如果您没有集群,请单击 Create cluster 来创建一个。如需了解详情,请参阅 创建集群。

  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 Editor 中的 Search 按钮。

以下示例使用带有子查询的 compound 操作符来搜索 20132015 年间且 title 字段中包含词语 snow 的电影。

以下查询:

  • 使用以下 compound 操作符子句:

    • filter 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

    • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 constant 选项更改 scoreconstant 选项将搜索词的所有得分结果替换为 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

结果中列出的前四个文档评分较高,因为查询中的 should 子句将标题中包含 snow 的文档指定为首选项。should 子句还使用 constant 选项更改了查询词 snow 的分数。

以下查询:

  • 使用以下 compound 操作符子句:

    • must 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

    • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 boost 选项更改 scoreboost 选项将搜索词结果中的基本分数乘以 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

结果中列出的前四个文档评分较高,因为查询中的 should 子句将标题中包含 snow 的文档指定为首选项。should 子句还使用 boost 选项更改了查询词 snow 的分数。

以下查询:

  • 将以下 compound 操作符子句与 boost 选项结合使用,使某些字段的优先级高于其他字段:

    • must文本操作符的子句优先考虑 comedy 类型,然后是 title 字段中的术语 snowboost 选项将权重应用于字段。

    • should 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

    注意

    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 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

    • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 function 选项更改 scorefunction 选项使用算术表达式添加以下内容:

      • 搜索词查询的相关性评分

      • 名为 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

结果中列出的前四个文档评分较高,因为查询中的 should 子句将标题中包含 snow 的文档指定为首选项。should 子句还使用 function 选项更改了查询词 snow 的分数。

6

Search Tester 可能不会显示其所返回文档的所有字段。要查看所有字段,包括在查询路径中指定的字段,请展开结果中的文档。

1

在终端窗口中打开mongosh并连接到集群。 有关连接的详细说明,请参阅通过mongosh连接。

2

mongosh 提示符下运行以下命令:

use sample_mflix
3

以下示例使用带有子查询的 compound 操作符来搜索 20132015 年间且 title 字段中包含词语 snow 的电影。

此查询使用以下管道阶段:

  • $search 来查询集合。查询:

    • 使用以下 compound 操作符子句:

      • filter 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

      • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 constant 选项更改 scoreconstant 选项将搜索词的所有得分结果替换为 5

    • 指定突出显示选项,从 title 字段返回与查询匹配的代码段。这些代码段包含使用 type: 'hit' 指定的匹配文本以及使用 type: 'text' 指定的相邻文本。

  • $limit 阶段将输出限制为 10 个结果。

  • $project 阶段到:

    • 排除 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: [] }
]

结果中列出的前四个文档评分较高,因为查询中的 should 子句将标题中包含 snow 的文档指定为首选项。should 子句还使用 constant 选项更改了查询词 snow 的分数。

此查询使用以下管道阶段:

  • $search 来查询集合。查询:

    • 使用以下 compound 操作符子句:

      • must 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

      • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 boost 选项更改 scoreboost 选项将搜索词结果中的基本分数乘以 2

    • 指定突出显示选项,从 title 字段返回与查询匹配的代码段。这些代码段包含使用 type: 'hit' 指定的匹配文本以及使用 type: 'text' 指定的相邻文本。

  • $limit 阶段将输出限制为 10 个结果。

  • $project 阶段到:

    • 排除 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: [] }
]

结果中列出的前四个文档评分较高,因为查询中的 should 子句将标题中包含 snow 的文档指定为首选项。should 子句还使用 boost 选项更改了查询词 snow 的分数。

此查询使用以下管道阶段:

  • $search 查询集合。查询使用以下 compound 操作符子句和 boost 选项,使某些字段的优先级高于其他字段:

    • must文本操作符的子句优先考虑 comedy 类型,然后是 title 字段中的术语 snowboost 选项将权重应用于字段。

    • should 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

    注意

    boost选项会对字段应用不同的权重,以确定字段的优先级。

  • $limit 阶段将输出限制为 10 个结果。

  • $project 阶段到:

    • 排除 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 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

      • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 function 选项更改 scorefunction 选项使用算术表达式添加以下内容:

        • 搜索词查询的相关性评分

        • 名为 imdb.rating 的数字字段的值,或者对于没有 imdb.rating 字段的文档,数字 2 的值。

    • 指定突出显示选项,从 title 字段返回与查询匹配的代码段。这些代码段包含使用 type: 'hit' 指定的匹配文本以及使用 type: 'text' 指定的相邻文本。

  • $limit 阶段将输出限制为 10 个结果。

  • $project 阶段到:

    • 排除 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: [] }
]

结果中列出的前四个文档评分较高,因为查询中的 should 子句将标题中包含 snow 的文档指定为首选项。should 子句还使用 function 选项更改了查询词 snow 的分数。

1

打开 MongoDB Compass 并连接到您的集群。有关连接的详细说明,请参阅通过 Compass 连接。

2

Database 屏幕上,依次单击 sample_mflix 数据库和 movies 集合。

3

该查询将执行以下任务:

  • 使用以下 compound 操作符子句:

    • filter 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

    • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 constant 选项更改 scoreconstant 选项将搜索词的所有得分结果替换为 5

  • 指定突出显示选项,从 title 字段返回与查询匹配的代码段。这些代码段包含使用 type: 'hit' 指定的匹配文本以及使用 type: 'text' 指定的相邻文本。

  • 使用以下管道阶段:

    • $limit 阶段将输出限制为 10 个结果。

    • $project 阶段:

      • 排除 titleyear 之外的所有字段

      • 添加两个名为 scorehighlights 的字段

若要在 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: [] }

    结果中列出的前四个文档评分较高,因为查询中的 should 子句将标题中包含 snow 的文档指定为首选项。should 子句还使用 constant 选项更改了查询词 snow 的分数。

4
  1. 单击 Aggregations 标签页。

  2. 单击 Select...,然后从下拉菜单中选择阶段并为该阶段添加查询,以配置以下每个管道阶段。单击 Add Stage 以添加其他阶段。

    查询使用了下列管道阶段:

    • $search 执行以下任务:

      • 查询使用以下 compound 操作符子句:

        • must 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

        • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 boost 选项更改 scoreboost 选项将搜索词结果中的基本分数乘以 2

      • 指定突出显示选项,从 title 字段返回与查询匹配的代码段。这些代码段包含使用 type: 'hit' 指定的匹配文本以及使用 type: 'text' 指定的相邻文本。

    • $limit 阶段将输出限制为 10 个结果。

    • $project 阶段:

      • 排除 titleyear 之外的所有字段

      • 添加两个名为 scorehighlights 的字段

    管道阶段
    查询

    $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 执行以下任务:

      • 查询使用 compound 操作符子句和 boost 选项,使某些字段的优先级高于其他字段:

        • must文本操作符的子句优先考虑 comedy 类型,然后是 title 字段中的术语 snowboost 选项将权重应用于字段。

        • should 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

        注意

        boost选项会对字段应用不同的权重,以确定字段的优先级。

    • $limit 阶段将输出限制为 10 个结果。

    • $project 阶段:

      • 排除 titleyear 之外的所有字段

      • 添加两个名为 scorehighlights 的字段

    • must文本操作符的子句优先考虑 comedy 类型,然后是 title 字段中的术语 snowboost 选项将权重应用于字段。

    • should 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

    注意

    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: [] }

    结果中列出的前四个文档评分较高,因为查询中的 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 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

      • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 function 选项更改 scorefunction 选项使用算术表达式添加以下内容:

        • 搜索词查询的相关性评分

        • 名为 imdb.rating 的数字字段的值,或者对于没有 imdb.rating 字段的文档,数字 2 的值。

    • 指定突出显示选项,从 title 字段返回与查询匹配的代码段。这些代码段包含使用 type: 'hit' 指定的匹配文本以及使用 type: 'text' 指定的相邻文本。

  • $limit 阶段将输出限制为 10 个结果。

  • $project 阶段:

    • 排除 titleyear 之外的所有字段

    • 添加两个名为 scorehighlights 的字段

若要在 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: [] }

    结果中列出的前四个文档评分较高,因为查询中的 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 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

      • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 constant 选项更改 scoreconstant 选项将搜索词的所有得分结果替换为 5

    • 指定突出显示选项,从 title 字段返回与查询匹配的代码段。这些代码段包含使用 type: 'hit' 指定的匹配文本以及使用 type: 'text' 指定的相邻文本。

    • 使用以下管道阶段:

      • $limit 阶段将输出限制为 10 个结果。

      • $project 阶段:

        • 排除 titleyear 之外的所有字段

        • 添加两个名为 scorehighlights 的字段

    • 遍历游标以打印与查询匹配的文档。

    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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

  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 }

    结果中列出的前四个文档评分较高,因为查询中的 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 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

        • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 boost 选项更改 scoreboost 选项将搜索词结果中的基本分数乘以 2

      指定突出显示选项,从 title 字段返回与查询匹配的代码段。这些代码段包含使用 type: 'hit' 指定的匹配文本以及使用 type: 'text' 指定的相邻文本。

    • $limit 阶段将输出限制为 10 个结果。

    • $project 阶段:

      • 排除 titleyear 之外的所有字段

      • 添加两个名为 scorehighlights 的字段

    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}

    此查询使用以下带有boost选项的compound操作符子句,使某些字段的优先级高于其他字段:

    • must文本操作符的子句优先考虑 comedy 类型,然后是 title 字段中的术语 snowboost 选项将权重应用于字段。

    • should 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

    注意

    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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

  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 }

    结果中列出的前四个文档评分较高,因为查询中的 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 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

      • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 function 选项更改 scorefunction 选项使用算术表达式添加以下内容:

        • 搜索词查询的相关性评分

        • 名为 imdb.rating 的数字字段的值,或者对于没有 imdb.rating 字段的文档,数字 2 的值。

    • 使用以下管道阶段:

      • $limit 阶段将输出限制为 10 个结果。

      • $project 阶段:

        • 排除 titleyear 之外的所有字段

        • 添加两个名为 scorehighlights 的字段

    • 指定突出显示选项,从 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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

  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 }

    结果中列出的前四个文档评分较高,因为查询中的 should 子句将标题中包含 snow 的文档指定为首选项。should 子句还使用 function 选项更改了查询词 snow 的分数。

1
  1. 创建一个名为 compound-constant-query.go 的文件。

  2. 将代码示例复制并粘贴到 compound-constant-query.go 文件中。

    此代码示例将执行以下任务:

    • 导入mongodb包和依赖项。

    • 建立与您的 Atlas 集群的连接。

    • 使用以下复合子句查询集合:

      • filter 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

      • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 constant 选项更改 scoreconstant 选项将搜索词的所有得分结果替换为 5

    • 指定突出显示选项,从 title 字段返回与查询匹配的代码段。这些代码段包含使用 type: 'hit' 指定的匹配文本以及使用 type: 'text' 指定的相邻文本。

    • 使用以下管道阶段:

      • $limit 阶段将输出限制为 10 个结果。

      • $project 阶段:

        • 排除 titleyear 之外的所有字段

        • 添加两个名为 scorehighlights 的字段

    • 遍历游标以打印与查询匹配的文档。

    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 连接字符串。确保您的连接字符串包含数据库用户的档案。要了解详情,请参阅通过驱动程序连接。

  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 []}]

    结果中列出的前四个文档评分较高,因为查询中的 should 子句将标题中包含 snow 的文档指定为首选项。should 子句还使用 constant 选项更改了查询词 snow 的分数。

2
  1. 创建一个名为 compound-boost-query.go 的文件。

  2. 将代码示例复制并粘贴到 compound-boost-query.go 文件中。

    这些代码示例执行以下任务:

    • 导入mongodb包和依赖项。

    • 建立与您的 Atlas 集群的连接。

    • 遍历游标以打印与查询匹配的文档。

    查询使用了下列管道阶段:

    • $search 查询集合阶段。查询:

      • 使用以下 compound 子句查询集合:

        • must 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

        • should 子句和 text 操作符,以在 title 字段中查询词语 snow,并使用 boost 选项更改 scoreboost 选项将搜索词结果中的基本分数乘以 2

      • 指定突出显示选项,从 title 字段返回与查询匹配的代码段。这些代码段包含使用 type: 'hit' 指定的匹配文本以及使用 type: 'text' 指定的相邻文本。

    • $limit 阶段将输出限制为 10 个结果。

    • $project 阶段:

      • 排除 titleyear 之外的所有字段

      • 添加两个名为 scorehighlights 的字段

    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 var err error
    20 // connect to the Atlas cluster
    21 ctx := context.Background()
    22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    23 if err != nil {
    24 panic(err)
    25 }
    26 defer client.Disconnect(ctx)
    27 // set namespace
    28 collection := client.Database("sample_mflix").Collection("movies")
    29 // define pipeline
    30 searchStage := bson.D{{"$search", bson.M{
    31 "index": "compound-query-custom-score-tutorial",
    32 "compound": bson.M{
    33 "must": bson.M{
    34 "range": bson.M{
    35 "path": "year", "gte": 2013, "lte": 2015,
    36 },
    37 },
    38 "should": bson.D{
    39 {"text", bson.M{
    40 "path": "title", "query": "snow", "score": bson.M{
    41 "boost": bson.D{{"value", 2}},
    42 },
    43 }},
    44 },
    45 },
    46 }}}
    47 limitStage := bson.D{{"$limit", 10}}
    48 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    49 // specify the amount of time the operation can run on the server
    50 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    51 // run pipeline
    52 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    53 if err != nil {
    54 panic(err)
    55 }
    56 // print results
    57 var results []bson.D
    58 if err = cursor.All(context.TODO(), &results); err != nil {
    59 panic(err)
    60 }
    61 for _, result := range results {
    62 fmt.Println(result)
    63 }
    64}

    此查询使用以下管道阶段:

    • $search 查询集合阶段。查询:

      • 使用带有 boost 选项的 compound 操作符子句,使某些字段的优先级高于其他字段:

        • must文本操作符的子句优先考虑 comedy 类型,然后是 title 字段中的术语 snowboost 选项将权重应用于字段。

        • should 带有范围操作符的子句,用于搜索 20132015 年之间的电影。

        注意

        boost选项会对字段应用不同的权重,以确定字段的优先级。

    • $limit 阶段将输出限制为 10 个结果。

    • $project 阶段:

      • 排除 titleyear 之外的所有字段

      • 添加两个名为 scorehighlights 的字段

    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 var err error
    20 // connect to the Atlas cluster
    21 ctx := context.Background()
    22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    23 if err != nil {
    24 panic(err)
    25 }
    26 defer client.Disconnect(ctx)
    27 // set namespace
    28 collection := client.Database("sample_mflix").Collection("movies")
    29 // define pipeline
    30 searchStage := bson.D{{"$search", bson.M{
    31 "index": "compound-query-custom-score-tutorial",