How to Run Atlas Search Compound Queries with Weighted Fields
This tutorial describes how to create an index with dynamic mapping on
the sample_mflix.movies
collection. It shows how to run compound
queries against the year
field and alter the score using
constant
, function
, and
boost
. It takes you through the following steps:
Set up an Atlas Search index with dynamic mapping for the
sample_mflix.movies
collection.Run Atlas Search queries against the
year
field in thesample_mflix.movies
collection and alter the score using specific a word in thetitle
field.
Before you begin, ensure that your Atlas cluster meets the requirements described in the Prerequisites.
To create an Atlas Search index, you must have Project Data Access Admin
or higher access to the project.
Create the Atlas Search Index With Dynamic Mapping
In this section, you will create an Atlas Search index that uses dynamic
mapping to index the fields in the sample_mflix.movies
collection.
In Atlas, go to the Clusters page for your project.
If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it is not already displayed, select your desired project from the Projects menu in the navigation bar.
If the Clusters page is not already displayed, click Database in the sidebar.
Go to the Atlas Search page for your cluster.
You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.
In the sidebar, click Atlas Search under the Services heading.
From the Select data source dropdown, select your cluster and click Go to Atlas Search.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
Click the cluster's name.
Click the Atlas Search tab.
Enter the Index Name, and set the Database and Collection.
In the Index Name field, enter
compound-query-custom-score-tutorial
.Note
If you name your index
default
, you don't need to specify anindex
parameter when using the $search pipeline stage. Otherwise, you must specify the index name using theindex
parameter.In the Database and Collection section, find the
sample_mflix
database, and select themovies
collection.
Specify an index definition.
You can create an Atlas Search index that uses dynamic mappings or static mappings. To learn more about dynamic and static mappings, see Static and Dynamic Mappings.
The following index definition dynamically indexes the fields of
supported types in the movies
collection. You can use the Atlas Search Visual Editor or the
Atlas Search JSON Editor in the Atlas user interface to create the
index.
Visual Editor
Click Next.
Review the
"default"
index definition for themovies
collection.
JSON Editor
Click Next.
Review the index definition.
Your index definition should look similar to the following:
{ "mappings": { "dynamic": true } } The above index definition dynamically indexes the fields of supported types in each document in the
movies
collection.Click Next.
Run a Compound Query
➤ Use the Select your language drop-down menu to set the language of the examples in this section.
You can use the compound operator to combine two or more operators into a single query. Every document that Atlas Search returns for your query is assigned a score based on relevance, in order from highest score to lowest. Atlas Search provides a sample compound query template with guidance. To learn more, see View Query Guidance Template.
In this section, you will connect to your
Atlas cluster and run the sample queries using the
compound operator against the title
and year
fields in the sample_mflix.movies
collection. The sample queries
use custom scoring to alter the relevance score returned by Atlas Search.
In Atlas, go to the Clusters page for your project.
If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it is not already displayed, select your desired project from the Projects menu in the navigation bar.
If the Clusters page is not already displayed, click Database in the sidebar.
Go to the Atlas Search page for your cluster.
You can go the Atlas Search page from the sidebar, the Data Explorer, or your cluster details page.
In the sidebar, click Atlas Search under the Services heading.
From the Select data source dropdown, select your cluster and click Go to Atlas Search.
Click the Browse Collections button for your cluster.
Expand the database and select the collection.
Click the Search Indexes tab for the collection.
Click the cluster's name.
Click the Atlas Search tab.
Run the following Atlas Search queries with the compound
operator on the movies
collection.
Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.
The following examples use the compound
operator with subqueries
to search for movies between the years 2013
to 2015
with the
term snow
in the title
field.
The following query:
Uses the following
compound
operator clauses:Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: '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
The first four documents in the results have a higher score
because the should
clause in the query specifies a preference for
documents with snow
in the title. The should
clause also
alters the score for the query term snow
using the constant
option.
The following query:
Uses the following
compound
operator clauses:Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: '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
The first four documents in the results have a higher score
because the should
clause in the query specifies a preference for
documents with snow
in the title. The should
clause also
alters the score for the query term snow
using the boost
option.
The following query:
Uses the following
compound
operator clauses with theboost
option to prioritize some fields more than other fields:must
clause with the text operator to prioritize the genrecomedy
the most, followed by the termsnow
in thetitle
field. Theboost
option applies weights to the fields.should
clause with the range operator to search for movies between the years2013
to2015
.
Note
The
boost
option applies different weights to the fields to prioritize the fields.
[ { $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
The following query:
Uses the following
compound
operator clauses:must
clause with the range operator to search for movies between the years2013
to2015
.should
clause with the text operator to query for the termsnow
in thetitle
field and alter thescore
with thefunction
option. Thefunction
option adds the following using an arithmetic expression:The relevance score of the query for the search term
The value of the numeric field named
imdb.rating
or the number2
for those documents that do not have theimdb.rating
field.
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: '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
The first four documents in the results have a higher score
because the should
clause in the query specifies a preference for
documents with snow
in the title. The should
clause also
alters the score for the query term snow
using the function
option.
Expand your query results.
The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.
Connect to your cluster in mongosh
.
Open mongosh
in a terminal window and
connect to your cluster. For detailed instructions on connecting,
see Connect via mongosh
.
Use the sample_mflix
database.
Run the following command at mongosh
prompt:
use sample_mflix
Run the following Atlas Search queries with the compound
operator on the movies
collection.
The following examples use the compound
operator with subqueries
to search for movies between the years 2013
to 2015
with the
term snow
in the title
field.
This query uses the following pipeline stages:
$search
to query the collection. The query:Uses the following
compound
operator clauses:Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit
stage to limit the output to10
results.$project
stage to:Exclude all fields except
title
andyear
Add a
score
field
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 returns the following results for
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: [] } ]
The first four documents in the results have a higher score
because the should
clause in the query specifies a preference for
documents with snow
in the title. The should
clause also
alters the score for the query term snow
using the constant
option.
This query uses the following pipeline stages:
$search
to query the collection. The query:Uses the following
compound
operator clauses:Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit
stage to limit the output to10
results.$project
stage to:Exclude all fields except
title
andyear
Add a
score
field
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 returns the following results for
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: [] } ]
The first four documents in the results have a higher score
because the should
clause in the query specifies a preference for
documents with snow
in the title. The should
clause also
alters the score for the query term snow
using the boost
option.
This query uses the following pipeline stages:
$search
to query the collection. The query uses the followingcompound
operator clauses with theboost
option to prioritize some fields more than other fields:must
clause with the text operator to prioritize the genrecomedy
the most, followed by the termsnow
in thetitle
field. Theboost
option applies weights to the fields.should
clause with the range operator to search for movies between the years2013
to2015
.
Note
The
boost
option applies different weights to the fields to prioritize the fields.$limit
stage to limit the output to10
results.$project
stage to:Exclude all fields except
title
,year
, andgenres
Add a
score
field
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 } ]
This query uses the following pipeline stages:
$search
to query the collection. The query:Uses the following
compound
operator clauses:must
clause with the range operator to search for movies between the years2013
to2015
.should
clause with the text operator to query for the termsnow
in thetitle
field and alter thescore
with thefunction
option. Thefunction
option adds the following using an arithmetic expression:The relevance score of the query for the search term
The value of the numeric field named
imdb.rating
or the number2
for those documents that do not have theimdb.rating
field.
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit
stage to limit the output to10
results.$project
stage to:Exclude all fields except
title
andyear
Add a
score
field
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 returns the following results for
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: [] } ]
The first four documents in the results have a higher score
because the should
clause in the query specifies a preference for
documents with snow
in the title. The should
clause also
alters the score for the query term snow
using the function
option.
Connect to your cluster in MongoDB Compass.
Open MongoDB Compass and connect to your cluster. For detailed instructions on connecting, see Connect via Compass.
Run an Atlas Search compound query that alters the score using the constant
option.
The query performs the following tasks:
Uses the following
compound
operator clauses:Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Uses the following pipeline stages:
To run this query in MongoDB Compass:
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
Pipeline StageQuery$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" } } If you enabled Auto Preview, MongoDB Compass displays the following documents next to the
$project
pipeline stage:{ 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: [] } The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theconstant
option.
Run Atlas Search compound queries that alter the score using the boost
option.
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
The query uses the following pipeline stages:
$search
to perform the following tasks:Queries using the following
compound
operator clauses:Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit stage to limit the output to 10 results
$project stage to:
Exclude all fields except
title
andyear
Add two fields named
score
andhighlights
Pipeline StageQuery$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" } } This query uses the following pipeline stages:
$search
to perform the following tasks:Queries using the
compound
operator clauses with theboost
option to prioritize some fields more than other fields:must
clause with the text operator to prioritize the genrecomedy
the most, followed by the termsnow
in thetitle
field. Theboost
option applies weights to the fields.should
clause with the range operator to search for movies between the years2013
to2015
.
Note
The
boost
option applies different weights to the fields to prioritize the fields.
$limit stage to limit the output to 10 results
$project stage to:
Exclude all fields except
title
andyear
Add two fields named
score
andhighlights
must
clause with the text operator to prioritize the genrecomedy
the most, followed by the termsnow
in thetitle
field. Theboost
option applies weights to the fields.should
clause with the range operator to search for movies between the years2013
to2015
.
Note
The
boost
option applies different weights to the fields to prioritize the fields.Pipeline StageQuery$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" } } If you enabled Auto Preview, MongoDB Compass displays the following documents next to the
$project
pipeline stage:{ 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: [] } The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theboost
option.[ { 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 } ]
Run an Atlas Search compound query that alters the score using the function
option.
The query uses the following pipeline stages:
$search
stage to perform the following tasks:Queries using the following
compound
operator clauses:must
clause with the range operator to search for movies between the years2013
to2015
.should
clause with the text operator to query for the termsnow
in thetitle
field and alter thescore
with thefunction
option. Thefunction
option adds the following using an arithmetic expression:The relevance score of the query for the search term
The value of the numeric field named
imdb.rating
or the number2
for those documents that do not have theimdb.rating
field.
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit stage to limit the output to 10 results
$project stage to:
Exclude all fields except
title
andyear
Add two fields named
score
andhighlights
To run this query in MongoDB Compass:
Click the Aggregations tab.
Click Select..., then configure each of the following pipeline stages by selecting the stage from the dropdown and adding the query for that stage. Click Add Stage to add additional stages.
Pipeline StageQuery$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" } } If you enabled Auto Preview, MongoDB Compass displays the following documents next to the
$project
pipeline stage:{ 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: [] } The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using thefunction
option.
Run an Atlas Search compound query that alters the score using the constant
option.
Create a new directory called
compound-constant-example
and initialize your project with thedotnet new
command.mkdir compound-constant-example cd compound-constant-example dotnet new console Add the .NET/C# Driver to your project as a dependency.
dotnet add package MongoDB.Driver Replace the contents of the
Program.cs
file with the following code.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following compound clauses to query the collection:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundConstantExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Filter(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015))) 26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Constant(5))), 27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title), 28 indexName: "compound-query-custom-score-tutorial") 29 .Project<MovieDocument>(Builders<MovieDocument>.Projection 30 .Include(movie => movie.Title) 31 .Include(movie => movie.Year) 32 .Exclude(movie => movie.Id) 33 .MetaSearchScore(movie => movie.Score) 34 .MetaSearchHighlights("highlights")) 35 .Limit(10) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string Title { get; set; } 52 public int Year { get; set; } 53 [ ]54 public List<SearchHighlight> Highlights { get; set; } 55 public double Score { get; set; } 56 } Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Compile and run the
Program.cs
file.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 } The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theconstant
option.
Run Atlas Search compound queries that alter the score using the boost
option.
Create a new directory called
compound-boost-example
and initialize your project with thedotnet new
command.mkdir compound-boost-example cd compound-boost-example dotnet new console Add the .NET/C# Driver to your project as a dependency.
dotnet add package MongoDB.Driver Replace the contents of the
Program.cs
file with the following code.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Iterates over the cursor to print the documents that match the query.
The query uses the following pipeline stages:
$search
stage to query the collection. The query:Uses the following
compound
operator clauses:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit stage to limit the output to 10 results
$project stage to:
Exclude all fields except
title
andyear
Add two fields named
score
andhighlights
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundBoostSingleExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015))) 26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(2))), 27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title), 28 indexName: "compound-query-custom-score-tutorial") 29 .Project<MovieDocument>(Builders<MovieDocument>.Projection 30 .Include(movie => movie.Title) 31 .Include(movie => movie.Year) 32 .Exclude(movie => movie.Id) 33 .MetaSearchScore(movie => movie.Score) 34 .MetaSearchHighlights("highlights")) 35 .Limit(10) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string Title { get; set; } 52 public int Year { get; set; } 53 [ ]54 public List<SearchHighlight> Highlights { get; set; } 55 public double Score { get; set; } 56 } This query uses the following
compound
operator clauses with theboost
option to prioritize some fields more than other fields:must
clause with the text operator to prioritize the genrecomedy
the most, followed by the termsnow
in thetitle
field. Theboost
option applies weights to the fields.should
clause with the range operator to search for movies between the years2013
to2015
.
Note
The
boost
option applies different weights to the fields to prioritize the fields.1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundBoostMultipleExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "comedy", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(9))) 26 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(5))) 27 .Should(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015), score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(3))), 28 indexName: "compound-query-custom-score-tutorial") 29 .Project<MovieDocument>(Builders<MovieDocument>.Projection 30 .Include(movie => movie.Genres) 31 .Include(movie => movie.Title) 32 .Include(movie => movie.Year) 33 .Exclude(movie => movie.Id) 34 .MetaSearchScore(movie => movie.Score)) 35 .Limit(10) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string [] Genres { get; set; } 52 public string Title { get; set; } 53 public int Year { get; set; } 54 public double Score { get; set; } 55 } Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Compile and run the
Program.cs
file.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 } The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theboost
option.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 }
Run an Atlas Search compound query that alters the score using the function
option.
Create a new directory called
compound-function-example
and initialize your project with thedotnet new
command.mkdir compound-function-example cd compound-function-example dotnet new console Add the .NET/C# Driver to your project as a dependency.
dotnet add package MongoDB.Driver Replace the contents of the
Program.cs
file with the following code.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages to query the collection:
must
clause with the range operator to search for movies between the years2013
to2015
.should
clause with the text operator to query for the termsnow
in thetitle
field and alter thescore
with thefunction
option. Thefunction
option adds the following using an arithmetic expression:The relevance score of the query for the search term
The value of the numeric field named
imdb.rating
or the number2
for those documents that do not have theimdb.rating
field.
Uses the following pipeline stages:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Iterates over the cursor to print the documents that match the query.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundFunctionExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 var scoreFunction = Builders<MovieDocument>.SearchScore.Function(Builders<MovieDocument>.SearchScoreFunction.Add(Builders<MovieDocument>.SearchScoreFunction.Path(movie => movie.Imdb.Rating, 2), Builders<MovieDocument>.SearchScoreFunction.Relevance())); 23 // define and run pipeline 24 var results = moviesCollection.Aggregate() 25 .Search(Builders<MovieDocument>.Search.Compound() 26 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015))) 27 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: scoreFunction)), 28 new SearchHighlightOptions<MovieDocument>(movie => movie.Title), 29 indexName: "compound-query-custom-score-tutorial") 30 .Project<MovieDocument>(Builders<MovieDocument>.Projection 31 .Include(movie => movie.Genres) 32 .Include(movie => movie.Title) 33 .Include(movie => movie.Year) 34 .Exclude(movie => movie.Id) 35 .MetaSearchScore(movie => movie.Score) 36 .MetaSearchHighlights("highlights")) 37 .Limit(10) 38 .ToList(); 39 40 // print results 41 foreach (var movie in results) 42 { 43 Console.WriteLine(movie.ToJson()); 44 } 45 } 46 } 47 48 [ ]49 public class MovieDocument 50 { 51 [ ]52 public ObjectId Id { get; set; } 53 public string [] Genres { get; set; } 54 public IMDB Imdb { get; set; } 55 public string Title { get; set; } 56 public int Year { get; set; } 57 [ ]58 public List<SearchHighlight> Highlights { get; set; } 59 public double Score { get; set; } 60 } 61 62 [ ]63 public class IMDB 64 { 65 public double Rating { get; set; } 66 } Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Compile and run the
Program.cs
file.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 } The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using thefunction
option.
Run an Atlas Search compound query that alters the score using the constant
option.
Create a file named
compound-constant-query.go
.Copy and paste the code example into the
compound-constant-query.go
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following compound clauses to query the collection:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 func main() { 14 // connect to your Atlas cluster 15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 16 if err != nil { 17 panic(err) 18 } 19 defer client.Disconnect(context.TODO()) 20 21 // set namespace 22 collection := client.Database("sample_mflix").Collection("movies") 23 24 // define pipeline stages 25 searchStage := bson.D{{"$search", bson.M{ 26 "index": "compound-query-custom-score-tutorial", 27 "compound": bson.M{ 28 "filter": bson.M{ 29 "range": bson.M{ 30 "path": "year", "gte": 2013, "lte": 2015, 31 }, 32 }, 33 "should": bson.D{ 34 {"text", bson.M{ 35 "path": "title", "query": "snow", "score": bson.M{ 36 "constant": bson.D{{"value", 5}}, 37 }}}}, 38 }, 39 "highlight": bson.D{{"path", "title"}}, 40 }}} 41 limitStage := bson.D{{"$limit", 10}} 42 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}} 43 44 // specify the amount of time the operation can run on the server 45 opts := options.Aggregate().SetMaxTime(5 * time.Second) 46 47 // run pipeline 48 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 49 if err != nil { 50 panic(err) 51 } 52 53 // print results 54 var results []bson.D 55 if err = cursor.All(context.TODO(), &results); err != nil { 56 panic(err) 57 } 58 for _, result := range results { 59 fmt.Println(result) 60 } 61 } Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
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 []}] The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theconstant
option.
Run an Atlas Search compound query that alters the score using the boost
option.
Create a file named
compound-boost-query.go
.Copy and paste the code example into the
compound-boost-query.go
file.The code examples perform the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Iterates over the cursor to print the documents that match the query.
The query uses the following pipeline stages:
$search
stage to query the collection. The query:Uses the following
compound
clauses to query the collection:Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit stage to limit the output to 10 results
$project stage to:
Exclude all fields except
title
andyear
Add two fields named
score
andhighlights
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 // define structure of movies collection 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 } 17 18 func main() { 19 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 } This query uses the following pipeline stages:
$search
stage to query the collection. The query:Uses the
compound
operator clauses with theboost
option to prioritize some fields more than other fields:must
clause with the text operator to prioritize the genrecomedy
the most, followed by the termsnow
in thetitle
field. Theboost
option applies weights to the fields.should
clause with the range operator to search for movies between the years2013
to2015
.
Note
The
boost
option applies different weights to the fields to prioritize the fields.
$limit stage to limit the output to 10 results
$project stage to:
Exclude all fields except
title
andyear
Add two fields named
score
andhighlights
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 // define structure of movies collection 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 } 17 18 func main() { 19 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.A{ 34 bson.M{ 35 "text": bson.M{ 36 "path": "genres", "query": "comedy", "score": bson.M{ 37 "boost": bson.D{{"value", 9}}, 38 }, 39 }, 40 }, 41 bson.M{ 42 "text": bson.M{ 43 "path": "title", "query": "snow", "score": bson.M{ 44 "boost": bson.D{{"value", 5}}, 45 }, 46 }, 47 }, 48 }, 49 "should": bson.M{ 50 "range": bson.M{ 51 "path": "year", "gte": 2013, "lte": 2015, "score": bson.M{ 52 "boost": bson.D{{"value", 3}}, 53 }, 54 }, 55 }, 56 }, 57 }}} 58 limitStage := bson.D{{"$limit", 10}} 59 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"genres", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 60 // specify the amount of time the operation can run on the server 61 opts := options.Aggregate().SetMaxTime(5 * time.Second) 62 // run pipeline 63 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 64 if err != nil { 65 panic(err) 66 } 67 // print results 68 var results []bson.D 69 if err = cursor.All(context.TODO(), &results); err != nil { 70 panic(err) 71 } 72 for _, result := range results { 73 fmt.Println(result) 74 } 75 } Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
go run compound-boost-query.go [{title Snow in Paradise} {year 2014} {score 6.7722930908203125} {highlights [[{score 1.382846713066101} {path title} {texts [[{value Snow} {type hit}] [{value in Paradise} {type text}]]}]]}] [{title Snow on the Blades} {year 2014} {score 6.063445568084717} {highlights [[{score 1.3766303062438965} {path title} {texts [[{value Snow} {type hit}] [{value on the Blades} {type text}]]}]]}] [{title The Snow White Murder Case} {year 2014} {score 5.509652137756348} {highlights [[{score 1.3525336980819702} {path title} {texts [[{value The } {type text}] [{value Snow} {type hit}] [{value White Murder Case} {type text}]]}]]}] [{title Dead Snow 2: Red vs. Dead} {year 2014} {score 5.065053939819336} {highlights [[{score 1.3924485445022583} {path title} {texts [[{value Dead } {type text}] [{value Snow} {type hit}] [{value 2: Red vs. } {type text}]]}]]}] [{year 2013} {title The Secret Life of Walter Mitty} {score 1} {highlights []}] [{title Jurassic World} {year 2015} {score 1} {highlights []}] [{title Action Jackson} {year 2014} {score 1} {highlights []}] [{year 2013} {title In Secret} {score 1} {highlights []}] [{title The Stanford Prison Experiment} {year 2015} {score 1} {highlights []}] [{year 2014} {title The Giver} {score 1} {highlights []}] The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theboost
option.go run compound-boost-query.go [ { genres: [ 'Comedy', 'Horror' ], title: 'Dead Snow', year: 2009, score: 21.872983932495117 }, { year: 2000, genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow Day', score: 21.043487548828125 }, { genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow Dogs', year: 2002, score: 21.043487548828125 }, { year: 1999, genres: [ 'Comedy', 'Romance' ], title: 'Let It Snow', score: 19.523927688598633 }, { genres: [ 'Action', 'Comedy', 'Horror' ], title: 'Dead Snow 2: Red vs. Dead', year: 2014, score: 17.426334381103516 }, { genres: [ 'Comedy', 'Drama' ], title: 'Snow White and Russian Red', year: 2009, score: 16.367326736450195 }, { genres: [ 'Comedy', 'Drama', 'Romance' ], title: 'The Tiger and the Snow', year: 2005, score: 15.537829399108887 }, { genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow White and the Three Stooges', year: 1961, score: 14.4263334274292 } ]
Run an Atlas Search compound query that alters the score using the function
option.
Create a file named
compound-boost-query.go
.Copy and paste the code example into the
compound-function-query.go
file.The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following
compound
operator clauses:must
clause with the range operator to search for movies between the years2013
to2015
.should
clause with the text operator to query for the termsnow
in thetitle
field and alter thescore
with thefunction
option. Thefunction
option adds the following using an arithmetic expression:The relevance score of the query for the search term
The value of the numeric field named
imdb.rating
or the number2
for those documents that do not have theimdb.rating
field.
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 func main() { 14 // connect to your Atlas cluster 15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 16 if err != nil { 17 panic(err) 18 } 19 defer client.Disconnect(context.TODO()) 20 21 // set namespace 22 collection := client.Database("sample_mflix").Collection("movies") 23 24 // define pipeline 25 searchStage := bson.D{{"$search", bson.M{ 26 "index": "compound-query-custom-score-tutorial", 27 "compound": bson.M{ 28 "must": 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 "function": bson.D{{"add", bson.A{ 37 bson.D{{"path", bson.D{ 38 {"value", "imdb.rating"}, {"undefined", 2}, 39 }}}, 40 bson.D{{"score", "relevance"}}, 41 }}}, 42 }}}}, 43 }, 44 "highlight": bson.D{{"path", "title"}}, 45 }}} 46 limitStage := bson.D{{"$limit", 10}} 47 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}} 48 49 // specify the amount of time the operation can run on the server 50 opts := options.Aggregate().SetMaxTime(5 * time.Second) 51 52 // run pipeline 53 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 54 if err != nil { 55 panic(err) 56 } 57 58 // print results 59 var results []bson.D 60 if err = cursor.All(context.TODO(), &results); err != nil { 61 panic(err) 62 } 63 for _, result := range results { 64 fmt.Println(result) 65 } 66 } Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
go run compound-function-query.go [{title The Snow White Murder Case} {year 2014} {score 10.454826354980469} {highlights [[{score 1.3525336980819702} {path title} {texts [[{value The } {type text}] [{value Snow} {type hit}] [{value White Murder Case} {type text}]]}]]}] [{title Snow on the Blades} {year 2014} {score 10.3317232131958} {highlights [[{score 1.3766303062438965} {path title} {texts [[{value Snow} {type hit}] [{value on the Blades} {type text}]]}]]}] [{title Dead Snow 2: Red vs. Dead} {year 2014} {score 10.032526969909668} {highlights [[{score 1.3924485445022583} {path title} {texts [[{value Dead } {type text}] [{value Snow} {type hit}] [{value 2: Red vs. } {type text}]]}]]}] [{title Snow in Paradise} {year 2014} {score 8.386146545410156} {highlights [[{score 1.382846713066101} {path title} {texts [[{value Snow} {type hit}] [{value in Paradise} {type text}]]}]]}] [{year 2013} {title The Secret Life of Walter Mitty} {score 1} {highlights []}] [{title Jurassic World} {year 2015} {score 1} {highlights []}] [{title Action Jackson} {year 2014} {score 1} {highlights []}] [{year 2013} {title In Secret} {score 1} {highlights []}] [{title The Stanford Prison Experiment} {year 2015} {score 1} {highlights []}] [{year 2014} {title The Giver} {score 1} {highlights []}] The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using thefunction
option.
Run an Atlas Search compound query that alters the score using the constant
option.
Create a file named
CompoundConstantQuery.java
.Copy and paste the following code into the file.
The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following compound clauses to query the collection:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 12 import org.bson.Document; 13 14 public class CompoundConstantQuery { 15 public static void main( String[] args ) { 16 // define clauses 17 List<Document> mustClauses = 18 List.of( 19 new Document( 20 "range", new Document("path", "year") 21 .append("gte", 2013) 22 .append("lte", 2015))); 23 List<Document> shouldClauses = 24 List.of( 25 new Document("text", 26 new Document("query", "snow") 27 .append("path", "title") 28 .append("score", new Document("constant", new Document("value", 5))))); 29 Document highlightOption = new Document("path", "title"); 30 // define query 31 Document agg = 32 new Document("$search", 33 new Document("index", "compound-query-custom-score-tutorial") 34 .append("compound", 35 new Document("must", mustClauses).append("should", shouldClauses)) 36 .append("highlight", highlightOption)); 37 // specify connection 38 String uri = "<connection-string>"; 39 // establish connection and set namespace 40 try (MongoClient mongoClient = MongoClients.create(uri)) { 41 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 42 MongoCollection<Document> collection = database.getCollection("movies"); 43 // run query and print results 44 collection.aggregate(Arrays.asList(agg, 45 limit(10), 46 project(fields( 47 excludeId(), 48 include("title", "year"), 49 computed("score", new Document("$meta", "searchScore")), 50 computed("highlights", new Document("$meta", "searchHighlights")))))) 51 .forEach(doc -> System.out.println(doc.toJson())); 52 } 53 } 54 } Note
To run the sample code in your Maven environment, add the following above the import statements in your file.
package com.mongodb.drivers; Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Compile and run
CompoundConstantQuery.java
file.javac CompoundConstantQuery.java java CompoundConstantQuery {"title": "Snow in Paradise", "year": 2014, "score": 5.0, "highlights": [{"score": 1.382846713066101, "path": "title", "texts": [{"value": "Snow", "type": "hit"}, {"value": " in Paradise", "type": "text"}]}]} {"title": "Dead Snow 2: Red vs. Dead", "year": 2014, "score": 5.0, "highlights": [{"score": 1.3924485445022583, "path": "title", "texts": [{"value": "Dead ", "type": "text"}, {"value": "Snow", "type": "hit"}, {"value": " 2: Red vs. ", "type": "text"}]}]} {"title": "The Snow White Murder Case", "year": 2014, "score": 5.0, "highlights": [{"score": 1.3525336980819702, "path": "title", "texts": [{"value": "The ", "type": "text"}, {"value": "Snow", "type": "hit"}, {"value": " White Murder Case", "type": "text"}]}]} {"title": "Snow on the Blades", "year": 2014, "score": 5.0, "highlights": [{"score": 1.3766303062438965, "path": "title", "texts": [{"value": "Snow", "type": "hit"}, {"value": " on the Blades", "type": "text"}]}]} {"year": 2013, "title": "The Secret Life of Walter Mitty", "score": 0.0, "highlights": []} {"title": "Jurassic World", "year": 2015, "score": 0.0, "highlights": []} {"title": "Action Jackson", "year": 2014, "score": 0.0, "highlights": []} {"year": 2013, "title": "In Secret", "score": 0.0, "highlights": []} {"title": "The Stanford Prison Experiment", "year": 2015, "score": 0.0, "highlights": []} {"year": 2014, "title": "The Giver", "score": 0.0, "highlights": []} The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theconstant
option.
Run Atlas Search compound queries that alter the score using the boost
option.
Create a file named
CompoundBoostQuery.java
.Copy and paste the following code into the file.
The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Iterates over the cursor to print the documents that match the query.
The query uses the following pipeline stages:
$search
stage to query the collection. The query:Uses the following
compound
operator clauses:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit stage to limit the output to 10 results
$project stage to:
Exclude all fields except
title
andyear
Add two fields named
score
andhighlights
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 public class CompoundBoostQuery { 14 public static void main( String[] args ) { 15 // define clauses 16 List<Document> mustClauses = 17 List.of( 18 new Document( 19 "range", new Document("path", "year") 20 .append("gte", 2013) 21 .append("lte", 2015))); 22 List<Document> shouldClauses = 23 List.of( 24 new Document( 25 "text", 26 new Document("query", "snow") 27 .append("path", "title") 28 .append("score", new Document("boost", new Document("value", 2))))); 29 Document highlightOption = new Document("path", "title"); 30 // define query 31 Document agg = 32 new Document("$search", 33 new Document("index", "compound-query-custom-score-tutorial") 34 .append("compound", 35 new Document("must", mustClauses).append("should", shouldClauses)) 36 .append("highlight", highlightOption)); 37 // specify connection 38 String uri = "<connection-string>"; 39 // establish connection and set namespace 40 try (MongoClient mongoClient = MongoClients.create(uri)) { 41 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 42 MongoCollection<Document> collection = database.getCollection("movies"); 43 // run query and print results 44 collection.aggregate(Arrays.asList(agg, 45 limit(10), 46 project(fields( 47 excludeId(), 48 include("title", "year"), 49 computed("score", new Document("$meta", "searchScore")), 50 computed("highlights", new Document("$meta", "searchHighlights")))))) 51 .forEach(doc -> System.out.println(doc.toJson())); 52 } 53 } 54 } This query uses the following
compound
operator clauses with theboost
option to prioritize some fields more than other fields:must
clause with the text operator to prioritize the genrecomedy
the most, followed by the termsnow
in thetitle
field. Theboost
option applies weights to the fields.should
clause with the range operator to search for movies between the years2013
to2015
.
Note
The
boost
option applies different weights to the fields to prioritize the fields.1 import java.util.Arrays; 2 import static com.mongodb.client.model.Filters.eq; 3 import static com.mongodb.client.model.Aggregates.limit; 4 import static com.mongodb.client.model.Aggregates.project; 5 import static com.mongodb.client.model.Projections.computed; 6 import static com.mongodb.client.model.Projections.excludeId; 7 import static com.mongodb.client.model.Projections.fields; 8 import static com.mongodb.client.model.Projections.include; 9 import com.mongodb.client.MongoClient; 10 import com.mongodb.client.MongoClients; 11 import com.mongodb.client.MongoCollection; 12 import com.mongodb.client.MongoDatabase; 13 import org.bson.Document; 14 15 public class CompoundBoostQuery { 16 public static void main( String[] args ) { 17 Document agg = new Document("index", "compound-query-custom-score-tutorial") 18 .append("must", Arrays.asList(new Document("text", 19 new Document("path", "genres") 20 .append("query", "comedy") 21 .append("score", 22 new Document("boost", 23 new Document("value", 9)))), 24 new Document("text", 25 new Document("path", "title") 26 .append("query", "snow") 27 .append("score", 28 new Document("boost", 29 new Document("value", 5)))))) 30 .append("should", Arrays.asList(new Document("range", 31 new Document("path", "year") 32 .append("gte", 2013) 33 .append("lte", 2015) 34 .append("score", 35 new Document("boost", 36 new Document("value", 3)))))); 37 38 String uri = "<connection-string>"; 39 40 try (MongoClient mongoClient = MongoClients.create(uri)) { 41 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 42 MongoCollection<Document> collection = database.getCollection("movies"); 43 44 collection.aggregate(Arrays.asList( 45 eq("$search", eq("compound", agg)), 46 limit(10), 47 project(fields(excludeId(), include("title", "year","genres"), computed("score", new Document("$meta", "searchScore"))))) 48 ).forEach(doc -> System.out.println(doc.toJson())); 49 } 50 } 51 } Note
To run the sample code in your Maven environment, add the following above the import statements in your file.
package com.mongodb.drivers; Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Compile and run
CompoundBoostQuery.java
file.javac CompoundBoostQuery.java java CompoundBoostQuery {"title": "Snow in Paradise", "year": 2014, "score": 6.7722930908203125, "highlights": [{"score": 1.382846713066101, "path": "title", "texts": [{"value": "Snow", "type": "hit"}, {"value": " in Paradise", "type": "text"}]}]} {"title": "Snow on the Blades", "year": 2014, "score": 6.063445568084717, "highlights": [{"score": 1.3766303062438965, "path": "title", "texts": [{"value": "Snow", "type": "hit"}, {"value": " on the Blades", "type": "text"}]}]} {"title": "The Snow White Murder Case", "year": 2014, "score": 5.509652137756348, "highlights": [{"score": 1.3525336980819702, "path": "title", "texts": [{"value": "The ", "type": "text"}, {"value": "Snow", "type": "hit"}, {"value": " White Murder Case", "type": "text"}]}]} {"title": "Dead Snow 2: Red vs. Dead", "year": 2014, "score": 5.065053939819336, "highlights": [{"score": 1.3924485445022583, "path": "title", "texts": [{"value": "Dead ", "type": "text"}, {"value": "Snow", "type": "hit"}, {"value": " 2: Red vs. ", "type": "text"}]}]} {"year": 2013, "title": "The Secret Life of Walter Mitty", "score": 1.0, "highlights": []} {"title": "Jurassic World", "year": 2015, "score": 1.0, "highlights": []} {"title": "Action Jackson", "year": 2014, "score": 1.0, "highlights": []} {"year": 2013, "title": "In Secret", "score": 1.0, "highlights": []} {"title": "The Stanford Prison Experiment", "year": 2015, "score": 1.0, "highlights": []} {"year": 2014, "title": "The Giver", "score": 1.0, "highlights": []} The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theboost
option.javac CompoundBoostQuery.java java CompoundBoostQuery { "genres": ["Comedy", "Horror"], "title": "Dead Snow", "year": 2009, "score": 21.872983932495117 } { "year": 2000, "genres": ["Adventure", "Comedy", "Family"], "title": "Snow Day", "score": 21.043487548828125 } { "genres": ["Adventure", "Comedy", "Family"], "title": "Snow Dogs", "year": 2002, "score": 21.043487548828125 } { "year": 1999, "genres": ["Comedy", "Romance"], "title": "Let It Snow", "score": 19.523927688598633 } { "genres": ["Action", "Comedy", "Horror"], "title": "Dead Snow 2: Red vs. Dead", "year": 2014, "score": 17.426334381103516 } { "genres": ["Comedy", "Drama"], "title": "Snow White and Russian Red", "year": 2009, "score": 16.367326736450195} { "genres": ["Comedy", "Drama", "Romance"], "title": "The Tiger and the Snow", "year": 2005, "score": 15.537829399108887 } { "genres": ["Adventure", "Comedy", "Family"], "title": "Snow White and the Three Stooges", "year": 1961, "score": 14.4263334274292 }
Run an Atlas Search compound query that alters the score using the function
option.
Create a file named
CompoundFunctionQuery.java
.Copy and paste the following code into the file.
The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages to query the collection:
must
clause with the range operator to search for movies between the years2013
to2015
.should
clause with the text operator to query for the termsnow
in thetitle
field and alter thescore
with thefunction
option. Thefunction
option adds the following using an arithmetic expression:The relevance score of the query for the search term
The value of the numeric field named
imdb.rating
or the number2
for those documents that do not have theimdb.rating
field.
Uses the following pipeline stages:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Iterates over the cursor to print the documents that match the query.
1 import java.util.Arrays; 2 import java.util.List; 3 4 import static com.mongodb.client.model.Aggregates.limit; 5 import static com.mongodb.client.model.Aggregates.project; 6 import static com.mongodb.client.model.Projections.*; 7 import com.mongodb.client.MongoClient; 8 import com.mongodb.client.MongoClients; 9 import com.mongodb.client.MongoCollection; 10 import com.mongodb.client.MongoDatabase; 11 import org.bson.Document; 12 13 public class CompoundFunctionQuery { 14 public static void main( String[] args ) { 15 // define clauses 16 List<Document> mustClauses = 17 List.of( 18 new Document("range", new Document("path", "year") 19 .append("gte", 2013) 20 .append("lte", 2015))); 21 List<Document> shouldClauses = 22 List.of( 23 new Document("text", 24 new Document("query", "snow") 25 .append("path", "title") 26 .append("score", new Document("function", 27 new Document("add", Arrays.asList( 28 new Document("path", new Document("value", "imdb.rating") 29 .append("undefined", 2)), new Document("score", "relevance"))))))); 30 Document highlightOption = new Document("path", "title"); 31 // define query 32 Document agg = 33 new Document("$search", 34 new Document("index", "compound-query-custom-score-tutorial") 35 .append("compound", 36 new Document("must", mustClauses).append("should", shouldClauses)) 37 .append("highlight", highlightOption)); 38 // specify connection 39 String uri = "<connection-string>"; 40 // establish connection and set namespace 41 try (MongoClient mongoClient = MongoClients.create(uri)) { 42 MongoDatabase database = mongoClient.getDatabase("sample_mflix"); 43 MongoCollection<Document> collection = database.getCollection("movies"); 44 // run query and print results 45 collection.aggregate(Arrays.asList(agg, 46 limit(10), 47 project(fields( 48 excludeId(), 49 include("title", "year"), 50 computed("score", new Document("$meta", "searchScore")), 51 computed("highlights", new Document("$meta", "searchHighlights")))))) 52 .forEach(doc -> System.out.println(doc.toJson())); 53 } 54 } 55 } Note
To run the sample code in your Maven environment, add the following above the import statements in your file.
package com.mongodb.drivers; Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Compile and run
CompoundFunctionQuery.java
file.javac CompoundFunctionQuery.java java CompoundFunctionQuery {"title": "The Snow White Murder Case", "year": 2014, "score": 10.454826354980469, "highlights": [{"score": 1.3525336980819702, "path": "title", "texts": [{"value": "The ", "type": "text"}, {"value": "Snow", "type": "hit"}, {"value": " White Murder Case", "type": "text"}]}]} {"title": "Snow on the Blades", "year": 2014, "score": 10.3317232131958, "highlights": [{"score": 1.3766303062438965, "path": "title", "texts": [{"value": "Snow", "type": "hit"}, {"value": " on the Blades", "type": "text"}]}]} {"title": "Dead Snow 2: Red vs. Dead", "year": 2014, "score": 10.032526969909668, "highlights": [{"score": 1.3924485445022583, "path": "title", "texts": [{"value": "Dead ", "type": "text"}, {"value": "Snow", "type": "hit"}, {"value": " 2: Red vs. ", "type": "text"}]}]} {"title": "Snow in Paradise", "year": 2014, "score": 8.386146545410156, "highlights": [{"score": 1.382846713066101, "path": "title", "texts": [{"value": "Snow", "type": "hit"}, {"value": " in Paradise", "type": "text"}]}]} {"year": 2013, "title": "The Secret Life of Walter Mitty", "score": 1.0, "highlights": []} {"title": "Jurassic World", "year": 2015, "score": 1.0, "highlights": []} {"title": "Action Jackson", "year": 2014, "score": 1.0, "highlights": []} {"year": 2013, "title": "In Secret", "score": 1.0, "highlights": []} {"title": "The Stanford Prison Experiment", "year": 2015, "score": 1.0, "highlights": []} {"year": 2014, "title": "The Giver", "score": 1.0, "highlights": []} The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using thefunction
option.
Run an Atlas Search compound query that alters the score using the constant
option.
Create a file named
CompoundConstantQuery.kt
.Copy and paste the following code into the file.
The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following compound clauses to query the collection:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Uses the following pipeline stages:
Prints the documents that match the query from the
AggregateFlow
instance.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 val database = mongoClient.getDatabase("sample_mflix") 13 val collection = database.getCollection<Document>("movies") 14 15 runBlocking { 16 // define clauses 17 val mustClauses = listOf( 18 Document( 19 "range", Document("path", "year") 20 .append("gte", 2013) 21 .append("lte", 2015) 22 ) 23 ) 24 25 val shouldClauses = listOf( 26 Document( 27 "text", 28 Document("query", "snow") 29 .append("path", "title") 30 .append("score", Document("constant", Document("value", 5))) 31 ) 32 ) 33 34 val highlightOption = Document("path", "title") 35 36 // define pipeline 37 val agg = Document( 38 "\$search", 39 Document("index", "compound-query-custom-score-tutorial") 40 .append( 41 "compound", 42 Document("must", mustClauses).append("should", shouldClauses) 43 ) 44 .append("highlight", highlightOption) 45 ) 46 47 val resultsFlow = collection.aggregate<Document>( 48 listOf( 49 agg, 50 limit(10), 51 project(fields( 52 excludeId(), 53 include("title", "year"), 54 computed("score", Document("\$meta", "searchScore")), 55 computed("highlights", Document("\$meta", "searchHighlights")) 56 )) 57 ) 58 ) 59 resultsFlow.collect { println(it) } 60 } 61 mongoClient.close() 62 } Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the
CompoundConstantQuery.kt
file.When you run the
CompoundConstantQuery.kt
program in your IDE, it prints the following documents:Document{{title=Snow in Paradise, year=2014, score=6.0, highlights=[Document{{score=1.382846713066101, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= in Paradise, type=text}}]}}]}} Document{{title=Dead Snow 2: Red vs. Dead, year=2014, score=6.0, highlights=[Document{{score=1.3924485445022583, path=title, texts=[Document{{value=Dead , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= 2: Red vs. , type=text}}]}}]}} Document{{title=The Snow White Murder Case, year=2014, score=6.0, highlights=[Document{{score=1.3525336980819702, path=title, texts=[Document{{value=The , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= White Murder Case, type=text}}]}}]}} Document{{title=Snow on the Blades, year=2014, score=6.0, highlights=[Document{{score=1.3766303062438965, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= on the Blades, type=text}}]}}]}} Document{{year=2013, title=The Secret Life of Walter Mitty, score=1.0, highlights=[]}} Document{{title=Jurassic World, year=2015, score=1.0, highlights=[]}} Document{{title=Action Jackson, year=2014, score=1.0, highlights=[]}} Document{{year=2013, title=In Secret, score=1.0, highlights=[]}} Document{{title=The Stanford Prison Experiment, year=2015, score=1.0, highlights=[]}} Document{{year=2014, title=The Giver, score=1.0, highlights=[]}} The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theconstant
option.
Run Atlas Search compound queries that alter the score using the boost
option.
Create a file named
CompoundBoostQuery.kt
.Copy and paste the following code into the file.
The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Prints the documents that match the query from the
AggregateFlow
instance.
The query uses the following pipeline stages:
$search
stage to query the collection. The query:Uses the following
compound
operator clauses:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit stage to limit the output to 10 results
$project stage to:
Exclude all fields except
title
andyear
Add two fields named
score
andhighlights
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define clauses 18 val mustClauses = listOf( 19 Document( 20 "range", Document("path", "year") 21 .append("gte", 2013) 22 .append("lte", 2015) 23 ) 24 ) 25 26 val shouldClauses = listOf( 27 Document( 28 "text", 29 Document("query", "snow") 30 .append("path", "title") 31 .append("score", Document("boost", Document("value", 2))) 32 ) 33 ) 34 35 val highlightOption = Document("path", "title") 36 37 // define pipeline 38 val agg = Document( 39 "\$search", 40 Document("index", "compound-query-custom-score-tutorial") 41 .append( 42 "compound", 43 Document("must", mustClauses).append("should", shouldClauses) 44 ) 45 .append("highlight", highlightOption) 46 ) 47 48 // run query and print results 49 val resultsFlow = collection.aggregate<Document>( 50 listOf( 51 agg, 52 limit(10), 53 project(fields( 54 excludeId(), 55 include("title", "year"), 56 computed("score", Document("\$meta", "searchScore")), 57 computed("highlights", Document("\$meta", "searchHighlights")) 58 )) 59 ) 60 ) 61 resultsFlow.collect { println(it) } 62 } 63 mongoClient.close() 64 } This query uses the following
compound
operator clauses with theboost
option to prioritize some fields more than other fields:must
clause with the text operator to prioritize the genrecomedy
the most, followed by the termsnow
in thetitle
field. Theboost
option applies weights to the fields.should
clause with the range operator to search for movies between the years2013
to2015
.
Note
The
boost
option applies different weights to the fields to prioritize the fields.1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define pipeline 18 val agg = Document( 19 "\$search", 20 Document("index", "compound-query-custom-score-tutorial") 21 .append( 22 "compound", 23 Document( 24 "must", listOf( 25 Document( 26 "text", 27 Document("path", "genres") 28 .append("query", "comedy") 29 .append( 30 "score", 31 Document( 32 "boost", 33 Document("value", 9) 34 ) 35 ) 36 ), 37 Document( 38 "text", 39 Document("path", "title") 40 .append("query", "snow") 41 .append( 42 "score", 43 Document( 44 "boost", 45 Document("value", 5) 46 ) 47 ) 48 ) 49 ) 50 ) 51 .append( 52 "should", listOf( 53 Document( 54 "range", 55 Document("path", "year") 56 .append("gte", 2013) 57 .append("lte", 2015) 58 .append( 59 "score", 60 Document( 61 "boost", 62 Document("value", 3) 63 ) 64 ) 65 ) 66 ) 67 ) 68 ) 69 ) 70 71 // run query and print results 72 val resultsFlow = collection.aggregate<Document>( 73 listOf( 74 agg, 75 limit(10), 76 project(fields( 77 excludeId(), 78 include("title", "year","genres"), 79 computed("score", Document("\$meta", "searchScore")) 80 )) 81 ) 82 ) 83 resultsFlow.collect { println(it) } 84 } 85 mongoClient.close() 86 } Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the
CompoundBoostQuery.kt
file.When you run the
CompoundBoostQuery.kt
program in your IDE, it prints the following documents:Document{{title=Snow in Paradise, year=2014, score=6.784297466278076, highlights=[Document{{score=1.382846713066101, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= in Paradise, type=text}}]}}]}} Document{{title=Snow on the Blades, year=2014, score=6.073266506195068, highlights=[Document{{score=1.3766303062438965, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= on the Blades, type=text}}]}}]}} Document{{title=The Snow White Murder Case, year=2014, score=5.517906188964844, highlights=[Document{{score=1.3525336980819702, path=title, texts=[Document{{value=The , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= White Murder Case, type=text}}]}}]}} Document{{title=Dead Snow 2: Red vs. Dead, year=2014, score=5.072136878967285, highlights=[Document{{score=1.3924485445022583, path=title, texts=[Document{{value=Dead , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= 2: Red vs. , type=text}}]}}]}} Document{{year=2013, title=The Secret Life of Walter Mitty, score=1.0, highlights=[]}} Document{{title=Jurassic World, year=2015, score=1.0, highlights=[]}} Document{{title=Action Jackson, year=2014, score=1.0, highlights=[]}} Document{{year=2013, title=In Secret, score=1.0, highlights=[]}} Document{{title=The Stanford Prison Experiment, year=2015, score=1.0, highlights=[]}} Document{{year=2014, title=The Giver, score=1.0, highlights=[]}} The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theboost
option.When you run the
CompoundBoostQuery.kt
program in your IDE, it prints the following documents:Document{{year=2000, genres=[Adventure, Comedy, Family], title=Snow Day, score=20.998544692993164}} Document{{genres=[Adventure, Comedy, Family], title=Snow Dogs, year=2002, score=20.998544692993164}} Document{{year=1999, genres=[Comedy, Romance], title=Let It Snow, score=19.45327377319336}} Document{{genres=[Action, Comedy, Horror], title=Dead Snow 2: Red vs. Dead, year=2014, score=17.361087799072266}} Document{{genres=[Comedy, Drama], title=Snow White and Russian Red, year=2009, score=16.287294387817383}} Document{{genres=[Comedy, Drama, Romance], title=The Tiger and the Snow, year=2005, score=15.475509643554688}} Document{{genres=[Adventure, Comedy, Family], title=Snow White and the Three Stooges, year=1961, score=14.361087799072266}}
Run an Atlas Search compound query that alters the score using the function
option.
Create a file named
CompoundFunctionQuery.kt
.Copy and paste the following code into the file.
The code example performs the following tasks:
Imports
mongodb
packages and dependencies.Establishes a connection to your Atlas cluster.
Uses the following pipeline stages to query the collection:
must
clause with the range operator to search for movies between the years2013
to2015
.should
clause with the text operator to query for the termsnow
in thetitle
field and alter thescore
with thefunction
option. Thefunction
option adds the following using an arithmetic expression:The relevance score of the query for the search term
The value of the numeric field named
imdb.rating
or the number2
for those documents that do not have theimdb.rating
field.
Uses the following pipeline stages:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Prints the documents that match the query from the
AggregateFlow
instance.
1 import com.mongodb.client.model.Aggregates.limit 2 import com.mongodb.client.model.Aggregates.project 3 import com.mongodb.client.model.Projections.* 4 import com.mongodb.kotlin.client.coroutine.MongoClient 5 import kotlinx.coroutines.runBlocking 6 import org.bson.Document 7 8 fun main() { 9 // establish connection and set namespace 10 val uri = "<connection-string>" 11 val mongoClient = MongoClient.create(uri) 12 13 val database = mongoClient.getDatabase("sample_mflix") 14 val collection = database.getCollection<Document>("movies") 15 16 runBlocking { 17 // define clauses 18 val mustClauses = listOf( 19 Document( 20 "range", Document("path", "year") 21 .append("gte", 2013) 22 .append("lte", 2015) 23 ) 24 ) 25 26 val shouldClauses = listOf( 27 Document("text", Document("query", "snow") 28 .append("path", "title") 29 .append("score", 30 Document("function", Document("add", listOf( 31 Document("path", Document("value", "imdb.rating").append("undefined", 2)), 32 Document("score", "relevance") 33 ))) 34 ) 35 ) 36 ) 37 38 val highlightOption = Document("path", "title") 39 40 // define pipeline 41 val agg = Document( 42 "\$search", 43 Document("index", "compound-query-custom-score-tutorial") 44 .append( 45 "compound", 46 Document("must", mustClauses).append("should", shouldClauses) 47 ) 48 .append("highlight", highlightOption) 49 ) 50 51 // run query and print results 52 val resultsFlow = collection.aggregate<Document>( 53 listOf( 54 agg, 55 limit(10), 56 project(fields( 57 excludeId(), 58 include("title", "year"), 59 computed("score", Document("\$meta", "searchScore")), 60 computed("highlights", Document("\$meta", "searchHighlights")) 61 )) 62 ) 63 ) 64 resultsFlow.collect { println(it) } 65 } 66 mongoClient.close() 67 } Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the
CompoundFunctionQuery.kt
file.When you run the
CompoundFunctionQuery.kt
program in your IDE, it prints the following documents:Document{{title=The Snow White Murder Case, year=2014, score=10.458952903747559, highlights=[Document{{score=1.3525336980819702, path=title, texts=[Document{{value=The , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= White Murder Case, type=text}}]}}]}} Document{{title=Snow on the Blades, year=2014, score=10.336633682250977, highlights=[Document{{score=1.3766303062438965, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= on the Blades, type=text}}]}}]}} Document{{title=Dead Snow 2: Red vs. Dead, year=2014, score=10.036067962646484, highlights=[Document{{score=1.3924485445022583, path=title, texts=[Document{{value=Dead , type=text}}, Document{{value=Snow, type=hit}}, Document{{value= 2: Red vs. , type=text}}]}}]}} Document{{title=Snow in Paradise, year=2014, score=8.392148971557617, highlights=[Document{{score=1.382846713066101, path=title, texts=[Document{{value=Snow, type=hit}}, Document{{value= in Paradise, type=text}}]}}]}} Document{{year=2013, title=The Secret Life of Walter Mitty, score=1.0, highlights=[]}} Document{{title=Jurassic World, year=2015, score=1.0, highlights=[]}} Document{{title=Action Jackson, year=2014, score=1.0, highlights=[]}} Document{{year=2013, title=In Secret, score=1.0, highlights=[]}} Document{{title=The Stanford Prison Experiment, year=2015, score=1.0, highlights=[]}} Document{{year=2014, title=The Giver, score=1.0, highlights=[]}} The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using thefunction
option.
Run an Atlas Search compound query that alters the score using the constant
option.
Create a file named
compound-constant-query.js
.Copy and paste the code example into the
compound-constant-query.js
file.The code example performs the following tasks:
Imports
mongodb
, MongoDB's Node.js driver.Creates an instance of the
MongoClient
class to establish a connection to your Atlas cluster.Uses the following compound clauses to query the collection:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'compound-query-custom-score-tutorial', 8 'compound': { 9 'filter': [ 10 { 11 'range': { 12 'path': 'year', 13 'gte': 2013, 14 'lte': 2015 15 } 16 } 17 ], 18 'should': [ 19 { 20 'text': { 21 'query': 'snow', 22 'path': 'title', 23 'score': { 24 'constant': { 25 'value': 5 26 } 27 } 28 } 29 } 30 ] 31 }, 32 'highlight': { 33 'path': 'title' 34 } 35 } 36 }, { 37 '$limit': 10 38 }, { 39 '$project': { 40 '_id': 0, 41 'title': 1, 42 'year': 1, 43 'score': { 44 '$meta': 'searchScore' 45 }, 46 'highlights': { 47 '$meta': 'searchHighlights' 48 } 49 } 50 } 51 ]; 52 53 MongoClient.connect( 54 "<connection-string>", 55 { useNewUrlParser: true, useUnifiedTopology: true }, 56 async function (connectErr, client) { 57 assert.equal(null, connectErr); 58 const coll = client.db("sample_mflix").collection("movies"); 59 let cursor = await coll.aggregate(agg); 60 await cursor.forEach((doc) => console.log(doc)); 61 client.close(); 62 } 63 ); Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
node compound-constant-query.js '{"title":"Snow in Paradise","year":2014,"score":5,"highlights":[{"score":1.382846713066101,"path":"title","texts":[{"value":"Snow","type":"hit"},{"value":" in Paradise","type":"text"}]}]}' '{"title":"Dead Snow 2: Red vs. Dead","year":2014,"score":5,"highlights":[{"score":1.3924485445022583,"path":"title","texts":[{"value":"Dead ","type":"text"},{"value":"Snow","type":"hit"},{"value":" 2: Red vs. ","type":"text"}]}]}' '{"title":"The Snow White Murder Case","year":2014,"score":5,"highlights":[{"score":1.3525336980819702,"path":"title","texts":[{"value":"The ","type":"text"},{"value":"Snow","type":"hit"},{"value":" White Murder Case","type":"text"}]}]}' '{"title":"Snow on the Blades","year":2014,"score":5,"highlights":[{"score":1.3766303062438965,"path":"title","texts":[{"value":"Snow","type":"hit"},{"value":" on the Blades","type":"text"}]}]}' '{"year":2013,"title":"The Secret Life of Walter Mitty","score":0,"highlights":[]}' '{"title":"Jurassic World","year":2015,"score":0,"highlights":[]}' '{"title":"Action Jackson","year":2014,"score":0,"highlights":[]}' '{"year":2013,"title":"In Secret","score":0,"highlights":[]}' '{"title":"The Stanford Prison Experiment","year":2015,"score":0,"highlights":[]}' '{"year":2014,"title":"The Giver","score":0,"highlights":[]}' The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theconstant
option.
Run an Atlas Search compound query that alters the score using the boost
option.
Create a file named
compound-boost-query.js
.Copy and paste the code example into the
compound-boost-query.js
file.The code example performs the following tasks:
Imports
mongodb
, MongoDB's Node.js driver.Creates an instance of the
MongoClient
class to establish a connection to your Atlas cluster.Iterates over the cursor to print the documents that match the query.
The query uses the following pipeline stages:
$search
stage to query the collection. The query:Uses the following
compound
operator clauses:Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit stage to limit the output to 10 results
$project stage to:
Exclude all fields except
title
andyear
Add two fields named
score
andhighlights
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'compound-query-custom-score-tutorial', 8 'compound': { 9 'must': [ 10 { 11 'range': { 12 'path': 'year', 13 'gte': 2013, 14 'lte': 2015 15 } 16 } 17 ], 18 'should': [ 19 { 20 'text': { 21 'query': 'snow', 22 'path': 'title', 23 'score': { 24 'boost': { 25 'value': 2 26 } 27 } 28 } 29 } 30 ] 31 } 32 } 33 }, { 34 '$limit': 10 35 }, { 36 '$project': { 37 '_id': 0, 38 'title': 1, 39 'year': 1, 40 'score': { 41 '$meta': 'searchScore' 42 } 43 } 44 } 45 ]; 46 47 MongoClient.connect( 48 "<connection-string>", 49 { useNewUrlParser: true, useUnifiedTopology: true }, 50 async function (connectErr, client) { 51 assert.equal(null, connectErr); 52 const coll = client.db("sample_mflix").collection("movies"); 53 let cursor = await coll.aggregate(agg); 54 await cursor.forEach((doc) => console.log(doc)); 55 client.close(); 56 } 57 ); The query uses the following pipeline stages:
$search
stage to query the collection. The query:Uses the following
compound
operator clauses with theboost
option to prioritize some fields more than other fields:must
clause with the text operator to prioritize the genrecomedy
the most, followed by the termsnow
in thetitle
field. Theboost
option applies weights to the fields.should
clause with the range operator to search for movies between the years2013
to2015
.
Note
The
boost
option applies different weights to the fields to prioritize the fields.
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'compound-query-custom-score-tutorial', 8 'compound': { 9 'must': [ 10 { 11 'text': { 12 'path': 'genres', 13 'query': 'comedy', 14 'score': { 15 'boost': { 16 'value': 9 17 } 18 } 19 } 20 }, { 21 'text': { 22 'path': 'title', 23 'query': 'snow', 24 'score': { 25 'boost': { 26 'value': 5 27 } 28 } 29 } 30 } 31 ], 32 'should': [ 33 { 34 'range': { 35 'path': 'year', 36 'gte': 2013, 37 'lte': 2015, 38 'score': { 39 'boost': { 40 'value': 3 41 } 42 } 43 } 44 } 45 ] 46 } 47 } 48 }, { 49 '$limit': 10 50 }, { 51 '$project': { 52 '_id': 0, 53 'title': 1, 54 'year': 1, 55 'genres': 1, 56 'score': { 57 '$meta': 'searchScore' 58 } 59 } 60 } 61 ]; 62 63 MongoClient.connect( 64 "<connection-string>", 65 { useNewUrlParser: true, useUnifiedTopology: true }, 66 async function (connectErr, client) { 67 assert.equal(null, connectErr); 68 const coll = client.db("sample_mflix").collection("movies"); 69 let cursor = await coll.aggregate(agg); 70 await cursor.forEach((doc) => console.log(doc)); 71 client.close(); 72 } 73 ); Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
node compound-boost-query.js '{"title":"Snow in Paradise","year":2014,"score":6.7722930908203125,"highlights":[{"score":1.382846713066101,"path":"title","texts":[{"value":"Snow","type":"hit"},{"value":" in Paradise","type":"text"}]}]}' '{"title":"Snow on the Blades","year":2014,"score":6.063445568084717,"highlights":[{"score":1.3766303062438965,"path":"title","texts":[{"value":"Snow","type":"hit"},{"value":" on the Blades","type":"text"}]}]}' '{"title":"The Snow White Murder Case","year":2014,"score":5.509652137756348,"highlights":[{"score":1.3525336980819702,"path":"title","texts":[{"value":"The ","type":"text"},{"value":"Snow","type":"hit"},{"value":" White Murder Case","type":"text"}]}]}' '{"title":"Dead Snow 2: Red vs. Dead","year":2014,"score":5.065053939819336,"highlights":[{"score":1.3924485445022583,"path":"title","texts":[{"value":"Dead ","type":"text"},{"value":"Snow","type":"hit"},{"value":" 2: Red vs. ","type":"text"}]}]}' '{"year":2013,"title":"The Secret Life of Walter Mitty","score":1,"highlights":[]}' '{"title":"Jurassic World","year":2015,"score":1,"highlights":[]}' '{"title":"Action Jackson","year":2014,"score":1,"highlights":[]}' '{"year":2013,"title":"In Secret","score":1,"highlights":[]}' '{"title":"The Stanford Prison Experiment","year":2015,"score":1,"highlights":[]}' '{"year":2014,"title":"The Giver","score":1,"highlights":[]}' The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theboost
option.node compound-boost-query.js { genres: [ 'Comedy', 'Horror' ], title: 'Dead Snow', year: 2009, score: 21.872983932495117 } { year: 2000, genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow Day', score: 21.043487548828125 } { genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow Dogs', year: 2002, score: 21.043487548828125 } { year: 1999, genres: [ 'Comedy', 'Romance' ], title: 'Let It Snow', score: 19.523927688598633 } { genres: [ 'Action', 'Comedy', 'Horror' ], title: 'Dead Snow 2: Red vs. Dead', year: 2014, score: 17.426334381103516 } { genres: [ 'Comedy', 'Drama' ], title: 'Snow White and Russian Red', year: 2009, score: 16.367326736450195 } { genres: [ 'Comedy', 'Drama', 'Romance' ], title: 'The Tiger and the Snow', year: 2005, score: 15.537829399108887 } { genres: [ 'Adventure', 'Comedy', 'Family' ], title: 'Snow White and the Three Stooges', year: 1961, score: 14.4263334274292 }
Run an Atlas Search compound query that alters the score using the function
option.
Create a file named
compound-function-query.js
.Copy and paste the code example into the
compound-function-query.js
file.The code example performs the following tasks:
Imports
mongodb
, MongoDB's Node.js driver.Creates an instance of the
MongoClient
class to establish a connection to your Atlas cluster.Uses the following compound clauses to query the collection:
must
clause with the range operator to search for movies between the years2013
to2015
.should
clause with the text operator to query for the termsnow
in thetitle
field and alter thescore
with thefunction
option. Thefunction
option adds the following using an arithmetic expression:The relevance score of the query for the search term
The value of the numeric field named
imdb.rating
or the number2
for those documents that do not have theimdb.rating
field.
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 const MongoClient = require("mongodb").MongoClient; 2 const assert = require("assert"); 3 4 const agg = [ 5 { 6 '$search': { 7 'index': 'compound-query-custom-score-tutorial', 8 'compound': { 9 'must': [ 10 { 11 'range': { 12 'path': 'year', 13 'gte': 2013, 14 'lte': 2015 15 } 16 } 17 ], 18 'should': [ 19 { 20 'text': { 21 'query': 'snow', 22 'path': 'title', 23 'score': { 24 'function': { 25 'add': [ 26 { 27 'path': { 28 'value': 'imdb.rating', 29 'undefined': 2 30 } 31 }, { 32 'score': 'relevance' 33 } 34 ] 35 } 36 } 37 } 38 } 39 ] 40 } 41 } 42 }, { 43 '$limit': 10 44 }, { 45 '$project': { 46 '_id': 0, 47 'title': 1, 48 'year': 1, 49 'score': { 50 '$meta': 'searchScore' 51 }, 52 'highlights': { 53 '$meta': 'searchHighlights' 54 } 55 } 56 } 57 ]; 58 59 MongoClient.connect( 60 "<connection-string>", 61 { useNewUrlParser: true, useUnifiedTopology: true }, 62 async function (connectErr, client) { 63 assert.equal(null, connectErr); 64 const coll = client.db("sample_mflix").collection("movies"); 65 let cursor = await coll.aggregate(agg); 66 await cursor.forEach((doc) => console.log(doc)); 67 client.close(); 68 } 69 ); Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
node compound-function-query.js '{"title":"The Snow White Murder Case","year":2014,"score":10.454826354980469,"highlights":[{"score":1.3525336980819702,"path":"title","texts":[{"value":"The ","type":"text"},{"value":"Snow","type":"hit"},{"value":" White Murder Case","type":"text"}]}]}' '{"title":"Snow on the Blades","year":2014,"score":10.3317232131958,"highlights":[{"score":1.3766303062438965,"path":"title","texts":[{"value":"Snow","type":"hit"},{"value":" on the Blades","type":"text"}]}]}' '{"title":"Dead Snow 2: Red vs. Dead","year":2014,"score":10.032526969909668,"highlights":[{"score":1.3924485445022583,"path":"title","texts":[{"value":"Dead ","type":"text"},{"value":"Snow","type":"hit"},{"value":" 2: Red vs. ","type":"text"}]}]}' '{"title":"Snow in Paradise","year":2014,"score":8.386146545410156,"highlights":[{"score":1.382846713066101,"path":"title","texts":[{"value":"Snow","type":"hit"},{"value":" in Paradise","type":"text"}]}]}' '{"year":2013,"title":"The Secret Life of Walter Mitty","score":1,"highlights":[]}' '{"title":"Jurassic World","year":2015,"score":1,"highlights":[]}' '{"title":"Action Jackson","year":2014,"score":1,"highlights":[]}' '{"year":2013,"title":"In Secret","score":1,"highlights":[]}' '{"title":"The Stanford Prison Experiment","year":2015,"score":1,"highlights":[]}' '{"year":2014,"title":"The Giver","score":1,"highlights":[]}' The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using thefunction
option.
Run an Atlas Search compound query that alters the score using the constant
option.
Create a file named
compound-constant-query.py
.Copy and paste the code example into the
compound-constant.py
file.The following code example:
Imports
pymongo
, MongoDB's Python driver, and thedns
module, which is required to connectpymongo
toAtlas
using a DNS seed list connection string.Creates an instance of the
MongoClient
class to establish a connection to your Atlas cluster.Uses the following compound clauses to query the collection:
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 {'$search': { 9 'index': 'compound-query-custom-score-tutorial', 10 'compound': { 11 'filter': [{'range': {'path': 'year', 'gte': 2013, 'lte': 2015}}], 12 'should': [{'text': {'query': 'snow', 'path': 'title', 'score': {'constant': {'value': 5}}}}]}, 13 'highlight': {'path': 'title'}}}, 14 {'$limit': 10}, 15 {'$project': {'_id': 0, 'title': 1, 'year': 1, 16 'score': {'$meta': 'searchScore'}, "highlights": {"$meta": "searchHighlights"}}} 17 ] 18 19 # run pipeline 20 result = client['sample_mflix']['movies'].aggregate(pipeline) 21 22 # print results 23 for i in result: 24 print(i) Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
python compound-constant-query.py {'highlights': [{'path': 'title', 'score': 1.382846713066101, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' in Paradise'}]}], 'year': 2014, 'score': 5.0, 'title': 'Snow in Paradise'} {'highlights': [{'path': 'title', 'score': 1.3924485445022583, 'texts': [{'type': 'text', 'value': 'Dead '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' 2: Red vs. '}]}], 'year': 2014, 'score': 5.0, 'title': 'Dead Snow 2: Red vs. Dead'} {'highlights': [{'path': 'title', 'score': 1.3525336980819702, 'texts': [{'type': 'text', 'value': 'The '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' White Murder Case'}]}], 'year': 2014, 'score': 5.0, 'title': 'The Snow White Murder Case'} {'highlights': [{'path': 'title', 'score': 1.3766303062438965, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' on the Blades'}]}], 'year': 2014, 'score': 5.0, 'title': 'Snow on the Blades'} {'highlights': [], 'title': 'The Secret Life of Walter Mitty', 'score': 0.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 0.0, 'title': 'Jurassic World'} {'highlights': [], 'year': 2014, 'score': 0.0, 'title': 'Action Jackson'} {'highlights': [], 'title': 'In Secret', 'score': 0.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 0.0, 'title': 'The Stanford Prison Experiment'} {'highlights': [], 'title': 'The Giver', 'score': 0.0, 'year': 2014} The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theconstant
option.
Run an Atlas Search compound query that alters the score using the boost
option.
Create a file named
compound-boost-query.py
.Copy and paste the code example into the
compound-boost-query.py
file.The following code example:
Imports
pymongo
, MongoDB's Python driver, and thedns
module, which is required to connectpymongo
toAtlas
using a DNS seed list connection string.Creates an instance of the
MongoClient
class to establish a connection to your Atlas cluster.Iterates over the cursor to print the documents that match the query.
The query uses the following pipeline stages:
$search
stage to query the collection. The query:Uses the following
compound
operator clauses:must
clause with the range operator to search for movies between the years2013
to2015
.should
clause with the text operator to query for the termsnow
in thetitle
field and alter thescore
with theboost
option. Theboost
option multiplies the base score in the results for the search term by2
.
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.
$limit stage to limit the output to 10 results
$project stage to:
Exclude all fields except
title
andyear
Add two fields named
score
andhighlights
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 {'$search': { 9 'index': 'compound-query-custom-score-tutorial', 10 'compound': { 11 'must': [{'range': {'path': 'year', 'gte': 2013, 'lte': 2015}}], 12 'should': [{'text': {'query': 'snow', 'path': 'title', 'score': {'boost': {'value': 2}}}}]}, 13 'highlight': {'path': 'title'}}}, 14 {'$limit': 10}, 15 {'$project': {'_id': 0, 'title': 1, 'year': 1, 'score': {'$meta': 'searchScore'}, "highlights": {"$meta": "searchHighlights"}}} 16 ] 17 18 # run pipeline 19 result = client['sample_mflix']['movies'].aggregate(pipeline) 20 21 # print results 22 for i in result: 23 print(i) The query uses the following pipeline stages:
$search
stage to query the collection. The query uses the followingcompound
operator clauses with theboost
option to prioritize some fields more than other fields:must
clause with the text operator to prioritize the genrecomedy
the most, followed by the termsnow
in thetitle
field. Theboost
option applies weights to the fields.should
clause with the range operator to search for movies between the years2013
to2015
.
Note
The
boost
option applies different weights to the fields to prioritize the fields.$limit
stage to limit the output to10
results.$project
stage to:Exclude all fields except
title
,year
, andgenres
Add a field named
score
import pymongo import dns client = pymongo.MongoClient('<connection-string>') result = client['sample_mflix']['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' } } } ]) for i in result: print(i) Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
python compound-boost-query.py {'highlights': [{'path': 'title', 'score': 1.382846713066101, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' in Paradise'}]}], 'year': 2014, 'score': 6.7722930908203125, 'title': 'Snow in Paradise'} {'highlights': [{'path': 'title', 'score': 1.3766303062438965, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' on the Blades'}]}], 'year': 2014, 'score': 6.063445568084717, 'title': 'Snow on the Blades'} {'highlights': [{'path': 'title', 'score': 1.3525336980819702, 'texts': [{'type': 'text', 'value': 'The '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' White Murder Case'}]}], 'year': 2014, 'score': 5.509652137756348, 'title': 'The Snow White Murder Case'} {'highlights': [{'path': 'title', 'score': 1.3924485445022583, 'texts': [{'type': 'text', 'value': 'Dead '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' 2: Red vs. '}]}], 'year': 2014, 'score': 5.065053939819336, 'title': 'Dead Snow 2: Red vs. Dead'} {'highlights': [], 'title': 'The Secret Life of Walter Mitty', 'score': 1.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'Jurassic World'} {'highlights': [], 'year': 2014, 'score': 1.0, 'title': 'Action Jackson'} {'highlights': [], 'title': 'In Secret', 'score': 1.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'The Stanford Prison Experiment'} {'highlights': [], 'title': 'The Giver', 'score': 1.0, 'year': 2014} The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using theboost
option.python compound-boost-query.py { 'genres': ['Comedy', 'Horror'], 'title': 'Dead Snow', 'year': 2009, 'score': 21.872983932495117 } { 'year': 2000, 'genres': ['Adventure', 'Comedy', 'Family'], 'title': 'Snow Day', 'score': 21.043487548828125 } { 'genres': ['Adventure', 'Comedy', 'Family'], 'title': 'Snow Dogs', 'year': 2002, 'score': 21.043487548828125 } { 'year': 1999, 'genres': ['Comedy', 'Romance'], 'title': 'Let It Snow', 'score': 19.523927688598633 } { 'genres': ['Action', 'Comedy', 'Horror'], 'title': 'Dead Snow 2: Red vs. Dead', 'year': 2014, 'score': 17.426334381103516 } { 'genres': ['Comedy', 'Drama'], 'title': 'Snow White and Russian Red', 'year': 2009, 'score': 16.367326736450195 } { 'genres': ['Comedy', 'Drama', 'Romance'], 'title': 'The Tiger and the Snow', 'year': 2005, 'score': 15.537829399108887 } { 'genres': ['Adventure', 'Comedy', 'Family'], 'title': 'Snow White and the Three Stooges', 'year': 1961, 'score': 14.4263334274292 }
Run an Atlas Search compound query that alters the score using the function
option.
Create a file named
compound-function-query.py
.Copy and paste the code example into the
compound-function-query.py
file.The following code example:
Imports
pymongo
, MongoDB's Python driver, and thedns
module, which is required to connectpymongo
toAtlas
using a DNS seed list connection string.Creates an instance of the
MongoClient
class to establish a connection to your Atlas cluster.Uses the following compound clauses to query the collection:
must
clause with the range operator to search for movies between the years2013
to2015
.should
clause with the text operator to query for the termsnow
in thetitle
field and alter thescore
with thefunction
option. Thefunction
option adds the following using an arithmetic expression:The relevance score of the query for the search term
The value of the numeric field named
imdb.rating
or the number2
for those documents that do not have theimdb.rating
field.
Specifies the highlight option to return snippets of text from the
title
field that match the query. The snippets contain matching text specified withtype: 'hit'
, and adjacent text specified withtype: 'text'
.Uses the following pipeline stages:
Iterates over the cursor to print the documents that match the query.
1 import pymongo 2 3 # connect to your Atlas cluster 4 client = pymongo.MongoClient('<connection-string>') 5 6 # define pipeline 7 pipeline = [ 8 {'$search': { 9 'index': 'compound-query-custom-score-tutorial', 10 'compound': { 11 'must': [{'range': {'path': 'year', 'gte': 2013, 'lte': 2015}}], 12 'should': [{'text': {'query': 'snow', 'path': 'title', 13 'score': {'function': { 14 'add': [{'path': {'value': 'imdb.rating','undefined': 2}}, {'score': 'relevance'}]}}}}]}, 15 'highlight': {'path': 'title'}}}, 16 {'$limit': 10}, 17 {'$project': {'_id': 0, 'title': 1, 'year': 1, 'score': {'$meta': 'searchScore'}, "highlights": {"$meta": "searchHighlights"}}} 18 ] 19 20 # run pipeline 21 result = client['sample_mflix']['movies'].aggregate(pipeline) 22 23 # print results 24 for i in result: 25 print(i) Before you run the sample, replace
<connection-string>
with your Atlas connection string. Ensure that your connection string includes your database user's credentials. To learn more, see Connect via Drivers.Run the following command to query your collection:
python compound-function-query.py {'highlights': [{'path': 'title', 'score': 1.3525336980819702, 'texts': [{'type': 'text', 'value': 'The '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' White Murder Case'}]}], 'year': 2014, 'score': 10.454826354980469, 'title': 'The Snow White Murder Case'} {'highlights': [{'path': 'title', 'score': 1.3766303062438965, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' on the Blades'}]}], 'year': 2014, 'score': 10.3317232131958, 'title': 'Snow on the Blades'} {'highlights': [{'path': 'title', 'score': 1.3924485445022583, 'texts': [{'type': 'text', 'value': 'Dead '}, {'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' 2: Red vs. '}]}], 'year': 2014, 'score': 10.032526969909668, 'title': 'Dead Snow 2: Red vs. Dead'} {'highlights': [{'path': 'title', 'score': 1.382846713066101, 'texts': [{'type': 'hit', 'value': 'Snow'}, {'type': 'text', 'value': ' in Paradise'}]}], 'year': 2014, 'score': 8.386146545410156, 'title': 'Snow in Paradise'} {'highlights': [], 'title': 'The Secret Life of Walter Mitty', 'score': 1.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'Jurassic World'} {'highlights': [], 'year': 2014, 'score': 1.0, 'title': 'Action Jackson'} {'highlights': [], 'title': 'In Secret', 'score': 1.0, 'year': 2013} {'highlights': [], 'year': 2015, 'score': 1.0, 'title': 'The Stanford Prison Experiment'} {'highlights': [], 'title': 'The Giver', 'score': 1.0, 'year': 2014} The first four documents in the results have a higher score because the
should
clause in the query specifies a preference for documents withsnow
in the title. Theshould
clause also alters the score for the query termsnow
using thefunction
option.
Continue Learning
To learn more about compound queries using Atlas Search, take
Unit 9 of the Intro To MongoDB Course on MongoDB University. The 1.5
hour unit includes an overview of Atlas Search and lessons on creating Atlas Search
indexes, running $search
queries using compound operators,
and grouping results using facet.