Docs Menu
Docs Home
/
MongoDB Atlas
/ /

가중치 필드로 Atlas Search 복합 쿼리를 실행하는 방법

이 페이지의 내용

  • 동적 매핑으로 Atlas Search 인덱스 만들기
  • 복합 쿼리 실행
  • 복합 쿼리를 실행하여 결과 개선
  • 복합 쿼리를 실행하여 결과 숨기기
  • 학습 계속하기

이 튜토리얼에서는 검색 필드에 가중치를 추가하여 결과나 결과 카테고리에서 문서를 순위를 높이거나 낮추는 방법을 보여줍니다. 하나 이상의 값을 필드에 할당하여 더 높거나 낮은 점수의 결과를 반환하는 방법을 보여 줍니다.

특히, 자습서에서는 sample_mflix.movies 컬렉션에서 동적 매핑을 사용하여 인덱스를 만드는 방법을 보여줍니다. , constant, function, boost를 사용하여 복합 쿼리를 실행하고 점수를 변경하는 방법을 보여줍니다. 다음 단계에 따르세요.

  1. sample_mflix.movies collection에 대한 동적 매핑을 사용하여 Atlas Search 인덱스를 설정합니다.

  2. 다음 Atlas Search 쿼리를 실행하세요.

    • year 필드를 쿼리하고 title 필드의 특정 단어를 사용하여 점수를 변경해서 결과의 문서를 부스트합니다.

    • titleplot 필드를 쿼리하여 genres 필드에서 특정 장르에 따라 점수를 변경하여 해당 장르의 결과를 낮춥니다.

시작하기 전에 Atlas 클러스터가 필수구성 요소에 설명된 요건을 충족하는지 확인하십시오.

Atlas Search 인덱스를 생성하려면 프로젝트에 대한 Project Data Access Admin 이상의 액세스 권한이 있어야 합니다.

이 섹션에서는 동적 매핑을 사용하여 sample_mflix.movies 컬렉션의 필드를 인덱싱하는 Atlas Search 인덱스를 생성합니다.

1
  1. 아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.

  2. 아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.

  3. 아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.

    클러스터 페이지가 표시됩니다.

2

사이드바, Data Explorer 또는 클러스터 세부 정보 페이지에서 Atlas Search 페이지로 이동할 수 있습니다.

  1. 사이드바에서 Services 제목 아래의 Atlas Search를 클릭합니다.

    참고

    클러스터가 없는 경우 을 Create cluster 클릭하여 클러스터를 생성합니다. 자세한 학습 은 클러스터 생성을 참조하세요.

  2. Select data source 드롭다운에서 클러스터를 선택하고 Go to Atlas Search를 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

  1. cluster의 Browse Collections 버튼을 클릭합니다.

  2. 데이터베이스를 확장하고 컬렉션을 선택합니다.

  3. 컬렉션의 Search Indexes 탭을 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

  1. 클러스터 이름을 클릭합니다.

  2. Atlas Search 탭을 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

3
4

페이지에서 다음 항목을 선택한 다음 Next을(를) 클릭합니다.

Search Type

Atlas Search 인덱스 유형을 선택합니다.

Index Name and Data Source

다음 정보를 지정합니다.

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

  • Database and Collection:

    • sample_mflix database

    • movies 컬렉션

Configuration Method

For a guided experience, select Visual Editor.

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

동적 매핑 또는 정적 매핑을 사용하는 Atlas Search 인덱스를 만들 수 있습니다. 동적 및 정적 매핑에 대해 자세히 알아보려면 정적 및 동적 매핑을 참조하세요.

다음 인덱스 정의는 movies 컬렉션에서 지원되는 유형의 필드를 동적으로 인덱싱합니다. Atlas user 인터페이스에서 Atlas Search Visual Editor 또는 Atlas Search JSON Editor을(를) 사용하여 인덱스를 생성할 수 있습니다.

movies 컬렉션에 대한 "default" 인덱스 정의를 검토합니다.

  1. 인덱스 정의를 검토합니다.

    인덱스 정의는 다음과 비슷해야 합니다:

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

    위의 인덱스 정의는 movies 컬렉션의 각 문서에서 지원되는 유형의 필드를 동적으로 인덱싱합니다.

  2. Next를 클릭합니다.

6
7

인덱스가 작성 중임을 보여주는 모달 창이 표시됩니다. Close 버튼을 클릭합니다.

8

인덱스 작성에는 약 1분 정도가 소요됩니다. 작성하는 동안 Status 열은 Build in Progress을 읽습니다. 작성이 완료되면 Status 열에 Active이 표시됩니다.

복합 연산자를 사용하여 두 개 이상의 연산자를 단일 쿼리로 결합합니다. Atlas Search는 쿼리에 대해 반환하는 모든 문서에 관련성에 따라 가장 높은 점수부터 가장 낮은 점수 순으로 점수를 부여합니다. 쿼리는 결과에서 문서를 부스트(boost)하거나 묻는(bury) 방법을 보여줍니다.


언어 선택 드롭다운 메뉴를 사용하여 이 섹션에 있는 예시의 언어를 설정합니다.


Atlas Search는 지침과 함께 샘플 복합 쿼리 템플릿을 제공합니다. 자세히 알아보려면 쿼리 지침 템플릿 보기를 참조하세요.

이 섹션에서는 Atlas 클러스터에 연결하고 sample_mflix.movies 컬렉션의 titleyear 필드에 대해 복합 연산자를 사용하여 샘플 쿼리를 실행합니다. 샘플 쿼리는 사용자 지정 점수를 사용하여 snow 용어가 포함된 영화 제목에 대해 Atlas Search에서 반환한 관련성 점수를 변경합니다.

1
  1. 아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.

  2. 아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.

  3. 아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.

    Clusters(클러스터) 페이지가 표시됩니다.

2

사이드바, Data Explorer 또는 클러스터 세부 정보 페이지에서 Atlas Search 페이지로 이동할 수 있습니다.

  1. 사이드바에서 Services 제목 아래의 Atlas Search를 클릭합니다.

    참고

    클러스터가 없는 경우 을 Create cluster 클릭하여 클러스터를 생성합니다. 자세한 학습 은 클러스터 생성을 참조하세요.

  2. Select data source 드롭다운에서 클러스터를 선택하고 Go to Atlas Search를 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

  1. cluster의 Browse Collections 버튼을 클릭합니다.

  2. 데이터베이스를 확장하고 컬렉션을 선택합니다.

  3. 컬렉션의 Search Indexes 탭을 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

  1. 클러스터 이름을 클릭합니다.

  2. Atlas Search 탭을 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

3

쿼리할 인덱스 오른쪽에 있는 Query 버튼을 클릭합니다.

4

Edit Query 을 클릭하면 JSON 형식의 기본 쿼리 구문 샘플을 볼 수 있습니다.

5

다음 쿼리를 복사하여 Query Editor에 붙여 넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.

다음 예에서는 하위 쿼리와 함께 compound 연산자를 사용하여 title 필드에 snow 이라는 용어가 포함된 2013 ~ 2015 년 사이의 영화를 검색합니다.

다음 쿼리입니다:

  • 다음 compound 연산자 절을 사용합니다:

    • filter 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

    • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 constant 옵션으로 score를 변경합니다. constant 옵션은 검색어에 대한 모든 점수 결과를 5로 바꿉니다.

  • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

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

쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 constant 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.constant

다음 쿼리입니다:

  • 다음 compound 연산자 절을 사용합니다:

    • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

    • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 boost 옵션으로 score를 변경합니다. boost 옵션은 검색어에 대한 결과의 기본 점수에 2를 곱합니다.

  • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

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

쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 boost 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.boost

다음 쿼리입니다:

  • 다음 compound 연산자 절을 boost 옵션과 함께 사용하여 일부 필드의 우선 순위를 다른 필드보다 높게 지정합니다.

    • must 절로 가장 우선시하는 장르 comedy텍스트 연산자와 함께 지정한 다음 title 필드에 snow라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다. boost 옵션은 필드에 가중치를 적용합니다.

    • should 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

    참고

    boost 옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.

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

다음 쿼리입니다:

  • 다음 compound 연산자 절을 사용합니다:

    • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

    • should 절은 text 연산자를 사용하여 title 필드에서 snow라는 텀을 쿼리하고 function 옵션을 사용하여 score를 변경합니다. function 옵션은 산술 표현식을 사용하여 다음을 추가합니다.

      • 검색어에 대한 쿼리의 관련성 점수입니다.

      • imdb.rating 필드가 없는 문서의 경우 imdb.rating이라는 숫자 필드의 값이나 숫자 2 를 사용합니다.

  • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

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

쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 function 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.function

6

Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.

1

터미널 창에서 mongosh 를 열고 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh 를 통한 연결을 참조하세요.

2

mongosh 프롬프트에서 다음 명령을 실행합니다.

use sample_mflix
3

다음 예에서는 하위 쿼리와 함께 compound 연산자를 사용하여 title 필드에 snow 이라는 용어가 포함된 2013 ~ 2015 년 사이의 영화를 검색합니다.

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • $search 를 클릭하여 collection을 쿼리합니다. 쿼리:

    • 다음 compound 연산자 절을 사용합니다:

      • filter 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 constant 옵션으로 score를 변경합니다. constant 옵션은 검색어에 대한 모든 점수 결과를 5로 바꿉니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

  • $limit 단계는 출력을 10 결과로만 제한합니다.

  • $project 단계로 이동합니다:

    • titleyear을 제외한 모든 필드를 제외합니다.

    • score 필드를 추가합니다.

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

Atlas Search는 constant에 대해 다음 결과를 반환합니다.

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

쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 constant 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.constant

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • $search 를 클릭하여 collection을 쿼리합니다. 쿼리:

    • 다음 compound 연산자 절을 사용합니다:

      • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 boost 옵션으로 score를 변경합니다. boost 옵션은 검색어에 대한 결과의 기본 점수에 2를 곱합니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

  • $limit 단계는 출력을 10 결과로만 제한합니다.

  • $project 단계로 이동합니다:

    • titleyear을 제외한 모든 필드를 제외합니다.

    • score 필드를 추가합니다.

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

Atlas Search는 boost에 대해 다음 결과를 반환합니다.

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

쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 boost 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.boost

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • $search를 사용하여 컬렉션을 쿼리합니다. 쿼리는 다음 compound 연산자 절을 boost 옵션과 함께 사용하여 일부 필드의 우선 순위를 다른 필드보다 높게 지정합니다.

    • must 절로 가장 우선시하는 장르 comedy텍스트 연산자와 함께 지정한 다음 title 필드에 snow라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다. boost 옵션은 필드에 가중치를 적용합니다.

    • should 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

    참고

    boost 옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.

  • $limit 단계는 출력을 10 결과로만 제한합니다.

  • $project 단계로 이동합니다:

    • title, year, genres 이외의 모든 필드 제외

    • score 필드를 추가합니다.

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

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • $search 를 클릭하여 collection을 쿼리합니다. 쿼리:

    • 다음 compound 연산자 절을 사용합니다:

      • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절은 text 연산자를 사용하여 title 필드에서 snow라는 텀을 쿼리하고 function 옵션을 사용하여 score를 변경합니다. function 옵션은 산술 표현식을 사용하여 다음을 추가합니다.

        • 검색어에 대한 쿼리의 관련성 점수입니다.

        • imdb.rating 필드가 없는 문서의 경우 imdb.rating이라는 숫자 필드의 값이나 숫자 2 를 사용합니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

  • $limit 단계는 출력을 10 결과로만 제한합니다.

  • $project 단계로 이동합니다:

    • titleyear을 제외한 모든 필드를 제외합니다.

    • score 필드를 추가합니다.

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

Atlas Search는 function에 대해 다음 결과를 반환합니다.

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

쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 function 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.function

1

MongoDB Compass를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.

2

Database 화면에서 sample_mflix 데이터베이스를 클릭한 다음 movies collection을 클릭합니다.

3

이 쿼리는 다음 작업을 수행합니다.

  • 다음 compound 연산자 절을 사용합니다:

    • filter 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

    • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 constant 옵션으로 score를 변경합니다. constant 옵션은 검색어에 대한 모든 점수 결과를 5로 바꿉니다.

  • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

  • 다음 파이프라인 단계를 사용합니다:

    • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

    • $project 단계에서 다음을 수행합니다:

      • titleyear을 제외한 모든 필드를 제외합니다.

      • scorehighlights 이라는 두 필드를 추가합니다.

MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.

  1. Aggregations 탭을 클릭합니다.

  2. Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.

    파이프라인 단계
    쿼리

    $search

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

    $limit

    10

    $project

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

    Auto Preview활성화한 경우 MongoDB Compass는 $project 파이프라인 단계 옆에 다음 문서를 표시합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 constant 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.constant

4
  1. Aggregations 탭을 클릭합니다.

  2. Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.

    쿼리는 다음 파이프라인 단계를 사용합니다:

    • $search 다음 작업을 수행합니다.

      • 다음 compound 연산자 절을 사용하는 쿼리:

        • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

        • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 boost 옵션으로 score를 변경합니다. boost 옵션은 검색어에 대한 결과의 기본 점수에 2를 곱합니다.

      • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

    • $project 단계에서 다음을 수행합니다:

      • titleyear을 제외한 모든 필드를 제외합니다.

      • scorehighlights 이라는 두 필드를 추가합니다.

    파이프라인 단계
    쿼리

    $search

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

    $limit

    10

    $project

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

    이 쿼리는 다음 파이프라인 단계를 사용합니다:

    • $search 다음 작업을 수행합니다.

      • 일부 필드를 다른 필드보다 더 우선시하기 위해 compound 연산자 절을 boost 옵션과 함께 사용하는 쿼리:

        • must 절로 가장 우선시하는 장르 comedy텍스트 연산자와 함께 지정한 다음 title 필드에 snow라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다. boost 옵션은 필드에 가중치를 적용합니다.

        • should 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

        참고

        boost 옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.

    • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

    • $project 단계에서 다음을 수행합니다:

      • titleyear을 제외한 모든 필드를 제외합니다.

      • scorehighlights 이라는 두 필드를 추가합니다.

    • must 절로 가장 우선시하는 장르 comedy텍스트 연산자와 함께 지정한 다음 title 필드에 snow라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다. boost 옵션은 필드에 가중치를 적용합니다.

    • should 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

    참고

    boost 옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.

    파이프라인 단계
    쿼리

    $search

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

    $limit

    10

    $project

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

    Auto Preview활성화한 경우 MongoDB Compass는 $project 파이프라인 단계 옆에 다음 문서를 표시합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 boost 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.boost

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

쿼리는 다음 파이프라인 단계를 사용합니다:

  • $search 다음 작업을 수행하기 위한 단계입니다.

    • 다음 compound 연산자 절을 사용하는 쿼리:

      • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절은 text 연산자를 사용하여 title 필드에서 snow라는 텀을 쿼리하고 function 옵션을 사용하여 score를 변경합니다. function 옵션은 산술 표현식을 사용하여 다음을 추가합니다.

        • 검색어에 대한 쿼리의 관련성 점수입니다.

        • imdb.rating 필드가 없는 문서의 경우 imdb.rating이라는 숫자 필드의 값이나 숫자 2 를 사용합니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

  • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

  • $project 단계에서 다음을 수행합니다:

    • titleyear을 제외한 모든 필드를 제외합니다.

    • scorehighlights 이라는 두 필드를 추가합니다.

MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.

  1. Aggregations 탭을 클릭합니다.

  2. Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.

    파이프라인 단계
    쿼리

    $search

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

    $limit

    10

    $project

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

    Auto Preview활성화한 경우 MongoDB Compass는 $project 파이프라인 단계 옆에 다음 문서를 표시합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 function 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.function

1
  1. compound-constant-example라는 새 디렉토리를 만들고 dotnet new 명령으로 프로젝트를 초기화합니다.

    mkdir compound-constant-example
    cd compound-constant-example
    dotnet new console
  2. .NET/C# 드라이버를 프로젝트에 종속성으로 추가합니다.

    dotnet add package MongoDB.Driver
  3. Program.cs 파일의 내용을 다음 코드로 바꿉니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 복합 절을 사용하여 컬렉션을 쿼리합니다.

      • filter 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 constant 옵션으로 score를 변경합니다. constant 옵션은 검색어에 대한 모든 점수 결과를 5로 바꿉니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundConstantExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // define and run pipeline
    23 var results = moviesCollection.Aggregate()
    24 .Search(Builders<MovieDocument>.Search.Compound()
    25 .Filter(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015)))
    26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Constant(5))),
    27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title),
    28 indexName: "compound-query-custom-score-tutorial")
    29 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    30 .Include(movie => movie.Title)
    31 .Include(movie => movie.Year)
    32 .Exclude(movie => movie.Id)
    33 .MetaSearchScore(movie => movie.Score)
    34 .MetaSearchHighlights("highlights"))
    35 .Limit(10)
    36 .ToList();
    37
    38 // print results
    39 foreach (var movie in results)
    40 {
    41 Console.WriteLine(movie.ToJson());
    42 }
    43 }
    44}
    45
    46[BsonIgnoreExtraElements]
    47public class MovieDocument
    48{
    49 [BsonIgnoreIfDefault]
    50 public ObjectId Id { get; set; }
    51 public string Title { get; set; }
    52 public int Year { get; set; }
    53 [BsonElement("highlights")]
    54 public List<SearchHighlight> Highlights { get; set; }
    55 public double Score { get; set; }
    56}
  4. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  5. Program.cs 파일을 컴파일하고 실행합니다.

    dotnet run compound-constant-example.csproj
    {
    "title" : "Snow in Paradise",
    "year" : 2014,
    "highlights" : [{
    "path" : "title",
    "score" : 1.3828467130661011,
    "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " in Paradise" }]
    }],
    "score" : 5.0
    }
    {
    "title" : "Dead Snow 2: Red vs. Dead",
    "year" : 2014,
    "highlights" : [{
    "path" : "title",
    "score" : 1.3924485445022583,
    "texts" : [{ "type" : "Text", "value" : "Dead " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " 2: Red vs. " }]
    }],
    "score" : 5.0
    }
    {
    "title" : "The Snow White Murder Case",
    "year" : 2014,
    "highlights" : [{
    "path" : "title",
    "score" : 1.3525336980819702,
    "texts" : [{ "type" : "Text", "value" : "The " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " White Murder Case" }]
    }],
    "score" : 5.0
    }
    {
    "title" : "Snow on the Blades",
    "year" : 2014,
    "highlights" : [{
    "path" : "title",
    "score" : 1.3766303062438965,
    "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " on the Blades" }]
    }],
    "score" : 5.0
    }
    { "title" : "The Secret Life of Walter Mitty", "year" : 2013, "highlights" : [], "score" : 0.0 }
    { "title" : "Jurassic World", "year" : 2015, "highlights" : [], "score" : 0.0 }
    { "title" : "Action Jackson", "year" : 2014, "highlights" : [], "score" : 0.0 }
    { "title" : "In Secret", "year" : 2013, "highlights" : [], "score" : 0.0 }
    { "title" : "The Stanford Prison Experiment", "year" : 2015, "highlights" : [], "score" : 0.0 }
    { "title" : "The Giver", "year" : 2014, "highlights" : [], "score" : 0.0 }

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 constant 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.constant

2
  1. compound-boost-example라는 새 디렉토리를 만들고 dotnet new 명령으로 프로젝트를 초기화합니다.

    mkdir compound-boost-example
    cd compound-boost-example
    dotnet new console
  2. .NET/C# 드라이버를 프로젝트에 종속성으로 추가합니다.

    dotnet add package MongoDB.Driver
  3. Program.cs 파일의 내용을 다음 코드로 바꿉니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    쿼리는 다음 파이프라인 단계를 사용합니다:

    • $search 단계를 통해 collection을 쿼리할 수 있습니다. 쿼리:

      • 다음 compound 연산자 절을 사용합니다:

        • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

        • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 boost 옵션으로 score를 변경합니다. boost 옵션은 검색어에 대한 결과의 기본 점수에 2를 곱합니다.

      title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

    • $project 단계에서 다음을 수행합니다:

      • titleyear을 제외한 모든 필드를 제외합니다.

      • scorehighlights 이라는 두 필드를 추가합니다.

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

    이 쿼리는 boost 옵션과 함께 다음 compound 연산자 절을 사용하여 일부 필드의 우선 순위를 다른 필드보다 더 높습니다.

    • must 절로 가장 우선시하는 장르 comedy텍스트 연산자와 함께 지정한 다음 title 필드에 snow라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다. boost 옵션은 필드에 가중치를 적용합니다.

    • should 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

    참고

    boost 옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundBoostMultipleExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // define and run pipeline
    23 var results = moviesCollection.Aggregate()
    24 .Search(Builders<MovieDocument>.Search.Compound()
    25 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "comedy", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(9)))
    26 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(5)))
    27 .Should(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015), score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(3))),
    28 indexName: "compound-query-custom-score-tutorial")
    29 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    30 .Include(movie => movie.Genres)
    31 .Include(movie => movie.Title)
    32 .Include(movie => movie.Year)
    33 .Exclude(movie => movie.Id)
    34 .MetaSearchScore(movie => movie.Score))
    35 .Limit(10)
    36 .ToList();
    37
    38 // print results
    39 foreach (var movie in results)
    40 {
    41 Console.WriteLine(movie.ToJson());
    42 }
    43 }
    44}
    45
    46[BsonIgnoreExtraElements]
    47public class MovieDocument
    48{
    49 [BsonIgnoreIfDefault]
    50 public ObjectId Id { get; set; }
    51 public string [] Genres { get; set; }
    52 public string Title { get; set; }
    53 public int Year { get; set; }
    54 public double Score { get; set; }
    55}
  4. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  5. Program.cs 파일을 컴파일하고 실행합니다.

    dotnet run compound-boost-example.csproj
    {
    "title" : "Snow in Paradise",
    "year" : 2014,
    "highlights" : [{
    "path" : "title",
    "score" : 1.3828467130661011,
    "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " in Paradise" }]
    }],
    "score" : 6.7722930908203125
    }
    {
    "title" : "Snow on the Blades",
    "year" : 2014,
    "highlights" : [{
    "path" : "title",
    "score" : 1.3766303062438965,
    "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " on the Blades" }]
    }],
    "score" : 6.0634455680847168
    }
    {
    "title" : "The Snow White Murder Case",
    "year" : 2014,
    "highlights" : [{
    "path" : "title",
    "score" : 1.3525336980819702,
    "texts" : [{ "type" : "Text", "value" : "The " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " White Murder Case" }]
    }],
    "score" : 5.5096521377563477
    }
    {
    "title" : "Dead Snow 2: Red vs. Dead",
    "year" : 2014,
    "highlights" : [{
    "path" : "title",
    "score" : 1.3924485445022583,
    "texts" : [{ "type" : "Text", "value" : "Dead " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " 2: Red vs. " }]
    }],
    "score" : 5.0650539398193359
    }
    { "title" : "The Secret Life of Walter Mitty", "year" : 2013, "highlights" : [], "score" : 1.0 }
    { "title" : "Jurassic World", "year" : 2015, "highlights" : [], "score" : 1.0 }
    { "title" : "Action Jackson", "year" : 2014, "highlights" : [], "score" : 1.0 }
    { "title" : "In Secret", "year" : 2013, "highlights" : [], "score" : 1.0 }
    { "title" : "The Stanford Prison Experiment", "year" : 2015, "highlights" : [], "score" : 1.0 }
    { "title" : "The Giver", "year" : 2014, "highlights" : [], "score" : 1.0 }

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 boost 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.boost

    dotnet run compound-boost-example.csproj
    { "genres" : ["Comedy", "Horror"], "title" : "Dead Snow", "year" : 2009, "score" : 21.872983932495117 }
    { "genres" : ["Adventure", "Comedy", "Family"], "title" : "Snow Day", "year" : 2000, "score" : 21.043487548828125 }
    { "genres" : ["Adventure", "Comedy", "Family"], "title" : "Snow Dogs", "year" : 2002, "score" : 21.043487548828125 }
    { "genres" : ["Comedy", "Romance"], "title" : "Let It Snow", "year" : 1999, "score" : 19.523927688598633 }
    { "genres" : ["Action", "Comedy", "Horror"], "title" : "Dead Snow 2: Red vs. Dead", "year" : 2014, "score" : 17.426334381103516 }
    { "genres" : ["Comedy", "Drama"], "title" : "Snow White and Russian Red", "year" : 2009, "score" : 16.367326736450195 }
    { "genres" : ["Comedy", "Drama", "Romance"], "title" : "The Tiger and the Snow", "year" : 2005, "score" : 15.537829399108887 }
    { "genres" : ["Adventure", "Comedy", "Family"], "title" : "Snow White and the Three Stooges", "year" : 1961, "score" : 14.426333427429199 }
3
  1. compound-function-example라는 새 디렉토리를 만들고 dotnet new 명령으로 프로젝트를 초기화합니다.

    mkdir compound-function-example
    cd compound-function-example
    dotnet new console
  2. .NET/C# 드라이버를 프로젝트에 종속성으로 추가합니다.

    dotnet add package MongoDB.Driver
  3. Program.cs 파일의 내용을 다음 코드로 바꿉니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 파이프라인 단계를 사용하여 컬렉션을 쿼리합니다.

      • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절은 text 연산자를 사용하여 title 필드에서 snow라는 텀을 쿼리하고 function 옵션을 사용하여 score를 변경합니다. function 옵션은 산술 표현식을 사용하여 다음을 추가합니다.

        • 검색어에 대한 쿼리의 관련성 점수입니다.

        • imdb.rating 필드가 없는 문서의 경우 imdb.rating이라는 숫자 필드의 값이나 숫자 2 를 사용합니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class CompoundFunctionExample
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 var scoreFunction = Builders<MovieDocument>.SearchScore.Function(Builders<MovieDocument>.SearchScoreFunction.Add(Builders<MovieDocument>.SearchScoreFunction.Path(movie => movie.Imdb.Rating, 2), Builders<MovieDocument>.SearchScoreFunction.Relevance()));
    23 // define and run pipeline
    24 var results = moviesCollection.Aggregate()
    25 .Search(Builders<MovieDocument>.Search.Compound()
    26 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015)))
    27 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: scoreFunction)),
    28 new SearchHighlightOptions<MovieDocument>(movie => movie.Title),
    29 indexName: "compound-query-custom-score-tutorial")
    30 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    31 .Include(movie => movie.Genres)
    32 .Include(movie => movie.Title)
    33 .Include(movie => movie.Year)
    34 .Exclude(movie => movie.Id)
    35 .MetaSearchScore(movie => movie.Score)
    36 .MetaSearchHighlights("highlights"))
    37 .Limit(10)
    38 .ToList();
    39
    40 // print results
    41 foreach (var movie in results)
    42 {
    43 Console.WriteLine(movie.ToJson());
    44 }
    45 }
    46}
    47
    48[BsonIgnoreExtraElements]
    49public class MovieDocument
    50{
    51 [BsonIgnoreIfDefault]
    52 public ObjectId Id { get; set; }
    53 public string [] Genres { get; set; }
    54 public IMDB Imdb { get; set; }
    55 public string Title { get; set; }
    56 public int Year { get; set; }
    57 [BsonElement("highlights")]
    58 public List<SearchHighlight> Highlights { get; set; }
    59 public double Score { get; set; }
    60}
    61
    62[BsonIgnoreExtraElements]
    63public class IMDB
    64{
    65 public double Rating { get; set; }
    66}
  4. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  5. Program.cs 파일을 컴파일하고 실행합니다.

    dotnet run compound-function-example.csproj
    { "genres" : ["Drama", "Mystery"], "title" : "The Snow White Murder Case", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3525336980819702, "texts" : [{ "type" : "Text", "value" : "The " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " White Murder Case" }] }], "score" : 10.454826354980469 }
    { "genres" : ["Action", "Drama", "History"], "title" : "Snow on the Blades", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3766303062438965, "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " on the Blades" }] }], "score" : 10.331723213195801 }
    { "genres" : ["Action", "Comedy", "Horror"], "title" : "Dead Snow 2: Red vs. Dead", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3924485445022583, "texts" : [{ "type" : "Text", "value" : "Dead " }, { "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " 2: Red vs. " }] }], "score" : 10.032526969909668 }
    { "genres" : ["Thriller"], "title" : "Snow in Paradise", "year" : 2014, "highlights" : [{ "path" : "title", "score" : 1.3828467130661011, "texts" : [{ "type" : "Hit", "value" : "Snow" }, { "type" : "Text", "value" : " in Paradise" }] }], "score" : 8.3861465454101562 }
    { "genres" : ["Adventure", "Comedy", "Drama"], "title" : "The Secret Life of Walter Mitty", "year" : 2013, "highlights" : [], "score" : 1.0 }
    { "genres" : ["Action", "Adventure", "Sci-Fi"], "title" : "Jurassic World", "year" : 2015, "highlights" : [], "score" : 1.0 }
    { "genres" : ["Action", "Comedy", "Drama"], "title" : "Action Jackson", "year" : 2014, "highlights" : [], "score" : 1.0 }
    { "genres" : ["Crime", "Drama", "Thriller"], "title" : "In Secret", "year" : 2013, "highlights" : [], "score" : 1.0 }
    { "genres" : ["Drama", "Thriller"], "title" : "The Stanford Prison Experiment", "year" : 2015, "highlights" : [], "score" : 1.0 }
    { "genres" : ["Drama", "Sci-Fi"], "title" : "The Giver", "year" : 2014, "highlights" : [], "score" : 1.0 }

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 function 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.function

1
  1. compound-constant-query.go이라는 파일을 만듭니다.

  2. 코드 예시를 복사하여 compound-constant-query.go 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 복합 절을 사용하여 컬렉션을 쿼리합니다.

      • filter 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 constant 옵션으로 score를 변경합니다. constant 옵션은 검색어에 대한 모든 점수 결과를 5로 바꿉니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13func main() {
    14 // connect to your Atlas cluster
    15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
    16 if err != nil {
    17 panic(err)
    18 }
    19 defer client.Disconnect(context.TODO())
    20
    21 // set namespace
    22 collection := client.Database("sample_mflix").Collection("movies")
    23
    24 // define pipeline stages
    25 searchStage := bson.D{{"$search", bson.M{
    26 "index": "compound-query-custom-score-tutorial",
    27 "compound": bson.M{
    28 "filter": bson.M{
    29 "range": bson.M{
    30 "path": "year", "gte": 2013, "lte": 2015,
    31 },
    32 },
    33 "should": bson.D{
    34 {"text", bson.M{
    35 "path": "title", "query": "snow", "score": bson.M{
    36 "constant": bson.D{{"value", 5}},
    37 }}}},
    38 },
    39 "highlight": bson.D{{"path", "title"}},
    40 }}}
    41 limitStage := bson.D{{"$limit", 10}}
    42 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}}
    43
    44 // specify the amount of time the operation can run on the server
    45 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    46
    47 // run pipeline
    48 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    49 if err != nil {
    50 panic(err)
    51 }
    52
    53 // print results
    54 var results []bson.D
    55 if err = cursor.All(context.TODO(), &results); err != nil {
    56 panic(err)
    57 }
    58 for _, result := range results {
    59 fmt.Println(result)
    60 }
    61}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 constant 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.constant

2
  1. compound-boost-query.go이라는 파일을 만듭니다.

  2. 코드 예시를 복사하여 compound-boost-query.go 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다.

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    쿼리는 다음 파이프라인 단계를 사용합니다:

    • $search 단계를 통해 collection을 쿼리할 수 있습니다. 쿼리:

      • 다음 compound 절을 사용하여 컬렉션을 쿼리합니다.

        • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

        • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 boost 옵션으로 score를 변경합니다. boost 옵션은 검색어에 대한 결과의 기본 점수에 2를 곱합니다.

      • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

    • $project 단계에서 다음을 수행합니다:

      • titleyear을 제외한 모든 필드를 제외합니다.

      • scorehighlights 이라는 두 필드를 추가합니다.

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

    이 쿼리는 다음 파이프라인 단계를 사용합니다:

    • $search 단계를 통해 collection을 쿼리할 수 있습니다. 쿼리:

      • 일부 필드를 다른 필드보다 우선시하기 위해 boost 옵션과 함께 compound 연산자 절을 사용합니다.

        • must 절로 가장 우선시하는 장르 comedy텍스트 연산자와 함께 지정한 다음 title 필드에 snow라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다. boost 옵션은 필드에 가중치를 적용합니다.

        • should 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

        참고

        boost 옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.

    • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

    • $project 단계에서 다음을 수행합니다:

      • titleyear을 제외한 모든 필드를 제외합니다.

      • scorehighlights 이라는 두 필드를 추가합니다.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13// define structure of movies collection
    14type MovieCollection struct {
    15 title string `bson:"Title,omitempty"`
    16}
    17
    18func main() {
    19 var err error
    20 // connect to the Atlas cluster
    21 ctx := context.Background()
    22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    23 if err != nil {
    24 panic(err)
    25 }
    26 defer client.Disconnect(ctx)
    27 // set namespace
    28 collection := client.Database("sample_mflix").Collection("movies")
    29 // define pipeline
    30 searchStage := bson.D{{"$search", bson.M{
    31 "index": "compound-query-custom-score-tutorial",
    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}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 boost 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.boost

    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
    }
    ]
3
  1. compound-boost-query.go이라는 파일을 만듭니다.

  2. 코드 예시를 복사하여 compound-function-query.go 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 compound 연산자 절을 사용합니다:

      • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절은 text 연산자를 사용하여 title 필드에서 snow라는 텀을 쿼리하고 function 옵션을 사용하여 score를 변경합니다. function 옵션은 산술 표현식을 사용하여 다음을 추가합니다.

        • 검색어에 대한 쿼리의 관련성 점수입니다.

        • imdb.rating 필드가 없는 문서의 경우 imdb.rating이라는 숫자 필드의 값이나 숫자 2 를 사용합니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/bson"
    9 "go.mongodb.org/mongo-driver/mongo"
    10 "go.mongodb.org/mongo-driver/mongo/options"
    11)
    12
    13func main() {
    14 // connect to your Atlas cluster
    15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
    16 if err != nil {
    17 panic(err)
    18 }
    19 defer client.Disconnect(context.TODO())
    20
    21 // set namespace
    22 collection := client.Database("sample_mflix").Collection("movies")
    23
    24 // define pipeline
    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}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 function 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.function

1

junit

4.11 또는 그 이상의 버전

mongodb-driver-sync

4.3.0 또는 그 이상의 버전

slf4j-log4j12

1.7.30 또는 그 이상의 버전

2
  1. CompoundConstantQuery.java이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 복합 절을 사용하여 컬렉션을 쿼리합니다.

      • filter 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 constant 옵션으로 score를 변경합니다. constant 옵션은 검색어에 대한 모든 점수 결과를 5로 바꿉니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    1import java.util.Arrays;
    2import java.util.List;
    3
    4import static com.mongodb.client.model.Aggregates.limit;
    5import static com.mongodb.client.model.Aggregates.project;
    6import static com.mongodb.client.model.Projections.*;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11
    12import org.bson.Document;
    13
    14public 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}

    참고

    Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음을 추가하세요.

    package com.mongodb.drivers;
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. CompoundConstantQuery.java 파일을 컴파일하고 실행합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 constant 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.constant

3
  1. CompoundBoostQuery.java이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    쿼리는 다음 파이프라인 단계를 사용합니다:

    • $search 단계를 통해 collection을 쿼리할 수 있습니다. 쿼리:

      • 다음 compound 연산자 절을 사용합니다:

        • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

        • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 boost 옵션으로 score를 변경합니다. boost 옵션은 검색어에 대한 결과의 기본 점수에 2를 곱합니다.

      title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

    • $project 단계에서 다음을 수행합니다:

      • titleyear을 제외한 모든 필드를 제외합니다.

      • scorehighlights 이라는 두 필드를 추가합니다.

    1import java.util.Arrays;
    2import java.util.List;
    3
    4import static com.mongodb.client.model.Aggregates.limit;
    5import static com.mongodb.client.model.Aggregates.project;
    6import static com.mongodb.client.model.Projections.*;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11import org.bson.Document;
    12
    13public 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}

    이 쿼리는 boost 옵션과 함께 다음 compound 연산자 절을 사용하여 일부 필드의 우선 순위를 다른 필드보다 더 높습니다.

    • must 절로 가장 우선시하는 장르 comedy텍스트 연산자와 함께 지정한 다음 title 필드에 snow라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다. boost 옵션은 필드에 가중치를 적용합니다.

    • should 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

    참고

    boost 옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.

    1import java.util.Arrays;
    2import static com.mongodb.client.model.Filters.eq;
    3import static com.mongodb.client.model.Aggregates.limit;
    4import static com.mongodb.client.model.Aggregates.project;
    5import static com.mongodb.client.model.Projections.computed;
    6import static com.mongodb.client.model.Projections.excludeId;
    7import static com.mongodb.client.model.Projections.fields;
    8import static com.mongodb.client.model.Projections.include;
    9import com.mongodb.client.MongoClient;
    10import com.mongodb.client.MongoClients;
    11import com.mongodb.client.MongoCollection;
    12import com.mongodb.client.MongoDatabase;
    13import org.bson.Document;
    14
    15public 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}

    참고

    Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음을 추가하세요.

    package com.mongodb.drivers;
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. CompoundBoostQuery.java 파일을 컴파일하고 실행합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 boost 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.boost

    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
    }
4
  1. CompoundFunctionQuery.java이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 파이프라인 단계를 사용하여 컬렉션을 쿼리합니다.

      • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절은 text 연산자를 사용하여 title 필드에서 snow라는 텀을 쿼리하고 function 옵션을 사용하여 score를 변경합니다. function 옵션은 산술 표현식을 사용하여 다음을 추가합니다.

        • 검색어에 대한 쿼리의 관련성 점수입니다.

        • imdb.rating 필드가 없는 문서의 경우 imdb.rating이라는 숫자 필드의 값이나 숫자 2 를 사용합니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    1import java.util.Arrays;
    2import java.util.List;
    3
    4import static com.mongodb.client.model.Aggregates.limit;
    5import static com.mongodb.client.model.Aggregates.project;
    6import static com.mongodb.client.model.Projections.*;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11import org.bson.Document;
    12
    13public 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}

    참고

    Maven 환경에서 샘플 코드를 실행하려면 파일의 가져오기 문 위에 다음을 추가하세요.

    package com.mongodb.drivers;
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. CompoundFunctionQuery.java 파일을 컴파일하고 실행합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 function 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.function

1

mongodb-driver-kotlin-coroutine

4.10.0 또는 그 이상의 버전

2
  1. CompoundConstantQuery.kt이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 복합 절을 사용하여 컬렉션을 쿼리합니다.

      • filter 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 constant 옵션으로 score를 변경합니다. constant 옵션은 검색어에 대한 모든 점수 결과를 5로 바꿉니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • AggregateFlow 인스턴스에서 쿼리와 일치하는 문서를 인쇄합니다.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun 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}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. CompoundConstantQuery.kt 파일을 실행합니다.

    IDE에서 CompoundConstantQuery.kt 프로그램을 실행하면 다음 문서가 인쇄됩니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 constant 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.constant

3
  1. CompoundBoostQuery.kt이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • AggregateFlow 인스턴스에서 쿼리와 일치하는 문서를 인쇄합니다.

    쿼리는 다음 파이프라인 단계를 사용합니다:

    • $search 단계를 통해 collection을 쿼리할 수 있습니다. 쿼리:

      • 다음 compound 연산자 절을 사용합니다:

        • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

        • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 boost 옵션으로 score를 변경합니다. boost 옵션은 검색어에 대한 결과의 기본 점수에 2를 곱합니다.

      title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

    • $project 단계에서 다음을 수행합니다:

      • titleyear을 제외한 모든 필드를 제외합니다.

      • scorehighlights 이라는 두 필드를 추가합니다.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun 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}

    이 쿼리는 boost 옵션과 함께 다음 compound 연산자 절을 사용하여 일부 필드의 우선 순위를 다른 필드보다 더 높습니다.

    • must 절로 가장 우선시하는 장르 comedy텍스트 연산자와 함께 지정한 다음 title 필드에 snow라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다. boost 옵션은 필드에 가중치를 적용합니다.

    • should 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

    참고

    boost 옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun 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}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. CompoundBoostQuery.kt 파일을 실행합니다.

    IDE에서 CompoundBoostQuery.kt 프로그램을 실행하면 다음 문서가 인쇄됩니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 boost 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.boost

    IDE에서 CompoundBoostQuery.kt 프로그램을 실행하면 다음 문서가 인쇄됩니다.

    Document{{year=2000, genres=[Adventure, Comedy, Family], title=Snow Day, score=20.998544692993164}}
    Document{{genres=[Adventure, Comedy, Family], title=Snow Dogs, year=2002, score=20.998544692993164}}
    Document{{year=1999, genres=[Comedy, Romance], title=Let It Snow, score=19.45327377319336}}
    Document{{genres=[Action, Comedy, Horror], title=Dead Snow 2: Red vs. Dead, year=2014, score=17.361087799072266}}
    Document{{genres=[Comedy, Drama], title=Snow White and Russian Red, year=2009, score=16.287294387817383}}
    Document{{genres=[Comedy, Drama, Romance], title=The Tiger and the Snow, year=2005, score=15.475509643554688}}
    Document{{genres=[Adventure, Comedy, Family], title=Snow White and the Three Stooges, year=1961, score=14.361087799072266}}
4
  1. CompoundFunctionQuery.kt이라는 파일을 만듭니다.

  2. 다음 코드를 복사하여 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • mongodb 패키지 및 종속성을 가져옵니다.

    • Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 파이프라인 단계를 사용하여 컬렉션을 쿼리합니다.

      • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절은 text 연산자를 사용하여 title 필드에서 snow라는 텀을 쿼리하고 function 옵션을 사용하여 score를 변경합니다. function 옵션은 산술 표현식을 사용하여 다음을 추가합니다.

        • 검색어에 대한 쿼리의 관련성 점수입니다.

        • imdb.rating 필드가 없는 문서의 경우 imdb.rating이라는 숫자 필드의 값이나 숫자 2 를 사용합니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • AggregateFlow 인스턴스에서 쿼리와 일치하는 문서를 인쇄합니다.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Projections.*
    4import com.mongodb.kotlin.client.coroutine.MongoClient
    5import kotlinx.coroutines.runBlocking
    6import org.bson.Document
    7
    8fun 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}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. CompoundFunctionQuery.kt 파일을 실행합니다.

    IDE에서 CompoundFunctionQuery.kt 프로그램을 실행하면 다음 문서가 인쇄됩니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 function 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.function

1
  1. compound-constant-query.js이라는 파일을 만듭니다.

  2. 코드 예시를 복사하여 compound-constant-query.js 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • MongoDB의 Node.js 드라이버인 mongodb를 가져옵니다.

    • MongoClient 클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 복합 절을 사용하여 컬렉션을 쿼리합니다.

      • filter 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 constant 옵션으로 score를 변경합니다. constant 옵션은 검색어에 대한 모든 점수 결과를 5로 바꿉니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const 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
    53MongoClient.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);
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 constant 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.constant

2
  1. compound-boost-query.js이라는 파일을 만듭니다.

  2. 코드 예시를 복사하여 compound-boost-query.js 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • MongoDB의 Node.js 드라이버인 mongodb를 가져옵니다.

    • MongoClient 클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    쿼리는 다음 파이프라인 단계를 사용합니다:

    • $search 단계를 통해 collection을 쿼리할 수 있습니다. 쿼리:

      • 다음 compound 연산자 절을 사용합니다:

        • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

        • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 boost 옵션으로 score를 변경합니다. boost 옵션은 검색어에 대한 결과의 기본 점수에 2를 곱합니다.

      • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

    • $project 단계에서 다음을 수행합니다:

      • titleyear을 제외한 모든 필드를 제외합니다.

      • scorehighlights 이라는 두 필드를 추가합니다.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const 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
    47MongoClient.connect(
    48 "<connection-string>",
    49 { useNewUrlParser: true, useUnifiedTopology: true },
    50 async function (connectErr, client) {
    51 assert.equal(null, connectErr);
    52 const coll = client.db("sample_mflix").collection("movies");
    53 let cursor = await coll.aggregate(agg);
    54 await cursor.forEach((doc) => console.log(doc));
    55 client.close();
    56 }
    57);

    쿼리는 다음 파이프라인 단계를 사용합니다:

    • $search 단계를 통해 collection을 쿼리할 수 있습니다. 쿼리:

      • 다음 compound 연산자 절을 boost 옵션과 함께 사용하여 일부 필드의 우선 순위를 다른 필드보다 높게 지정합니다.

        • must 절로 가장 우선시하는 장르 comedy텍스트 연산자와 함께 지정한 다음 title 필드에 snow라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다. boost 옵션은 필드에 가중치를 적용합니다.

        • should 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

        참고

        boost 옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const 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
    63MongoClient.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);
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 boost 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.boost

    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
    }
3
  1. compound-function-query.js이라는 파일을 만듭니다.

  2. 코드 예시를 복사하여 compound-function-query.js 파일에 붙여넣습니다.

    이 코드 예시에서는 다음 작업을 수행합니다:

    • MongoDB의 Node.js 드라이버인 mongodb를 가져옵니다.

    • MongoClient 클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 복합 절을 사용하여 컬렉션을 쿼리합니다.

      • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절은 text 연산자를 사용하여 title 필드에서 snow라는 텀을 쿼리하고 function 옵션을 사용하여 score를 변경합니다. function 옵션은 산술 표현식을 사용하여 다음을 추가합니다.

        • 검색어에 대한 쿼리의 관련성 점수입니다.

        • imdb.rating 필드가 없는 문서의 경우 imdb.rating이라는 숫자 필드의 값이나 숫자 2 를 사용합니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const 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
    59MongoClient.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);
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

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

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 function 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.function

1
  1. compound-constant-query.py이라는 파일을 만듭니다.

  2. 코드 예시를 복사하여 compound-constant.py 파일에 붙여넣습니다.

    다음 코드 예제에서는:

    • pymongo, MongoDB의 Python 드라이버 및 dns 모듈을 가져옵니다. 이 모듈은 DNS 시드 리스트 연결 문자열을 사용하여 pymongoAtlas에 연결하는 데 필요합니다.

    • MongoClient 클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 복합 절을 사용하여 컬렉션을 쿼리합니다.

      • filter 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 constant 옵션으로 score를 변경합니다. constant 옵션은 검색어에 대한 모든 점수 결과를 5로 바꿉니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    1import pymongo
    2
    3# connect to your Atlas cluster
    4client = pymongo.MongoClient('<connection-string>')
    5
    6# define pipeline
    7pipeline = [
    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
    20result = client['sample_mflix']['movies'].aggregate(pipeline)
    21
    22# print results
    23for i in result:
    24 print(i)
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

    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}

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 constant 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.constant

2
  1. compound-boost-query.py이라는 파일을 만듭니다.

  2. 코드 예시를 복사하여 compound-boost-query.py 파일에 붙여넣습니다.

    다음 코드 예제에서는:

    • pymongo, MongoDB의 Python 드라이버 및 dns 모듈을 가져옵니다. 이 모듈은 DNS 시드 리스트 연결 문자열을 사용하여 pymongoAtlas에 연결하는 데 필요합니다.

    • MongoClient 클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    쿼리는 다음 파이프라인 단계를 사용합니다:

    • $search 단계를 통해 collection을 쿼리할 수 있습니다. 쿼리:

      • 다음 compound 연산자 절을 사용합니다:

        • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

        • should 절에 텍스트 연산자를 사용하여 title 필드에서 snow 용어를 쿼리하고 boost 옵션으로 score를 변경합니다. boost 옵션은 검색어에 대한 결과의 기본 점수에 2를 곱합니다.

        • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

    • $project 단계에서 다음을 수행합니다:

      • titleyear을 제외한 모든 필드를 제외합니다.

      • scorehighlights 이라는 두 필드를 추가합니다.

    1import pymongo
    2
    3# connect to your Atlas cluster
    4client = pymongo.MongoClient('<connection-string>')
    5
    6# define pipeline
    7pipeline = [
    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
    19result = client['sample_mflix']['movies'].aggregate(pipeline)
    20
    21# print results
    22for i in result:
    23 print(i)

    쿼리는 다음 파이프라인 단계를 사용합니다:

    • 컬렉션을 쿼리하기 위한 $search 단계입니다. 쿼리는 다음 compound 연산자 절을 boost 옵션과 함께 사용하여 일부 필드를 다른 필드보다 더 높은 우선순위로 지정합니다.

      • must 절로 가장 우선시하는 장르 comedy텍스트 연산자와 함께 지정한 다음 title 필드에 snow라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다. boost 옵션은 필드에 가중치를 적용합니다.

      • should 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      참고

      boost 옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.

    • $limit 단계는 출력을 10 결과로만 제한합니다.

    • $project 단계로 이동합니다:

      • title, year, genres 이외의 모든 필드 제외

      • 다음과 같은 이름의 필드를 추가합니다. 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)
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

    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}

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 boost 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.boost

    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
    }
3
  1. compound-function-query.py이라는 파일을 만듭니다.

  2. 코드 예시를 복사하여 compound-function-query.py 파일에 붙여넣습니다.

    다음 코드 예제에서는:

    • pymongo, MongoDB의 Python 드라이버 및 dns 모듈을 가져옵니다. 이 모듈은 DNS 시드 리스트 연결 문자열을 사용하여 pymongoAtlas에 연결하는 데 필요합니다.

    • MongoClient 클래스의 인스턴스를 만들어 Atlas 클러스터에 대한 연결을 설정합니다.

    • 다음 복합 절을 사용하여 컬렉션을 쿼리합니다.

      • must 2013~2015년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.

      • should 절은 text 연산자를 사용하여 title 필드에서 snow라는 텀을 쿼리하고 function 옵션을 사용하여 score를 변경합니다. function 옵션은 산술 표현식을 사용하여 다음을 추가합니다.

        • 검색어에 대한 쿼리의 관련성 점수입니다.

        • imdb.rating 필드가 없는 문서의 경우 imdb.rating이라는 숫자 필드의 값이나 숫자 2 를 사용합니다.

    • title 필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는 type: 'hit'으로 지정된 일치하는 텍스트와 type: 'text'로 지정된 인접 텍스트가 포함되어 있습니다.

    • 다음 파이프라인 단계를 사용합니다:

      • $limit 단계를 사용하여 출력 결과를 10개로 제한합니다.

      • $project 단계에서 다음을 수행합니다:

        • titleyear을 제외한 모든 필드를 제외합니다.

        • scorehighlights 이라는 두 필드를 추가합니다.

    • 커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.

    1import pymongo
    2
    3# connect to your Atlas cluster
    4client = pymongo.MongoClient('<connection-string>')
    5
    6# define pipeline
    7pipeline = [
    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
    21result = client['sample_mflix']['movies'].aggregate(pipeline)
    22
    23# print results
    24for i in result:
    25 print(i)
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

  4. 다음 명령을 실행하여 컬렉션을 쿼리합니다.

    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}

    쿼리의 should 절이 제목에 snow 이 포함된 문서에 대한 기본 설정을 지정하기 때문에 결과에서 처음 4개의 문서가 더 높은 점수를 받습니다. should 절은 function 옵션을 사용하여 쿼리 용어 snow 의 점수도 변경합니다.function

이 섹션에서는 Atlas cluster에 연결하고 sample_mflix 데이터베이스의 movies 컬렉션에 있는 title, plotgenres 필드에 대해 샘플 쿼리를 실행 합니다. 샘플 쿼리는 중첩된 복합 연산자 절을 사용하여 다음 검색을 수행합니다.

  • 'ghost'라는 단어가 포함된 모든 영화를 검색하되 코미디 영화의 점수를 50% 낮춥니다.

  • "ghost"라는 단어가 포함된 모든 영화를 검색하되 지정된 ObjectIds가 있는 영화의 점수를 50% 줄입니다.

1
  1. cluster 이름을 클릭하면 cluster 세부 정보를 볼 수 있습니다.

  2. Atlas Search 탭을 클릭합니다.

  3. 쿼리할 인덱스 오른쪽에 있는 Query 버튼을 클릭합니다.

2

JSON 형식의 기본 쿼리 구문 샘플을 보려면 Edit Query을(를) 클릭합니다.

3
  1. 다음 쿼리를 복사하여 Query Editor에 붙여넣습니다.

    쿼리는 $search compound 연산자 should 절을 사용하여 다음 작업을 수행하는 compound 연산자 쿼리를 중첩합니다.

    • 줄거리 또는 제목(must 절)에 ghost 라는 용어가 포함되고 comedy 장르(mustNot 절)에 속하지 않는 영화를 검색합니다.

    • 줄거리나 제목에 ghost 텀이 포함된 영화를 검색하지만(must 절) 제목이나 줄거리에 ghost 텀이 있는 comedy 장르의 영화에 대해 점수를 50%(0.5) 낮춥니다(boost).

    1[
    2 {
    3 "$search": {
    4 "index": "compound-query-custom-score-tutorial",
    5 "compound": {
    6 "should":[ {
    7 "compound":{
    8 "must":[
    9 {
    10 "text": {
    11 "query": "ghost",
    12 "path": ["plot","title"]
    13 }
    14 }
    15 ],
    16 "mustNot":[
    17 {
    18 "text": {
    19 "query": "Comedy",
    20 "path": ["genres"]
    21 }
    22 }
    23 ]
    24 }
    25 },
    26 {
    27 "compound":{
    28 "must":[
    29 {
    30 "text": {
    31 "query": "ghost",
    32 "path": ["plot","title"]
    33 }
    34 }
    35 ],
    36 "filter":[
    37 {
    38 "text": {
    39 "query": "Comedy",
    40 "path": ["genres"]
    41 }
    42 }
    43 ],
    44 "score":{ "boost": { "value": 0.5} }
    45 }
    46 }
    47 ]
    48 }
    49 }
    50 }
    51]

    쿼리는 $search compound 연산자 should 절을 사용하여 다음 작업을 수행하는 compound 연산자 쿼리를 중첩합니다.

    • 줄거리 또는 제목에 ghost라는 텀(must 절)이 포함되어 있지만 지정된 ObjectIds(mustNot 절)가 없는 영화를 검색합니다.

    • 줄거리 또는 제목에 ghost 용어가 포함된 영화를 검색하지만(must 절), 지정된 ObjectIds(filter 절)가 있는 영화에 대해 점수를 50%(0.5) 낮춥니다(boost).

    1[
    2 {
    3 "$search": {
    4 "index": "compound-query-custom-score-tutorial",
    5 "compound": {
    6 "should":[
    7 {
    8 "compound":{
    9 "must":[
    10 {
    11 "text": {
    12 "query": "ghost",
    13 "path": ["plot","title"]
    14 }
    15 }
    16 ],
    17 "mustNot":[
    18 {
    19 "in": {
    20 "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')],
    21 "path": "_id"
    22 }
    23 }
    24 ]
    25 }
    26 },
    27 {
    28 "compound":{
    29 "must":[
    30 {
    31 "text": {
    32 "query": "ghost",
    33 "path": ["plot","title"]
    34 }
    35 }
    36 ],
    37 "filter":[
    38 {
    39 "in": {
    40 "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')],
    41 "path": "_id"
    42 }
    43 }
    44 ],
    45 "score":{ "boost": { "value": 0.5} }
    46 }
    47 }
    48 ]
    49 }
    50 }
    51 }
    52]
  2. Query Editor에서 Search 버튼을 클릭합니다.

    1SCORE: 5.909613132476807
    2_id: “573a139af29313caabcefcce”
    3plot: "Adaption of the famous Oscar Wilde tale about a young American girl th…"
    4genres: Array (3)
    5runtime: 92
    6
    7SCORE: 5.367666244506836
    8_id: “573a13d8f29313caabda5dc1”
    9plot: "The Little Ghost lives in the castle over looking a small town and awa…"
    10genres: Array (2)
    11runtime: 92
    12
    13SCORE: 4.676314353942871
    14_id: “573a13c0f29313caabd6139d”
    15plot: "Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal …"
    16genres: Array (2)
    17runtime: 107
    18
    19SCORE: 3.9638845920562744
    20_id: “573a1398f29313caabcebf6f”
    21plot: "After an accident leaves a young man dead, his spirit stays behind to …"
    22genres: Array (3)
    23runtime: 127
    24
    25SCORE: 3.9638845920562744
    26_id: “573a13cdf29313caabd83c08”
    27plot: "A man tries to solve his lover's murder by communicating with her spir…"
    28genres: Array (3)
    29runtime: 115
    30
    31SCORE: 3.9638845920562744
    32_id: “573a13cef29313caabd873a2”
    33plot: "A man tries to solve his lover's murder by communicating with her spir…"
    34genres: Array (3)
    35runtime: 115
    36
    37SCORE: 3.526711940765381
    38_id: “573a13c3f29313caabd6a149”
    39plot: "What kind of scenes in a horror film scares you the most? When a ghost…"
    40genres: Array (2)
    41runtime: 95
    42
    43SCORE: 3.3177831172943115
    44_id: “573a1397f29313caabce7ea1”
    45plot: "Four successful elderly gentlemen, members of the Chowder Society, sha…"
    46genres: Array (3)
    47runtime: 110
    48
    49SCORE: 3.3177831172943115
    50_id: “573a13a4f29313caabd117df”
    51fullplot: "When the motorcyclist Johnny Blaze finds that his father Barton Blaze …"
    52imdb: Object
    53year: 2007
    54
    55SCORE: 3.3177831172943115
    56_id: “573a13a6f29313caabd185dc”
    57fullplot: "After discovering a passenger ship missing since 1962 floating adrift …"
    58imdb: Object
    59year: 2002

    결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 용어 ghost가 포함되어 있고, Comedy 장르에 속하지 않습니다. Atlas Search는 plot 또는 title 필드에 ghost라는 용어가 있는 Comedy 장르의 문서를 반환하지 않았습니다. 이는 쿼리가 해당 문서의 점수를 50% 낮췄기 때문에 상위 10개의 문서에 포함되지 않았기 때문입니다.

    1SCORE: 5.909613132476807
    2_id: “573a139af29313caabcefcce”
    3plot: "Adaption of the famous Oscar Wilde tale about a young American girl th…"
    4genres: Array (3)
    5runtime: 92
    6
    7SCORE: 5.367666244506836
    8_id: “573a13d8f29313caabda5dc1”
    9plot: "The Little Ghost lives in the castle over looking a small town and awa…"
    10genres: Array (2)
    11runtime: 92
    12
    13SCORE: 4.676314353942871
    14_id: “573a13c0f29313caabd6139d”
    15plot: "Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal …"
    16genres: Array (2)
    17runtime: 107
    18
    19SCORE: 3.9638845920562744
    20_id: “573a1398f29313caabcebf6f”
    21plot: "After an accident leaves a young man dead, his spirit stays behind to …"
    22genres: Array (3)
    23runtime: 127
    24
    25SCORE: 3.526711940765381
    26_id: “573a13c3f29313caabd6a149”
    27plot: "What kind of scenes in a horror film scares you the most? When a ghost…"
    28genres:Array (2)
    29runtime: 95
    30
    31SCORE: 3.5241782665252686
    32_id: “573a1398f29313caabce912c”
    33plot: "Three unemployed parapsychology professors set up shop as a unique gho…"
    34genres: Array (2)
    35runtime: 105
    36
    37SCORE: 3.5241782665252686
    38_id: “573a139cf29313caabcf5a48”
    39plot: "Casper, a ghost, teams up with Wendy, a witch, against an evil warlock…"
    40genres: Array (3)
    41runtime: 90
    42
    43SCORE: 3.4605300426483154
    44_id: “573a13bdf29313caabd58274”
    45plot: "Banku, his mother, Anjali Sharma and father move in to their new house…"
    46genres: Array (3)
    47runtime: 150
    48
    49SCORE: 3.3177831172943115
    50_id: “573a1397f29313caabce7ea1”
    51plot: "Four successful elderly gentlemen, members of the Chowder Society, sha…"
    52genres: Array (3)
    53runtime: 110
    54
    55SCORE: 3.3177831172943115
    56_id: “573a1398f29313caabcebf79”
    57plot: "Elliot Hopper is a widower with three children, he is currently workin…"
    58genres: Array (3)
    59runtime: 83

    결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 텀 ghost가 포함되어 있고 _id 필드에 지정된 ObjectIds가 없습니다. Atlas Search는 지정된 ObjectIds를 가진 문서를 반환하지 않았는데 이는 title 필드에 쿼리 텀 ghost가 포함되어 있음에도 불구하고 쿼리가 이 문서들의 점수를 50% 낮췄기 때문에 이 문서들이 상위 10개 문서에 포함되지 않았기 때문입니다.

1

터미널 창에서 mongosh 를 열고 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh 를 통한 연결을 참조하세요.

2
use sample_mflix
switched to db sample_mflix
3

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목(must 절)에 ghost 라는 용어가 포함되고 comedy 장르(mustNot 절)에 속하지 않는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost 용어가 포함되어 있고(must 절)comedy 장르에 속하지만(filter 절), score를 50% 낮추는(boost) 영화를 검색합니다.

결과 수를 10 개 문서로 제한합니다.

  • 결과 문서에서 _id, title, plotgenres 필드만 포함됩니다.

  • 결과에 점수를 표시하는 score라는 필드를 추가합니다.

1db.movies.aggregate([
2 {
3 "$search": {
4 "index": "compound-query-custom-score-tutorial",
5 "compound": {
6 "should": [
7 {
8 "compound":{
9 "must": [
10 {
11 "text": {
12 "query": "ghost",
13 "path": ["plot","title"]
14 }
15 }
16 ],
17 "mustNot": [
18 {
19 "text": {
20 "query": "Comedy",
21 "path": ["genres"]
22 }
23 }
24 ]
25 }
26 },
27 {
28 "compound":{
29 "must":[
30 {
31 "text": {
32 "query": "ghost",
33 "path": ["plot","title"]
34 }
35 }
36 ],
37 "filter": [
38 {
39 "text": {
40 "query": "Comedy",
41 "path": ["genres"]
42 }
43 }
44 ],
45 "score": { "boost": { "value": 0.5} }
46 }
47 }
48 ]
49 }
50 }
51 },
52 {
53 "$limit": 10
54 },
55 {
56 "$project": {
57 "_id": 1,
58 "title": 1,
59 "plot": 1,
60 "genres": 1,
61 "score": { "$meta": "searchScore" }
62 }
63 }
64])
1[
2 {
3 _id: ObjectId('573a139af29313caabcefcce'),
4 plot: 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.',
5 genres: [ 'Family', 'Drama', 'Fantasy' ],
6 title: 'The Canterville Ghost',
7 score: 5.909613132476807
8 },
9 {
10 _id: ObjectId('573a13d8f29313caabda5dc1'),
11 plot: 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!',
12 genres: [ 'Family', 'Fantasy' ],
13 title: 'The Little Ghost',
14 score: 5.367666244506836
15 },
16 {
17 _id: ObjectId('573a13c0f29313caabd6139d'),
18 plot: 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.',
19 genres: [ 'Horror', 'Thriller' ],
20 title: 'Death of a Ghost Hunter',
21 score: 4.676314353942871
22 },
23 {
24 _id: ObjectId('573a1398f29313caabcebf6f'),
25 plot: 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.',
26 genres: [ 'Drama', 'Fantasy', 'Romance' ],
27 title: 'Ghost',
28 score: 3.9638845920562744
29 },
30 {
31 _id: ObjectId('573a13cdf29313caabd83c08'),
32 plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.",
33 genres: [ 'Drama', 'Fantasy', 'Mystery' ],
34 title: 'Ghost',
35 score: 3.9638845920562744
36 },
37 {
38 _id: ObjectId('573a13cef29313caabd873a2'),
39 plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.",
40 genres: [ 'Drama', 'Fantasy', 'Mystery' ],
41 title: 'Ghost',
42 score: 3.9638845920562744
43 },
44 {
45 _id: ObjectId('573a13c3f29313caabd6a149'),
46 plot: 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...',
47 genres: [ 'Horror', 'Thriller' ],
48 title: 'Coming Soon',
49 score: 3.526711940765381
50 },
51 {
52 _id: ObjectId('573a1397f29313caabce7ea1'),
53 plot: "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...",
54 genres: [ 'Drama', 'Horror', 'Thriller' ],
55 title: 'Ghost Story',
56 score: 3.3177831172943115
57 },
58 {
59 _id: ObjectId('573a13a4f29313caabd117df'),
60 plot: 'Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.',
61 genres: [ 'Action', 'Fantasy', 'Thriller' ],
62 title: 'Ghost Rider',
63 score: 3.3177831172943115
64 },
65 {
66 _id: ObjectId('573a13a6f29313caabd185dc'),
67 plot: 'A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...',
68 genres: [ 'Horror', 'Mystery' ],
69 title: 'Ghost Ship',
70 score: 3.3177831172943115
71 }
72]

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 용어 ghost가 포함되어 있고, Comedy 장르에 속하지 않습니다. Atlas Search는 plot 또는 title 필드에 ghost라는 용어가 있는 Comedy 장르의 문서를 반환하지 않았습니다. 이는 쿼리가 해당 문서의 점수를 50% 낮췄기 때문에 상위 10개의 문서에 포함되지 않았기 때문입니다.

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목에 ghost라는 텀(must 절)이 포함되어 있지만 지정된 ObjectIds(mustNot 절)가 없는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost라는 텀이 포함되고(must 절) 지정된 ObjectIds(filter 절)가 있는 영화를 검색하지만 score를 50% 감소시킵니다(boost).

결과 수를 10 개 문서로 제한합니다.

  • 결과에는 문서의 title, plot_id 필드만 포함됩니다.

  • 결과에서 문서의 점수를 보여주는 score라는 이름의 필드를 추가합니다.

1db.movies.aggregate([
2 {
3 "$search": {
4 "compound": {
5 "index": "compound-query-custom-score-tutorial",
6 "should": [
7 {
8 "compound": {
9 "must": [
10 {
11 "text": {
12 "query": "ghost",
13 "path": ["plot","title"]
14 }
15 }
16 ],
17 "mustNot": [
18 {
19 "in": {
20 "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')],
21 "path": "_id"
22 }
23 }
24 ]
25 }
26 },
27 {
28 "compound": {
29 "must": [
30 {
31 "text": {
32 "query": "ghost",
33 "path": ["plot","title"]
34 }
35 }
36 ],
37 "filter": [
38 {
39 "in": {
40 "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')],
41 "path": "_id"
42 }
43 }
44 ],
45 "score": { "boost": { "value": 0.5} }
46 }
47 }
48 ]
49 }
50 }
51 },
52 {
53 "$limit": 10
54 },
55 {
56 "$project": {
57 "_id": 1,
58 "title": 1,
59 "plot": 1,
60 "score": { "$meta": "searchScore" }
61 }
62 }
63])
1[
2 {
3 _id: ObjectId('573a139af29313caabcefcce'),
4 plot: 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.',
5 genres: [ 'Family', 'Drama', 'Fantasy' ],
6 title: 'The Canterville Ghost',
7 score: 5.909613132476807
8 },
9 {
10 _id: ObjectId('573a13d8f29313caabda5dc1'),
11 plot: 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!',
12 genres: [ 'Family', 'Fantasy' ],
13 title: 'The Little Ghost',
14 score: 5.367666244506836
15 },
16 {
17 _id: ObjectId('573a13c0f29313caabd6139d'),
18 plot: 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.',
19 genres: [ 'Horror', 'Thriller' ],
20 title: 'Death of a Ghost Hunter',
21 score: 4.676314353942871
22 },
23 {
24 _id: ObjectId('573a1398f29313caabcebf6f'),
25 plot: 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.',
26 genres: [ 'Drama', 'Fantasy', 'Romance' ],
27 title: 'Ghost',
28 score: 3.9638845920562744
29 },
30 {
31 _id: ObjectId('573a13c3f29313caabd6a149'),
32 plot: 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...',
33 genres: [ 'Horror', 'Thriller' ],
34 title: 'Coming Soon',
35 score: 3.526711940765381
36 },
37 {
38 _id: ObjectId('573a1398f29313caabce912c'),
39 plot: 'Three unemployed parapsychology professors set up shop as a unique ghost removal service.',
40 genres: [ 'Comedy', 'Fantasy' ],
41 title: 'Ghostbusters',
42 score: 3.5241782665252686
43 },
44 {
45 _id: ObjectId('573a139cf29313caabcf5a48'),
46 plot: 'Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.',
47 genres: [ 'Adventure', 'Comedy', 'Family' ],
48 title: 'Casper Meets Wendy',
49 score: 3.5241782665252686
50 },
51 {
52 _id: ObjectId('573a13bdf29313caabd58274'),
53 plot: 'Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...',
54 genres: [ 'Comedy', 'Drama', 'Fantasy' ],
55 title: 'Bhoothnath',
56 score: 3.4605300426483154
57 },
58 {
59 _id: ObjectId('573a1397f29313caabce7ea1'),
60 plot: "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...",
61 genres: [ 'Drama', 'Horror', 'Thriller' ],
62 title: 'Ghost Story',
63 score: 3.3177831172943115
64 },
65 {
66 _id: ObjectId('573a1398f29313caabcebf79'),
67 plot: 'Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...',
68 genres: [ 'Comedy', 'Family', 'Fantasy' ],
69 title: 'Ghost Dad',
70 score: 3.3177831172943115
71 }
72]

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 텀 ghost가 포함되어 있고 _id 필드에 지정된 ObjectIds가 없습니다. Atlas Search는 지정된 ObjectIds를 가진 문서를 반환하지 않았는데 이는 title 필드에 쿼리 텀 ghost가 포함되어 있음에도 불구하고 쿼리가 이 문서들의 점수를 50% 낮췄기 때문에 이 문서들이 상위 10개 문서에 포함되지 않았기 때문입니다.

1

MongoDB Compass를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.

2

Database 화면에서 sample_mflix 데이터베이스를 클릭한 다음 movies collection을 클릭합니다.

3

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목(must 절)에 ghost 라는 용어가 포함되고 comedy 장르(mustNot 절)에 속하지 않는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost 용어가 포함되어 있고(must 절)comedy 장르에 속하지만(filter 절), score를 50% 낮추는(boost) 영화를 검색합니다.

결과 수를 10 개 문서로 제한합니다.

  • 결과 문서에서 _id, title, plotgenres 필드만 포함됩니다.

  • 결과에 점수를 표시하는 score라는 필드를 추가합니다.

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목에 ghost라는 텀(must 절)이 포함되어 있지만 지정된 ObjectIds(mustNot 절)가 없는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost라는 텀이 포함되고(must 절) 지정된 ObjectIds(filter 절)가 있는 영화를 검색하지만 score를 50% 감소시킵니다(boost).

결과 수를 10 개 문서로 제한합니다.

  • 결과에는 문서의 title, plot_id 필드만 포함됩니다.

  • 결과에서 문서의 점수를 보여주는 score라는 이름의 필드를 추가합니다.

이 쿼리를 실행하려면 MongoDB Compass에서 다음 단계를 수행하세요.

  1. Aggregations 탭을 클릭합니다.

  2. Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다.

    Add Stage를 클릭하여 단계를 추가합니다.

    파이프라인 단계
    쿼리

    $search

    {
    "index": "compound-query-custom-score-tutorial",
    "compound": {
    "should": [
    {
    "compound":{
    "must": [
    {
    "text": {
    "query": "ghost",
    "path": ["plot","title"]
    }
    }
    ],
    "mustNot": [
    {
    "text": {
    "query": "Comedy",
    "path": ["genres"]
    }
    }
    ]
    }
    },
    {
    "compound":{
    "must":[
    {
    "text": {
    "query": "ghost",
    "path": ["plot","title"]
    }
    }
    ],
    "filter": [
    {
    "text": {
    "query": "Comedy",
    "path": ["genres"]
    }
    }
    ],
    "score": { "boost": { "value": 0.5} }
    }
    }
    ]
    }
    }

    $limit

    10

    $project

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

    Auto Preview활성화한 경우 MongoDB Compass는 $project 파이프라인 단계 옆에 다음 문서를 표시합니다.

    1_id: ObjectId('573a139af29313caabcefcce'),
    2plot: 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.',
    3genres: [ 'Family', 'Drama', 'Fantasy' ],
    4title: 'The Canterville Ghost',
    5score: 5.909613132476807
    6
    7_id: ObjectId('573a13d8f29313caabda5dc1'),
    8plot: 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!',
    9genres: [ 'Family', 'Fantasy' ],
    10title: 'The Little Ghost',
    11score: 5.367666244506836
    12
    13_id: ObjectId('573a13c0f29313caabd6139d'),
    14plot: 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.',
    15genres: [ 'Horror', 'Thriller' ],
    16title: 'Death of a Ghost Hunter',
    17score: 4.676314353942871
    18
    19_id: ObjectId('573a1398f29313caabcebf6f'),
    20plot: 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.',
    21genres: [ 'Drama', 'Fantasy', 'Romance' ],
    22title: 'Ghost',
    23score: 3.9638845920562744
    24
    25_id: ObjectId('573a13cdf29313caabd83c08'),
    26plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.",
    27genres: [ 'Drama', 'Fantasy', 'Mystery' ],
    28title: 'Ghost',
    29score: 3.9638845920562744
    30
    31_id: ObjectId('573a13cef29313caabd873a2'),
    32plot: "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.",
    33genres: [ 'Drama', 'Fantasy', 'Mystery' ],
    34title: 'Ghost',
    35score: 3.9638845920562744
    36
    37_id: ObjectId('573a13c3f29313caabd6a149'),
    38plot: 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...',
    39genres: [ 'Horror', 'Thriller' ],
    40title: 'Coming Soon',
    41score: 3.526711940765381
    42
    43_id: ObjectId('573a1397f29313caabce7ea1'),
    44plot: "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...",
    45genres: [ 'Drama', 'Horror', 'Thriller' ],
    46title: 'Ghost Story',
    47score: 3.3177831172943115
    48
    49_id: ObjectId('573a13a4f29313caabd117df'),
    50plot: 'Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.',
    51genres: [ 'Action', 'Fantasy', 'Thriller' ],
    52title: 'Ghost Rider',
    53score: 3.3177831172943115
    54
    55_id: ObjectId('573a13a6f29313caabd185dc'),
    56plot: 'A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...',
    57genres: [ 'Horror', 'Mystery' ],
    58title: 'Ghost Ship',
    59score: 3.3177831172943115

    결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 용어 ghost가 포함되어 있고, Comedy 장르에 속하지 않습니다. Atlas Search는 plot 또는 title 필드에 ghost라는 용어가 있는 Comedy 장르의 문서를 반환하지 않았습니다. 이는 쿼리가 해당 문서의 점수를 50% 낮췄기 때문에 상위 10개의 문서에 포함되지 않았기 때문입니다.

    파이프라인 단계
    쿼리

    $search

    {
    "index": "compound-query-custom-score-tutorial",
    "compound": {
    "should": [
    {
    "compound":{
    "must": [
    {
    "text": {
    "query": "ghost",
    "path": ["plot","title"]
    }
    }
    ],
    "mustNot": [
    {
    "in": {
    "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')],
    "path": "_id"
    }
    }
    ]
    }
    },
    {
    "compound":{
    "must":[
    {
    "text": {
    "query": "ghost",
    "path": ["plot","title"]
    }
    }
    ],
    "filter": [
    {
    "in": {
    "value": [ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2')],
    "path": "_id"
    }
    }
    ],
    "score": { "boost": { "value": 0.5} }
    }
    }
    ]
    }
    }

    $limit

    10

    $project

    {
    "_id": 1,
    "title": 1,
    "plot": 1,
    "score": { "$meta": "searchScore" }
    }

    Auto Preview활성화한 경우 MongoDB Compass는 $project 파이프라인 단계 옆에 다음 문서를 표시합니다.

    1_id: ObjectId('573a139af29313caabcefcce'),
    2plot: 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.',
    3title: 'The Canterville Ghost',
    4score: 5.909613132476807
    5
    6_id: ObjectId('573a13d8f29313caabda5dc1'),
    7plot: 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!',
    8title: 'The Little Ghost',
    9score: 5.367666244506836
    10
    11_id: ObjectId('573a13c0f29313caabd6139d'),
    12plot: 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.',
    13title: 'Death of a Ghost Hunter',
    14score: 4.676314353942871
    15
    16_id: ObjectId('573a1398f29313caabcebf6f'),
    17plot: 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.',
    18title: 'Ghost',
    19score: 3.9638845920562744
    20
    21_id: ObjectId('573a13c3f29313caabd6a149'),
    22plot: 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...',
    23title: 'Coming Soon',
    24score: 3.526711940765381
    25
    26_id: ObjectId('573a1398f29313caabce912c'),
    27plot: 'Three unemployed parapsychology professors set up shop as a unique ghost removal service.',
    28title: 'Ghostbusters',
    29score: 3.5241782665252686
    30
    31_id: ObjectId('573a139cf29313caabcf5a48'),
    32plot: 'Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.',
    33title: 'Casper Meets Wendy',
    34score: 3.5241782665252686
    35
    36_id: ObjectId('573a13bdf29313caabd58274'),
    37plot: 'Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...',
    38title: 'Bhoothnath',
    39score: 3.4605300426483154
    40
    41_id: ObjectId('573a1397f29313caabce7ea1'),
    42plot: "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...",
    43title: 'Ghost Story',
    44score: 3.3177831172943115
    45
    46_id: ObjectId('573a1398f29313caabcebf79'),
    47plot: 'Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...',
    48title: 'Ghost Dad',
    49score: 3.3177831172943115

    결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 텀 ghost가 포함되어 있고 _id 필드에 지정된 ObjectIds가 없습니다. Atlas Search는 지정된 ObjectIds를 가진 문서를 반환하지 않았는데 이는 title 필드에 쿼리 텀 ghost가 포함되어 있음에도 불구하고 쿼리가 이 문서들의 점수를 50% 낮췄기 때문에 이 문서들이 상위 10개 문서에 포함되지 않았기 때문입니다.

1
  1. compound-bury-results라는 새 디렉터리를 만들고 dotnet new 명령으로 프로젝트를 초기화합니다.

    mkdir compound-bury-results
    cd compound-bury-results
    dotnet new console
  2. .NET/C# 드라이버를 프로젝트에 종속성으로 추가합니다.

    dotnet add package MongoDB.Driver
2

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목(must 절)에 ghost 라는 용어가 포함되고 comedy 장르(mustNot 절)에 속하지 않는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost 용어가 포함되어 있고(must 절)comedy 장르에 속하지만(filter 절), score를 50% 낮추는(boost) 영화를 검색합니다.

결과 수를 10 개 문서로 제한합니다.

  • 결과 문서에서 _id, title, plotgenres 필드만 포함됩니다.

  • 결과에 점수를 표시하는 score라는 필드를 추가합니다.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class BuryGenreCompoundExample
8{
9 private const string MongoConnectionString = "<connection-string>";
10
11 public static void Main(string[] args)
12 {
13 // allow automapping of the camelCase database fields to our MovieDocument
14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
21
22 // define and run pipeline
23 var results = moviesCollection.Aggregate()
24 .Search(Builders<MovieDocument>.Search.Compound()
25 .Should(Builders<MovieDocument>.Search.Compound()
26 .Must(Builders<MovieDocument>.Search.Text(
27 Builders<MovieDocument>.SearchPath.Multi(movie => movie.Title, movie => movie.Plot), "ghost"))
28 .MustNot(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Comedy"))
29 )
30 .Should(Builders<MovieDocument>.Search.Compound()
31 .Must(Builders<MovieDocument>.Search.Text(
32 Builders<MovieDocument>.SearchPath.Multi(movie => movie.Title, movie => movie.Plot), "ghost"))
33 .Filter(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "Comedy", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(0.5)))
34 ),
35 indexName: "compound-query-custom-score-tutorial")
36 .Project<MovieDocument>(Builders<MovieDocument>.Projection
37 .Include(movie => movie.Plot)
38 .Include(movie => movie.Title)
39 .Include(movie => movie.Id)
40 .Include(movie => movie.Genres)
41 .MetaSearchScore("score"))
42 .Limit(10)
43 .ToList();
44
45 // print results
46 foreach (var movie in results)
47 {
48 Console.WriteLine(movie.ToJson());
49 }
50 }
51}
52
53[BsonIgnoreExtraElements]
54public class MovieDocument
55{
56 [BsonIgnoreIfDefault]
57 public ObjectId Id { get; set; }
58 public string Plot { get; set; }
59 public string Title { get; set; }
60 public string[] Genres { get; set; }
61 public double Score { get; set; }
62}

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목에 ghost라는 텀(must 절)이 포함되어 있지만 지정된 ObjectIds(mustNot 절)가 없는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost라는 텀이 포함되고(must 절) 지정된 ObjectIds(filter 절)가 있는 영화를 검색하지만 score를 50% 감소시킵니다(boost).

결과 수를 10 개 문서로 제한합니다.

  • 결과에는 문서의 title, plot_id 필드만 포함됩니다.

  • 결과에서 문서의 점수를 보여주는 score라는 이름의 필드를 추가합니다.

1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Attributes;
3using MongoDB.Bson.Serialization.Conventions;
4using MongoDB.Driver;
5using MongoDB.Driver.Search;
6
7public class BuryDocumentCompoundExample
8{
9 private const string MongoConnectionString = "<connection-string>";
10
11 public static void Main(string[] args)
12 {
13 // allow automapping of the camelCase database fields to our MovieDocument
14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
16
17 // connect to your Atlas cluster
18 var mongoClient = new MongoClient(MongoConnectionString);
19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
21
22 string id1 = "573a13cef29313caabd873a2";
23 string id2 = "573a13cdf29313caabd83c08";
24
25 // define and run pipeline
26 var results = moviesCollection.Aggregate()
27 .Search(Builders<MovieDocument>.Search.Compound()
28 .Should(Builders<MovieDocument>.Search.Compound()
29 .Must(Builders<MovieDocument>.Search.Text(
30 Builders<MovieDocument>.SearchPath.Multi(movie => movie.Title, movie => movie.Plot), "ghost"))
31 .MustNot(Builders<MovieDocument>.Search.In(movie => movie.Id, new[] {ObjectId.Parse(id1), ObjectId.Parse(id2)}))
32 )
33 .Should(Builders<MovieDocument>.Search.Compound()
34 .Must(Builders<MovieDocument>.Search.Text(
35 Builders<MovieDocument>.SearchPath.Multi(movie => movie.Title, movie => movie.Plot), "ghost"))
36 .Filter(Builders<MovieDocument>.Search.In(movie => movie.Id, new[] {ObjectId.Parse(id1), ObjectId.Parse(id2)}, score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(0.5)))
37 ),
38 indexName: "compound-query-custom-score-tutorial")
39 .Project<MovieDocument>(Builders<MovieDocument>.Projection
40 .Include(movie => movie.Plot)
41 .Include(movie => movie.Title)
42 .Include(movie => movie.Id)
43 .MetaSearchScore("score"))
44 .Limit(10)
45 .ToList();
46
47 // print results
48 foreach (var movie in results)
49 {
50 Console.WriteLine(movie.ToJson());
51 }
52 }
53}
54
55[BsonIgnoreExtraElements]
56public class MovieDocument
57{
58 [BsonIgnoreIfDefault]
59 public ObjectId Id { get; set; }
60 public string Plot { get; set; }
61 public string Title { get; set; }
62 public double Score { get; set; }
63}
3

연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.

4
dotnet run compound-bury-results.csproj
{ "_id" : ObjectId("573a139af29313caabcefcce"), "plot" : "Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.", "title" : "The Canterville Ghost", "genres" : ["Family", "Drama", "Fantasy"], "score" : 5.9096131324768066 }
{ "_id" : ObjectId("573a13d8f29313caabda5dc1"), "plot" : "The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!", "title" : "The Little Ghost", "genres" : ["Family", "Fantasy"], "score" : 5.3676662445068359 }
{ "_id" : ObjectId("573a13c0f29313caabd6139d"), "plot" : "Renowned \"ghost hunter\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.", "title" : "Death of a Ghost Hunter", "genres" : ["Horror", "Thriller"], "score" : 4.6763143539428711 }
{ "_id" : ObjectId("573a1398f29313caabcebf6f"), "plot" : "After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.", "title" : "Ghost", "genres" : ["Drama", "Fantasy", "Romance"], "score" : 3.9638845920562744 }
{ "_id" : ObjectId("573a13cdf29313caabd83c08"), "plot" : "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "title" : "Ghost", "genres" : ["Drama", "Fantasy", "Mystery"], "score" : 3.9638845920562744 }
{ "_id" : ObjectId("573a13cef29313caabd873a2"), "plot" : "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "title" : "Ghost", "genres" : ["Drama", "Fantasy", "Mystery"], "score" : 3.9638845920562744 }
{ "_id" : ObjectId("573a13c3f29313caabd6a149"), "plot" : "What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...", "title" : "Coming Soon", "genres" : ["Horror", "Thriller"], "score" : 3.5267119407653809 }
{ "_id" : ObjectId("573a1398f29313caabce912c"), "plot" : "Three unemployed parapsychology professors set up shop as a unique ghost removal service.", "title" : "Ghostbusters", "genres" : ["Comedy", "Fantasy"], "score" : 3.5241782665252686 }
{ "_id" : ObjectId("573a139cf29313caabcf5a48"), "plot" : "Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.", "title" : "Casper Meets Wendy", "genres" : ["Adventure", "Comedy", "Family"], "score" : 3.5241782665252686 }
{ "_id" : ObjectId("573a13bdf29313caabd58274"), "plot" : "Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...", "title" : "Bhoothnath", "genres" : ["Comedy", "Drama", "Fantasy"], "score" : 3.4605300426483154 }

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 용어 ghost가 포함되어 있고, Comedy 장르에 속하지 않습니다. Atlas Search는 plot 또는 title 필드에 ghost라는 용어가 있는 Comedy 장르의 문서를 반환하지 않았습니다. 이는 쿼리가 해당 문서의 점수를 50% 낮췄기 때문에 상위 10개의 문서에 포함되지 않았기 때문입니다.

dotnet run compound-bury-results.csproj
{ "_id" : ObjectId("573a139af29313caabcefcce"), "plot" : "Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.", "title" : "The Canterville Ghost", "score" : 5.9096131324768066 }
{ "_id" : ObjectId("573a13d8f29313caabda5dc1"), "plot" : "The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!", "title" : "The Little Ghost", "score" : 5.3676662445068359 }
{ "_id" : ObjectId("573a13c0f29313caabd6139d"), "plot" : "Renowned \"ghost hunter\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.", "title" : "Death of a Ghost Hunter", "score" : 4.6763143539428711 }
{ "_id" : ObjectId("573a1398f29313caabcebf6f"), "plot" : "After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.", "title" : "Ghost", "score" : 3.9638845920562744 }
{ "_id" : ObjectId("573a13cdf29313caabd83c08"), "plot" : "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "title" : "Ghost", "score" : 3.9638845920562744 }
{ "_id" : ObjectId("573a13cef29313caabd873a2"), "plot" : "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "title" : "Ghost", "score" : 3.9638845920562744 }
{ "_id" : ObjectId("573a13c3f29313caabd6a149"), "plot" : "What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...", "title" : "Coming Soon", "score" : 3.5267119407653809 }
{ "_id" : ObjectId("573a1398f29313caabce912c"), "plot" : "Three unemployed parapsychology professors set up shop as a unique ghost removal service.", "title" : "Ghostbusters", "score" : 3.5241782665252686 }
{ "_id" : ObjectId("573a139cf29313caabcf5a48"), "plot" : "Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.", "title" : "Casper Meets Wendy", "score" : 3.5241782665252686 }
{ "_id" : ObjectId("573a13bdf29313caabd58274"), "plot" : "Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...", "title" : "Bhoothnath", "score" : 3.4605300426483154 }

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 텀 ghost가 포함되어 있고 _id 필드에 지정된 ObjectIds가 없습니다. Atlas Search는 지정된 ObjectIds를 가진 문서를 반환하지 않았는데 이는 title 필드에 쿼리 텀 ghost가 포함되어 있음에도 불구하고 쿼리가 이 문서들의 점수를 50% 낮췄기 때문에 이 문서들이 상위 10개 문서에 포함되지 않았기 때문입니다.

1
2

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목(must 절)에 ghost 라는 용어가 포함되고 comedy 장르(mustNot 절)에 속하지 않는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost 용어가 포함되어 있고(must 절)comedy 장르에 속하지만(filter 절), score를 50% 낮추는(boost) 영화를 검색합니다.

결과 수를 10 개 문서로 제한합니다.

  • 결과 문서에서 _id, title, plotgenres 필드만 포함됩니다.

  • 결과에 점수를 표시하는 score라는 필드를 추가합니다.

1package main
2
3import (
4 "context"
5 "fmt"
6 "time"
7
8 "go.mongodb.org/mongo-driver/bson"
9 "go.mongodb.org/mongo-driver/mongo"
10 "go.mongodb.org/mongo-driver/mongo/options"
11)
12
13// define structure of movies collection
14type MovieCollection struct {
15 title string `bson:"Title,omitempty"`
16 plot string `bson:"Plot,omitempty"`
17}
18
19func main() {
20 var err error
21 // connect to the Atlas cluster
22 ctx := context.Background()
23 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
24 if err != nil {
25 panic(err)
26 }
27 defer client.Disconnect(ctx)
28 // set namespace
29 collection := client.Database("sample_mflix").Collection("movies")
30 // define pipeline
31 searchStage := bson.D{{"$search", bson.D{
32 {"index", "compound-query-custom-score-tutorial"},
33 {"compound", bson.D{
34 {"should", bson.A{
35 bson.D{{"compound", bson.D{
36 {"must", bson.A{
37 bson.D{{"text", bson.D{
38 {"query", "ghost"},
39 {"path", bson.A{ "plot", "title" }},
40 }}},
41 }},
42 {"mustNot", bson.A{
43 bson.D{{"text", bson.D{
44 {"query", "Comedy"},
45 {"path", bson.A{ "genres" }},
46 }}},
47 }},
48 }}},
49 bson.D{{"compound", bson.D{
50 {"must", bson.A{
51 bson.D{{"text", bson.D{
52 {"query", "ghost"},
53 {"path", bson.A{ "plot", "title" }},
54 }}},
55 }},
56 {"filter", bson.A{
57 bson.D{{"text", bson.D{
58 {"query", "Comedy"},
59 {"path", bson.A{ "genres" }},
60 }}},
61 }},
62 {"score", bson.D{{"boost", bson.D{{"value", 0.5}}}}},
63 }}},
64 }},
65 }},
66 }}}
67 limitStage := bson.D{{"$limit", 10}}
68 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}, {"genres", 1}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
69 // specify the amount of time the operation can run on the server
70 opts := options.Aggregate().SetMaxTime(5 * time.Second)
71 // run pipeline
72 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
73 if err != nil {
74 panic(err)
75 }
76 // print results
77 var results []bson.D
78 if err = cursor.All(context.TODO(), &results); err != nil {
79 panic(err)
80 }
81 for _, result := range results {
82 fmt.Println(result)
83 }
84}

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목에 ghost라는 텀(must 절)이 포함되어 있지만 지정된 ObjectIds(mustNot 절)가 없는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost라는 텀이 포함되고(must 절) 지정된 ObjectIds(filter 절)가 있는 영화를 검색하지만 score를 50% 감소시킵니다(boost).

결과 수를 10 개 문서로 제한합니다.

  • 결과에는 문서의 title, plot_id 필드만 포함됩니다.

  • 결과에서 문서의 점수를 보여주는 score라는 이름의 필드를 추가합니다.

1package main
2
3import (
4 "context"
5 "fmt"
6 "time"
7 "log"
8
9 "go.mongodb.org/mongo-driver/bson"
10 "go.mongodb.org/mongo-driver/mongo"
11 "go.mongodb.org/mongo-driver/mongo/options"
12 "go.mongodb.org/mongo-driver/bson/primitive"
13)
14
15// define structure of movies collection
16type MovieCollection struct {
17 title string `bson:"Title,omitempty"`
18 plot string `bson:"Plot,omitempty"`
19}
20
21func main() {
22 var err error
23 // connect to the Atlas cluster
24 ctx := context.Background()
25 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
26 if err != nil {
27 panic(err)
28 }
29 defer client.Disconnect(ctx)
30 // set namespace
31 collection := client.Database("sample_mflix").Collection("movies")
32 // define variable
33 var objectIDFromHex = func(hex string) primitive.ObjectID {
34 objectID, err := primitive.ObjectIDFromHex(hex)
35 if err != nil {
36 log.Fatal(err)
37 }
38 return objectID
39 }
40 // define pipeline
41 searchStage := bson.D{{"$search", bson.D{
42 {"index", "compound-query-custom-score-tutorial"},
43 {"compound", bson.D{
44 {"should", bson.A{
45 bson.D{{"compound", bson.D{
46 {"must", bson.A{
47 bson.D{{"text", bson.D{
48 {"query", "ghost"},
49 {"path", bson.A{ "plot", "title" }},
50 }}},
51 }},
52 {"mustNot", bson.A{
53 bson.D{{"in", bson.D{
54 {"value", bson.A{objectIDFromHex("573a13cdf29313caabd83c08"), objectIDFromHex("573a13cef29313caabd873a2") }},
55 {"path", "_id"},
56 }}},
57 }},
58 }}},
59 bson.D{{"compound", bson.D{
60 {"must", bson.A{
61 bson.D{{"text", bson.D{
62 {"query", "ghost"},
63 {"path", bson.A{ "plot", "title" }},
64 }}},
65 }},
66 {"filter", bson.A{
67 bson.D{{"in", bson.D{
68 {"value", bson.A{ objectIDFromHex("573a13cdf29313caabd83c08"), objectIDFromHex("573a13cef29313caabd873a2")}},
69 {"path", "_id"},
70 }}},
71 }},
72 {"score", bson.D{{"boost", bson.D{{"value", 0.5}}}}},
73 }}},
74 }},
75 }},
76 }}}
77
78 limitStage := bson.D{{"$limit", 10}}
79 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
80 // specify the amount of time the operation can run on the server
81 opts := options.Aggregate().SetMaxTime(5 * time.Second)
82 // run pipeline
83 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
84 if err != nil {
85 panic(err)
86 }
87 // print results
88 var results []bson.D
89 if err = cursor.All(context.TODO(), &results); err != nil {
90 panic(err)
91 }
92 for _, result := range results {
93 fmt.Println(result)
94 }
95}
3

연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.

4
go run compound-bury-results.go
[{plot Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.} {genres [Family Drama Fantasy]} {title The Canterville Ghost} {score 5.909613132476807}]
[{plot The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!} {genres [Family Fantasy]} {title The Little Ghost} {score 5.367666244506836}]
[{plot Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.} {genres [Horror Thriller]} {title Death of a Ghost Hunter} {score 4.676314353942871}]
[{plot After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.} {genres [Drama Fantasy Romance]} {title Ghost} {score 3.9638845920562744}]
[{plot A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.} {genres [Drama Fantasy Mystery]} {title Ghost} {score 3.9638845920562744}]
[{plot A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.} {genres [Drama Fantasy Mystery]} {title Ghost} {score 3.9638845920562744}]
[{plot What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...} {genres [Horror Thriller]} {title Coming Soon} {score 3.526711940765381}]
[{plot Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...} {genres [Drama Horror Thriller]} {title Ghost Story} {score 3.3177831172943115}]
[{plot Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.} {genres [Action Fantasy Thriller]} {title Ghost Rider} {score 3.3177831172943115}]
[{plot A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...} {genres [Horror Mystery]} {title Ghost Ship} {score 3.3177831172943115}]

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 용어 ghost가 포함되어 있고, Comedy 장르에 속하지 않습니다. Atlas Search는 plot 또는 title 필드에 ghost라는 용어가 있는 Comedy 장르의 문서를 반환하지 않았습니다. 이는 쿼리가 해당 문서의 점수를 50% 낮췄기 때문에 상위 10개의 문서에 포함되지 않았기 때문입니다.

go run compound-bury-results.go
[{plot Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.} {title The Canterville Ghost} {score 5.909613132476807}]
[{plot The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!} {title The Little Ghost} {score 5.367666244506836}]
[{plot Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.} {title Death of a Ghost Hunter} {score 4.676314353942871}]
[{plot After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.} {title Ghost} {score 3.9638845920562744}]
[{plot What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...} {title Coming Soon} {score 3.526711940765381}]
[{plot Three unemployed parapsychology professors set up shop as a unique ghost removal service.} {title Ghostbusters} {score 3.5241782665252686}]
[{plot Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.} {title Casper Meets Wendy} {score 3.5241782665252686}]
[{plot Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...} {title Bhoothnath} {score 3.4605300426483154}]
[{plot Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...} {title Ghost Story} {score 3.3177831172943115}]
[{plot Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...} {title Ghost Dad} {score 3.3177831172943115}]

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 텀 ghost가 포함되어 있고 _id 필드에 지정된 ObjectIds가 없습니다. Atlas Search는 지정된 ObjectIds를 가진 문서를 반환하지 않았는데 이는 title 필드에 쿼리 텀 ghost가 포함되어 있음에도 불구하고 쿼리가 이 문서들의 점수를 50% 낮췄기 때문에 이 문서들이 상위 10개 문서에 포함되지 않았기 때문입니다.

1

junit

4.11 또는 그 이상의 버전

mongodb-driver-sync

4.3.0 또는 그 이상의 버전

slf4j-log4j12

1.7.30 또는 그 이상의 버전

2
3

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목(must 절)에 ghost 라는 용어가 포함되고 comedy 장르(mustNot 절)에 속하지 않는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost 용어가 포함되어 있고(must 절)comedy 장르에 속하지만(filter 절), score를 50% 낮추는(boost) 영화를 검색합니다.

결과 수를 10 개 문서로 제한합니다.

  • 결과 문서에서 _id, title, plotgenres 필드만 포함됩니다.

  • 결과에 점수를 표시하는 score라는 필드를 추가합니다.

1import java.util.Arrays;
2import static com.mongodb.client.model.Aggregates.limit;
3import static com.mongodb.client.model.Aggregates.project;
4import static com.mongodb.client.model.Projections.*;
5import com.mongodb.client.MongoClient;
6import com.mongodb.client.MongoClients;
7import com.mongodb.client.MongoCollection;
8import com.mongodb.client.MongoDatabase;
9
10import org.bson.Document;
11
12public class CompoundBuryQuery {
13 public static void main( String[] args ) {
14 // define query
15 Document agg =
16 new Document("$search",
17 new Document("index", "compound-query-custom-score-tutorial")
18 .append("compound",
19 new Document("should", Arrays.asList(new Document("compound",
20 new Document("must", Arrays.asList(new Document("text",
21 new Document("query", "ghost")
22 .append("path", Arrays.asList("plot", "title")))))
23 .append("mustNot", Arrays.asList(new Document("text",
24 new Document("query", "Comedy")
25 .append("path", Arrays.asList("genres")))))
26 ),
27 new Document("compound",
28 new Document("must", Arrays.asList(new Document("text",
29 new Document("query", "ghost")
30 .append("path", Arrays.asList("plot", "title")))))
31 .append("filter", Arrays.asList(new Document("text",
32 new Document("query", "Comedy")
33 .append("path", Arrays.asList("genres")))))
34 .append("score", new Document("boost",
35 new Document("value", 0.5d))))))
36 )
37 );
38 // specify connection
39 String uri = "<connection-string>";
40 // establish connection and set namespace
41 try (MongoClient mongoClient = MongoClients.create(uri)) {
42 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
43 MongoCollection<Document> collection = database.getCollection("movies");
44 // run query and print results
45 collection.aggregate(Arrays.asList(agg,
46 limit(10),
47 project(fields(
48 include("title", "plot", "genres", "_id"),
49 computed("score", new Document("$meta", "searchScore"))))))
50 .forEach(doc -> System.out.println(doc.toJson()));
51 }
52 }
53}

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목에 ghost라는 텀(must 절)이 포함되어 있지만 지정된 ObjectIds(mustNot 절)가 없는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost라는 텀이 포함되고(must 절) 지정된 ObjectIds(filter 절)가 있는 영화를 검색하지만 score를 50% 감소시킵니다(boost).

결과 수를 10 개 문서로 제한합니다.

  • 결과에는 문서의 title, plot_id 필드만 포함됩니다.

  • 결과에서 문서의 점수를 보여주는 score라는 이름의 필드를 추가합니다.

1import java.util.Arrays;
2import static com.mongodb.client.model.Aggregates.limit;
3import static com.mongodb.client.model.Aggregates.project;
4import static com.mongodb.client.model.Projections.*;
5import com.mongodb.client.MongoClient;
6import com.mongodb.client.MongoClients;
7import com.mongodb.client.MongoCollection;
8import com.mongodb.client.MongoDatabase;
9import org.bson.types.ObjectId;
10
11import org.bson.Document;
12
13public class CompoundBuryQuery {
14 public static void main( String[] args ) {
15 // define query
16 Document agg =
17 new Document("$search",
18 new Document("index", "compound-query-custom-score-tutorial")
19 .append("compound",
20 new Document("should", Arrays.asList(
21 new Document("compound",
22 new Document("must", Arrays.asList(new Document("text",
23 new Document("query", "ghost")
24 .append("path", Arrays.asList("plot", "title")))))
25 .append("mustNot", Arrays.asList(new Document("in",
26 new Document("value", Arrays.asList(new ObjectId("573a13cdf29313caabd83c08"),
27 new ObjectId("573a13cef29313caabd873a2")))
28 .append("path", "_id"))))),
29 new Document("compound",
30 new Document("must", Arrays.asList(new Document("text",
31 new Document("query", "ghost")
32 .append("path", Arrays.asList("plot", "title")))))
33 .append("filter", Arrays.asList(new Document("in",
34 new Document("value", Arrays.asList(new ObjectId("573a13cdf29313caabd83c08"),
35 new ObjectId("573a13cef29313caabd873a2")))
36 .append("path", "_id"))))
37 .append("score", new Document("boost",
38 new Document("value", 0.5d)))))
39 )
40 )
41 );
42 // specify connection
43 String uri = "<connection-string>";
44 // establish connection and set namespace
45 try (MongoClient mongoClient = MongoClients.create(uri)) {
46 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
47 MongoCollection<Document> collection = database.getCollection("movies");
48 // run query and print results
49 collection.aggregate(Arrays.asList(agg,
50 limit(10),
51 project(fields(
52 include("title", "plot", "_id"),
53 computed("score", new Document("$meta", "searchScore"))))))
54 .forEach(doc -> System.out.println(doc.toJson()));
55 }
56 }
57}
4

연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.

5
javac CompoundBuryQuery.java
{"_id": {"$oid": "573a139af29313caabcefcce"}, "plot": "Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.", "genres": ["Family", "Drama", "Fantasy"], "title": "The Canterville Ghost", "score": 5.909613132476807}
{"_id": {"$oid": "573a13d8f29313caabda5dc1"}, "plot": "The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!", "genres": ["Family", "Fantasy"], "title": "The Little Ghost", "score": 5.367666244506836}
{"_id": {"$oid": "573a13c0f29313caabd6139d"}, "plot": "Renowned \"ghost hunter\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.", "genres": ["Horror", "Thriller"], "title": "Death of a Ghost Hunter", "score": 4.676314353942871}
{"_id": {"$oid": "573a1398f29313caabcebf6f"}, "plot": "After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.", "genres": ["Drama", "Fantasy", "Romance"], "title": "Ghost", "score": 3.9638845920562744}
{"_id": {"$oid": "573a13cdf29313caabd83c08"}, "plot": "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "genres": ["Drama", "Fantasy", "Mystery"], "title": "Ghost", "score": 3.9638845920562744}
{"_id": {"$oid": "573a13cef29313caabd873a2"}, "plot": "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", "genres": ["Drama", "Fantasy", "Mystery"], "title": "Ghost", "score": 3.9638845920562744}
{"_id": {"$oid": "573a13c3f29313caabd6a149"}, "plot": "What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...", "genres": ["Horror", "Thriller"], "title": "Coming Soon", "score": 3.526711940765381}
{"_id": {"$oid": "573a1397f29313caabce7ea1"}, "plot": "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", "genres": ["Drama", "Horror", "Thriller"], "title": "Ghost Story", "score": 3.3177831172943115}
{"_id": {"$oid": "573a13a4f29313caabd117df"}, "plot": "Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.", "genres": ["Action", "Fantasy", "Thriller"], "title": "Ghost Rider", "score": 3.3177831172943115}
{"_id": {"$oid": "573a13a6f29313caabd185dc"}, "plot": "A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that \"strange things\" happen...", "genres": ["Horror", "Mystery"], "title": "Ghost Ship", "score": 3.3177831172943115}

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 용어 ghost가 포함되어 있고, Comedy 장르에 속하지 않습니다. Atlas Search는 plot 또는 title 필드에 ghost라는 용어가 있는 Comedy 장르의 문서를 반환하지 않았습니다. 이는 쿼리가 해당 문서의 점수를 50% 낮췄기 때문에 상위 10개의 문서에 포함되지 않았기 때문입니다.

javac CompoundBuryQuery.java
{"_id": {"$oid": "573a139af29313caabcefcce"}, "plot": "Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.", "title": "The Canterville Ghost", "score": 5.909613132476807}
{"_id": {"$oid": "573a13d8f29313caabda5dc1"}, "plot": "The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!", "title": "The Little Ghost", "score": 5.367666244506836}
{"_id": {"$oid": "573a13c0f29313caabd6139d"}, "plot": "Renowned \"ghost hunter\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.", "title": "Death of a Ghost Hunter", "score": 4.676314353942871}
{"_id": {"$oid": "573a1398f29313caabcebf6f"}, "plot": "After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.", "title": "Ghost", "score": 3.9638845920562744}
{"_id": {"$oid": "573a13c3f29313caabd6a149"}, "plot": "What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...", "title": "Coming Soon", "score": 3.526711940765381}
{"_id": {"$oid": "573a1398f29313caabce912c"}, "plot": "Three unemployed parapsychology professors set up shop as a unique ghost removal service.", "title": "Ghostbusters", "score": 3.5241782665252686}
{"_id": {"$oid": "573a139cf29313caabcf5a48"}, "plot": "Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.", "title": "Casper Meets Wendy", "score": 3.5241782665252686}
{"_id": {"$oid": "573a13bdf29313caabd58274"}, "plot": "Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...", "title": "Bhoothnath", "score": 3.4605300426483154}
{"_id": {"$oid": "573a1397f29313caabce7ea1"}, "plot": "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", "title": "Ghost Story", "score": 3.3177831172943115}
{"_id": {"$oid": "573a1398f29313caabcebf79"}, "plot": "Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...", "title": "Ghost Dad", "score": 3.3177831172943115}

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 텀 ghost가 포함되어 있고 _id 필드에 지정된 ObjectIds가 없습니다. Atlas Search는 지정된 ObjectIds를 가진 문서를 반환하지 않았는데 이는 title 필드에 쿼리 텀 ghost가 포함되어 있음에도 불구하고 쿼리가 이 문서들의 점수를 50% 낮췄기 때문에 이 문서들이 상위 10개 문서에 포함되지 않았기 때문입니다.

1

mongodb-driver-kotlin-coroutine

4.10.0 또는 그 이상의 버전

2
3

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목(must 절)에 ghost 라는 용어가 포함되고 comedy 장르(mustNot 절)에 속하지 않는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost 용어가 포함되어 있고(must 절)comedy 장르에 속하지만(filter 절), score를 50% 낮추는(boost) 영화를 검색합니다.

결과 수를 10 개 문서로 제한합니다.

  • 결과 문서에서 _id, title, plotgenres 필드만 포함됩니다.

  • 결과에 점수를 표시하는 score라는 필드를 추가합니다.

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7
8fun main() {
9 // establish connection and set namespace
10 val uri = "<connection-string>"
11 val mongoClient = MongoClient.create(uri)
12 val database = mongoClient.getDatabase("sample_mflix")
13 val collection = database.getCollection<Document>("movies")
14
15 runBlocking {
16 // define clauses
17 val mustClause = listOf(
18 Document("text",
19 Document("query", "ghost")
20 .append("path", listOf("plot","title"))
21 )
22 )
23
24 val mustNotClauseAndFilterClause = listOf(
25 Document("text",
26 Document("query", "Comedy")
27 .append("path", listOf("genres"))
28 )
29 )
30
31 val compound1 = Document("must", mustClause)
32 .append("mustNot", mustNotClauseAndFilterClause)
33
34 val compound2 = Document("must", mustClause)
35 .append("filter", mustNotClauseAndFilterClause)
36 .append("score",
37 Document("boost",
38 Document("value", 0.5)
39 )
40 )
41
42 val agg = Document("\$search",
43 Document("index", "compound-query-custom-score-tutorial")
44 .append("compound", Document("should", listOf(
45 Document("compound", compound1),
46 Document("compound", compound2)
47 )))
48 )
49
50 val resultsFlow = collection.aggregate<Document>(
51 listOf(
52 agg,
53 limit(10),
54 project(fields(
55 include("title", "plot", "genres"),
56 computed("score", Document("\$meta", "searchScore"))
57 ))
58 )
59 )
60 resultsFlow.collect { println(it) }
61 }
62 mongoClient.close()
63}

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목에 ghost라는 텀(must 절)이 포함되어 있지만 지정된 ObjectIds(mustNot 절)가 없는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost라는 텀이 포함되고(must 절) 지정된 ObjectIds(filter 절)가 있는 영화를 검색하지만 score를 50% 감소시킵니다(boost).

결과 수를 10 개 문서로 제한합니다.

  • 결과에는 문서의 title, plot_id 필드만 포함됩니다.

  • 결과에서 문서의 점수를 보여주는 score라는 이름의 필드를 추가합니다.

1import com.mongodb.client.model.Aggregates.limit
2import com.mongodb.client.model.Aggregates.project
3import com.mongodb.client.model.Projections.*
4import com.mongodb.kotlin.client.coroutine.MongoClient
5import kotlinx.coroutines.runBlocking
6import org.bson.Document
7import org.bson.types.ObjectId
8
9fun main() {
10 // establish connection and set namespace
11 val uri = "<connection-string>"
12 val mongoClient = MongoClient.create(uri)
13 val database = mongoClient.getDatabase("sample_mflix")
14 val collection = database.getCollection<Document>("movies")
15
16 runBlocking {
17 // define clauses
18 val mustClause = listOf(
19 Document("text",
20 Document("query", "ghost")
21 .append("path", listOf("plot","title"))
22 )
23 )
24
25 val mustNotClauseAndFilterClause = listOf(
26 Document("in",
27 Document("value", listOf(ObjectId("573a13cdf29313caabd83c08"), ObjectId("573a13cef29313caabd873a2")))
28 .append("path", "_id")
29 )
30 )
31
32 val compound1 = Document("must", mustClause)
33 .append("mustNot", mustNotClauseAndFilterClause)
34
35 val compound2 = Document("must", mustClause)
36 .append("filter", mustNotClauseAndFilterClause)
37 .append("score",
38 Document("boost",
39 Document("value", 0.5)
40 )
41 )
42
43 val agg = Document("\$search",
44 Document("index", "compound-query-custom-score-tutorial")
45 .append("compound", Document("should", listOf(
46 Document("compound", compound1),
47 Document("compound", compound2)
48 )))
49 )
50
51 val resultsFlow = collection.aggregate<Document>(
52 listOf(
53 agg,
54 limit(10),
55 project(fields(
56 include("title", "plot", "_id"),
57 computed("score", Document("\$meta", "searchScore"))
58 ))
59 )
60 )
61 resultsFlow.collect { println(it) }
62 }
63 mongoClient.close()
64}
4

연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.

5

IDE에서 CompoundBuryQuery.kt 프로그램을 실행하면 다음 문서가 인쇄됩니다.

dotnet run compound-bury-results.csproj
Document{{_id=573a139af29313caabcefcce, plot=Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness., genres=[Family, Drama, Fantasy], title=The Canterville Ghost, score=5.909613132476807}}
Document{{_id=573a13d8f29313caabda5dc1, plot=The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!, genres=[Family, Fantasy], title=The Little Ghost, score=5.367666244506836}}
Document{{_id=573a13c0f29313caabd6139d, plot=Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror., genres=[Horror, Thriller], title=Death of a Ghost Hunter, score=4.676314353942871}}
Document{{_id=573a1398f29313caabcebf6f, plot=After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic., genres=[Drama, Fantasy, Romance], title=Ghost, score=3.9638845920562744}}
Document{{_id=573a13cdf29313caabd83c08, plot=A man tries to solve his lover's murder by communicating with her spirit through the help of a medium., genres=[Drama, Fantasy, Mystery], title=Ghost, score=3.9638845920562744}}
Document{{_id=573a13cef29313caabd873a2, plot=A man tries to solve his lover's murder by communicating with her spirit through the help of a medium., genres=[Drama, Fantasy, Mystery], title=Ghost, score=3.9638845920562744}}
Document{{_id=573a13c3f29313caabd6a149, plot=What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ..., genres=[Horror, Thriller], title=Coming Soon, score=3.526711940765381}}
Document{{_id=573a1397f29313caabce7ea1, plot=Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ..., genres=[Drama, Horror, Thriller], title=Ghost Story, score=3.3177831172943115}}
Document{{_id=573a13a4f29313caabd117df, plot=Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself., genres=[Action, Fantasy, Thriller], title=Ghost Rider, score=3.3177831172943115}}
Document{{_id=573a13a6f29313caabd185dc, plot=A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen..., genres=[Horror, Mystery], title=Ghost Ship, score=3.3177831172943115}}

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 용어 ghost가 포함되어 있고, Comedy 장르에 속하지 않습니다. Atlas Search는 plot 또는 title 필드에 ghost라는 용어가 있는 Comedy 장르의 문서를 반환하지 않았습니다. 이는 쿼리가 해당 문서의 점수를 50% 낮췄기 때문에 상위 10개의 문서에 포함되지 않았기 때문입니다.

dotnet run compound-bury-results.csproj
Document{{_id=573a139af29313caabcefcce, plot=Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness., title=The Canterville Ghost, score=5.909613132476807}}
Document{{_id=573a13d8f29313caabda5dc1, plot=The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!, title=The Little Ghost, score=5.367666244506836}}
Document{{_id=573a13c0f29313caabd6139d, plot=Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror., title=Death of a Ghost Hunter, score=4.676314353942871}}
Document{{_id=573a1398f29313caabcebf6f, plot=After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic., title=Ghost, score=3.9638845920562744}}
Document{{_id=573a13c3f29313caabd6a149, plot=What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ..., title=Coming Soon, score=3.526711940765381}}
Document{{_id=573a1398f29313caabce912c, plot=Three unemployed parapsychology professors set up shop as a unique ghost removal service., title=Ghostbusters, score=3.5241782665252686}}
Document{{_id=573a139cf29313caabcf5a48, plot=Casper, a ghost, teams up with Wendy, a witch, against an evil warlock., title=Casper Meets Wendy, score=3.5241782665252686}}
Document{{_id=573a13bdf29313caabd58274, plot=Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy..., title=Bhoothnath, score=3.4605300426483154}}
Document{{_id=573a1397f29313caabce7ea1, plot=Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ..., title=Ghost Story, score=3.3177831172943115}}
Document{{_id=573a1398f29313caabcebf79, plot=Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ..., title=Ghost Dad, score=3.3177831172943115}}

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 텀 ghost가 포함되어 있고 _id 필드에 지정된 ObjectIds가 없습니다. Atlas Search는 지정된 ObjectIds를 가진 문서를 반환하지 않았는데 이는 title 필드에 쿼리 텀 ghost가 포함되어 있음에도 불구하고 쿼리가 이 문서들의 점수를 50% 낮췄기 때문에 이 문서들이 상위 10개 문서에 포함되지 않았기 때문입니다.

1
2

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목(must 절)에 ghost 라는 용어가 포함되고 comedy 장르(mustNot 절)에 속하지 않는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost 용어가 포함되어 있고(must 절)comedy 장르에 속하지만(filter 절), score를 50% 낮추는(boost) 영화를 검색합니다.

결과 수를 10 개 문서로 제한합니다.

  • 결과 문서에서 _id, title, plotgenres 필드만 포함됩니다.

  • 결과에 점수를 표시하는 score라는 필드를 추가합니다.

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas cluster
4const uri = "<connection-string>";
5const client = new MongoClient(uri);
6
7async function run() {
8 try {
9 await client.connect();
10
11 // set namespace
12 const database = client.db("sample_mflix");
13 const coll = database.collection("movies");
14
15 // define pipeline
16 const agg = [
17 {
18 "$search": {
19 "index": "compound-query-custom-score-tutorial",
20 "compound": {
21 "should": [
22 {
23 "compound": {
24 "must": [
25 {
26 "text": {
27 "query": "ghost",
28 "path": [
29 "plot", "title"
30 ]
31 }
32 }
33 ],
34 "mustNot": [
35 {
36 "text": {
37 "query": "Comedy",
38 "path": [
39 "genres"
40 ]
41 }
42 }
43 ]
44 }
45 }, {
46 "compound": {
47 "must": [
48 {
49 "text": {
50 "query": "ghost",
51 "path": [
52 "plot", "title"
53 ]
54 }
55 }
56 ],
57 "filter": [
58 {
59 "text": {
60 "query": "Comedy",
61 "path": [
62 "genres"
63 ]
64 }
65 }
66 ],
67 "score": { "boost": { "value": 0.5 } }
68 }
69 }
70 ]
71 }
72 }
73 }, {
74 "$limit": 10
75 }, {
76 "$project": {
77 "_id": 1,
78 "title": 1,
79 "plot": 1,
80 "genres": 1,
81 "score": { "$meta": "searchScore" }
82 }
83 }
84 ];
85
86 // run pipeline
87 const result = coll.aggregate(agg);
88
89 // print results
90 await result.forEach((doc) => console.dir(JSON.stringify(doc)));
91 } finally {
92 await client.close();
93 }
94}
95run().catch(console.dir);

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목에 ghost라는 텀(must 절)이 포함되어 있지만 지정된 ObjectIds(mustNot 절)가 없는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost라는 텀이 포함되고(must 절) 지정된 ObjectIds(filter 절)가 있는 영화를 검색하지만 score를 50% 감소시킵니다(boost).

결과 수를 10 개 문서로 제한합니다.

  • 결과에는 문서의 title, plot_id 필드만 포함됩니다.

  • 결과에서 문서의 점수를 보여주는 score라는 이름의 필드를 추가합니다.

1const { MongoClient } = require("mongodb");
2const { ObjectId } = require("mongodb");
3
4// connect to your Atlas cluster
5const uri = "<connection-string>";
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 await client.connect();
11
12 // set namespace
13 const database = client.db("sample_mflix");
14 const coll = database.collection("movies");
15
16 // define pipeline
17 const agg = [
18 {
19 '$search': {
20 'index': 'compound-query-custom-score-tutorial',
21 'compound': {
22 'should': [
23 {
24 'compound': {
25 'must': [
26 {
27 'text': {
28 'query': 'ghost',
29 'path': [ 'plot', 'title' ]
30 }
31 }
32 ],
33 'mustNot': [
34 {
35 'in': {
36 'value': [ new ObjectId('573a13cdf29313caabd83c08'), new ObjectId('573a13cef29313caabd873a2') ],
37 'path': '_id'
38 }
39 }
40 ]
41 }
42 }, {
43 'compound': {
44 'must': [
45 {
46 'text': {
47 'query': 'ghost',
48 'path': [ 'plot', 'title' ]
49 }
50 }
51 ],
52 'filter': [
53 {
54 'in': {
55 'value': [ new ObjectId('573a13cdf29313caabd83c08'), new ObjectId('573a13cef29313caabd873a2') ],
56 'path': '_id'
57 }
58 }
59 ],
60 'score': {
61 'boost': { 'value': 0.5 }
62 }
63 }
64 }
65 ]
66 }
67 }
68 }, {
69 '$limit': 10
70 }, {
71 '$project': {
72 '_id': 1,
73 'title': 1,
74 'plot': 1,
75 'score': { '$meta': 'searchScore' }
76 }
77 }
78 ];
79
80 // run pipeline
81 const result = coll.aggregate(agg);
82
83 // print results
84 await result.forEach((doc) => console.dir(JSON.stringify(doc)));
85 } finally {
86 await client.close();
87 }
88}
89run().catch(console.dir);
3

연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.

4

다음 명령을 실행하여 컬렉션을 쿼리합니다.

node compound-bury-results.js
{"_id":"573a139af29313caabcefcce","plot":"Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.","genres":["Family","Drama","Fantasy"],"title":"The Canterville Ghost","score":5.909613132476807}
{"_id":"573a13d8f29313caabda5dc1","plot":"The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!","genres":["Family","Fantasy"],"title":"The Little Ghost","score":5.367666244506836}
{"_id":"573a13c0f29313caabd6139d","plot":"Renowned \\"ghost hunter\\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.","genres":["Horror","Thriller"],"title":"Death of a Ghost Hunter","score":4.676314353942871}
{"_id":"573a1398f29313caabcebf6f","plot":"After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.","genres":["Drama","Fantasy","Romance"],"title":"Ghost","score":3.9638845920562744}
{"_id":"573a13cdf29313caabd83c08","plot":"A man tries to solve his lovers murder by communicating with her spirit through the help of a medium.","genres":["Drama","Fantasy","Mystery"],"title":"Ghost","score":3.9638845920562744}
{"_id":"573a13cef29313caabd873a2","plot":"A man tries to solve his lovers murder by communicating with her spirit through the help of a medium.","genres":["Drama","Fantasy","Mystery"],"title":"Ghost","score":3.9638845920562744}
{"_id":"573a13c3f29313caabd6a149","plot":"What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...","genres":["Horror","Thriller"],"title":"Coming Soon","score":3.526711940765381}
{"_id":"573a1397f29313caabce7ea1","plot":"Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderleys twin sons dies in a bizarre accident, the group ...","genres":["Drama","Horror","Thriller"],"title":"Ghost Story","score":3.3177831172943115}
{"_id":"573a13a4f29313caabd117df","plot":"Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.","genres":["Action","Fantasy","Thriller"],"title":"Ghost Rider","score":3.3177831172943115}
{"_id":"573a13a6f29313caabd185dc","plot":"A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that \\"strange things\\" happen...","genres":["Horror","Mystery"],"title":"Ghost Ship","score":3.3177831172943115}

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 용어 ghost가 포함되어 있고, Comedy 장르에 속하지 않습니다. Atlas Search는 plot 또는 title 필드에 ghost라는 용어가 있는 Comedy 장르의 문서를 반환하지 않았습니다. 이는 쿼리가 해당 문서의 점수를 50% 낮췄기 때문에 상위 10개의 문서에 포함되지 않았기 때문입니다.

node compound-bury-results.js
{"_id":"573a139af29313caabcefcce","plot":"Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.","title":"The Canterville Ghost","score":5.909613132476807}
{"_id":"573a13d8f29313caabda5dc1","plot":"The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!","title":"The Little Ghost","score":5.367666244506836}
{"_id":"573a13c0f29313caabd6139d","plot":"Renowned \\"ghost hunter\\", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.","title":"Death of a Ghost Hunter","score":4.676314353942871}
{"_id":"573a1398f29313caabcebf6f","plot":"After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.","title":"Ghost","score":3.9638845920562744}
{"_id":"573a13c3f29313caabd6a149","plot":"What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...","title":"Coming Soon","score":3.526711940765381}
{"_id":"573a1398f29313caabce912c","plot":"Three unemployed parapsychology professors set up shop as a unique ghost removal service.","title":"Ghostbusters","score":3.5241782665252686}
{"_id":"573a139cf29313caabcf5a48","plot":"Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.","title":"Casper Meets Wendy","score":3.5241782665252686}
{"_id":"573a13bdf29313caabd58274","plot":"Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...","title":"Bhoothnath","score":3.4605300426483154}
{"_id":"573a1397f29313caabce7ea1","plot":"Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderleys twin sons dies in a bizarre accident, the group ...","title":"Ghost Story","score":3.3177831172943115}
{"_id":"573a1398f29313caabcebf79","plot":"Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...","title":"Ghost Dad","score":3.3177831172943115}

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 텀 ghost가 포함되어 있고 _id 필드에 지정된 ObjectIds가 없습니다. Atlas Search는 지정된 ObjectIds를 가진 문서를 반환하지 않았는데 이는 title 필드에 쿼리 텀 ghost가 포함되어 있음에도 불구하고 쿼리가 이 문서들의 점수를 50% 낮췄기 때문에 이 문서들이 상위 10개 문서에 포함되지 않았기 때문입니다.

1
2

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목(must 절)에 ghost 라는 용어가 포함되고 comedy 장르(mustNot 절)에 속하지 않는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost 용어가 포함되어 있고(must 절)comedy 장르에 속하지만(filter 절), score를 50% 낮추는(boost) 영화를 검색합니다.

결과 수를 10 개 문서로 제한합니다.

  • 결과 문서에서 _id, title, plotgenres 필드만 포함됩니다.

  • 결과에 점수를 표시하는 score라는 필드를 추가합니다.

1import pymongo
2import dns
3
4client = pymongo.MongoClient('<connection-string>')
5result = client['sample_mflix']['movies'].aggregate([
6 {
7 '$search': {
8 'index': 'compound-query-custom-score-tutorial',
9 'compound': {
10 'should': [
11 {
12 'compound': {
13 'must': [
14 {
15 'text': {
16 'query': 'ghost',
17 'path': [ 'plot', 'title' ]
18 }
19 }
20 ],
21 'mustNot': [
22 {
23 'text': {
24 'query': 'Comedy',
25 'path': [ 'genres' ]
26 }
27 }
28 ]
29 }
30 }, {
31 'compound': {
32 'must': [
33 {
34 'text': {
35 'query': 'ghost',
36 'path': [ 'plot', 'title' ]
37 }
38 }
39 ],
40 'filter': [
41 {
42 'text': {
43 'query': 'Comedy',
44 'path': [ 'genres' ]
45 }
46 }
47 ],
48 'score': { 'boost': { 'value': 0.5 } }
49 }
50 }
51 ]
52 }
53 }
54 }, {
55 '$limit': 10
56 }, {
57 '$project': {
58 '_id': 1,
59 'title': 1,
60 'plot': 1,
61 'genres': 1,
62 'score': { '$meta': 'searchScore' }
63 }
64 }
65])
66
67for i in result:
68 print(i)

이 쿼리는 다음 파이프라인 단계를 사용합니다:

  • 줄거리 또는 제목에 ghost라는 텀(must 절)이 포함되어 있지만 지정된 ObjectIds(mustNot 절)가 없는 영화를 검색합니다.

  • 줄거리 또는 제목에 ghost라는 텀이 포함되고(must 절) 지정된 ObjectIds(filter 절)가 있는 영화를 검색하지만 score를 50% 감소시킵니다(boost).

결과 수를 10 개 문서로 제한합니다.

  • 결과에는 문서의 title, plot_id 필드만 포함됩니다.

  • 결과에서 문서의 점수를 보여주는 score라는 이름의 필드를 추가합니다.

1import pymongo
2import dns
3from bson import ObjectId
4
5client = pymongo.MongoClient('<connection-string>')
6result = client['sample_mflix']['movies'].aggregate([
7 {
8 '$search': {
9 'index': 'compound-query-custom-score-tutorial',
10 'compound': {
11 'should': [
12 {
13 'compound': {
14 'must': [
15 {
16 'text': {
17 'query': 'ghost',
18 'path': [ 'plot', 'title' ]
19 }
20 }
21 ],
22 'mustNot': [
23 {
24 'in': {
25 'value': [ ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2') ],
26 'path': '_id'
27 }
28 }
29 ]
30 }
31 }, {
32 'compound': {
33 'must': [
34 {
35 'text': {
36 'query': 'ghost',
37 'path': [ 'plot', 'title' ]
38 }
39 }
40 ],
41 'filter': [
42 {
43 'in': {
44 'value': [ ObjectId('573a13cdf29313caabd83c08'), ObjectId('573a13cef29313caabd873a2') ],
45 'path': '_id'
46 }
47 }
48 ],
49 'score': { 'boost': { 'value': 0.5 } }
50 }
51 }
52 ]
53 }
54 }
55 }, {
56 '$limit': 10
57 }, {
58 '$project': {
59 '_id': 1,
60 'title': 1,
61 'plot': 1,
62 'score': { '$meta': 'searchScore' }
63 }
64 }
65])
66
67for i in result:
68 print(i)
3

연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통해 연결하기를 참조하세요.

4
python compound-bury-results.csproj
{'_id': ObjectId('573a139af29313caabcefcce'), 'plot': 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.', 'genres': ['Family', 'Drama', 'Fantasy'], 'title': 'The Canterville Ghost', 'score': 5.909613132476807}
{'_id': ObjectId('573a13d8f29313caabda5dc1'), 'plot': 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!', 'genres': ['Family', 'Fantasy'], 'title': 'The Little Ghost', 'score': 5.367666244506836}
{'_id': ObjectId('573a13c0f29313caabd6139d'), 'plot': 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.', 'genres': ['Horror', 'Thriller'], 'title': 'Death of a Ghost Hunter', 'score': 4.676314353942871}
{'_id': ObjectId('573a1398f29313caabcebf6f'), 'plot': 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.', 'genres': ['Drama', 'Fantasy', 'Romance'], 'title': 'Ghost', 'score': 3.9638845920562744}
{'_id': ObjectId('573a13cdf29313caabd83c08'), 'plot': "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", 'genres': ['Drama', 'Fantasy', 'Mystery'], 'title': 'Ghost', 'score': 3.9638845920562744}
{'_id': ObjectId('573a13cef29313caabd873a2'), 'plot': "A man tries to solve his lover's murder by communicating with her spirit through the help of a medium.", 'genres': ['Drama', 'Fantasy', 'Mystery'], 'title': 'Ghost', 'score': 3.9638845920562744}
{'_id': ObjectId('573a13c3f29313caabd6a149'), 'plot': 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...', 'genres': ['Horror', 'Thriller'], 'title': 'Coming Soon', 'score': 3.526711940765381}
{'_id': ObjectId('573a1397f29313caabce7ea1'), 'plot': "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", 'genres': ['Drama', 'Horror', 'Thriller'], 'title': 'Ghost Story', 'score': 3.3177831172943115}
{'_id': ObjectId('573a13a4f29313caabd117df'), 'plot': 'Stunt motorcyclist Johnny Blaze gives up his soul to become a hellblazing vigilante, to fight against power hungry Blackheart, the son of the devil himself.', 'genres': ['Action', 'Fantasy', 'Thriller'], 'title': 'Ghost Rider', 'score': 3.3177831172943115}
{'_id': ObjectId('573a13a6f29313caabd185dc'), 'plot': 'A salvage crew that discovers a long-lost 1962 passenger ship floating lifeless in a remote region of the Bering Sea soon notices, as they prepare to tow it back to land, that "strange things" happen...', 'genres': ['Horror', 'Mystery'], 'title': 'Ghost Ship', 'score': 3.3177831172943115}

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 용어 ghost가 포함되어 있고, Comedy 장르에 속하지 않습니다. Atlas Search는 plot 또는 title 필드에 ghost라는 용어가 있는 Comedy 장르의 문서를 반환하지 않았습니다. 이는 쿼리가 해당 문서의 점수를 50% 낮췄기 때문에 상위 10개의 문서에 포함되지 않았기 때문입니다.

python compound-bury-results.csproj
{'_id': ObjectId('573a139af29313caabcefcce'), 'plot': 'Adaption of the famous Oscar Wilde tale about a young American girl that helps a British ghost find rest and forgiveness.', 'title': 'The Canterville Ghost', 'score': 5.909613132476807}
{'_id': ObjectId('573a13d8f29313caabda5dc1'), 'plot': 'The Little Ghost lives in the castle over looking a small town and awakens for precisely one hour after the clock strikes midnight. Follow him on this adventure to see his first sunrise ever!', 'title': 'The Little Ghost', 'score': 5.367666244506836}
{'_id': ObjectId('573a13c0f29313caabd6139d'), 'plot': 'Renowned "ghost hunter", Carter Simms is paid to conduct a paranormal investigation of a supposedly haunted house. Along with a cameraman, a reporter, and a spiritual advocate, she embarks on a three night journey into terror.', 'title': 'Death of a Ghost Hunter', 'score': 4.676314353942871}
{'_id': ObjectId('573a1398f29313caabcebf6f'), 'plot': 'After an accident leaves a young man dead, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.', 'title': 'Ghost', 'score': 3.9638845920562744}
{'_id': ObjectId('573a13c3f29313caabd6a149'), 'plot': 'What kind of scenes in a horror film scares you the most? When a ghost appears totally unexpectedly? When the main character does not see the ghost sneaking up behind him? When at the very ...', 'title': 'Coming Soon', 'score': 3.526711940765381}
{'_id': ObjectId('573a1398f29313caabce912c'), 'plot': 'Three unemployed parapsychology professors set up shop as a unique ghost removal service.', 'title': 'Ghostbusters', 'score': 3.5241782665252686}
{'_id': ObjectId('573a139cf29313caabcf5a48'), 'plot': 'Casper, a ghost, teams up with Wendy, a witch, against an evil warlock.', 'title': 'Casper Meets Wendy', 'score': 3.5241782665252686}
{'_id': ObjectId('573a13bdf29313caabd58274'), 'plot': 'Banku, his mother, Anjali Sharma and father move in to their new house -- the Nath villa, unaware of the fact that the house is inhabited by a ghost. It is learnt the ghost is not too happy...', 'title': 'Bhoothnath', 'score': 3.4605300426483154}
{'_id': ObjectId('573a1397f29313caabce7ea1'), 'plot': "Four successful elderly gentlemen, members of the Chowder Society, share a gruesome, 50-year old secret. When one of Edward Wanderley's twin sons dies in a bizarre accident, the group ...", 'title': 'Ghost Story', 'score': 3.3177831172943115}
{'_id': ObjectId('573a1398f29313caabcebf79'), 'plot': 'Elliot Hopper is a widower with three children, he is currently working on a deal. It seems like his wife illness was very costly and this deal could put them out of the red. However he ...', 'title': 'Ghost Dad', 'score': 3.3177831172943115}

결과에 있는 영화 문서에는 plot 또는 title 필드에 쿼리 텀 ghost가 포함되어 있고 _id 필드에 지정된 ObjectIds가 없습니다. Atlas Search는 지정된 ObjectIds를 가진 문서를 반환하지 않았는데 이는 title 필드에 쿼리 텀 ghost가 포함되어 있음에도 불구하고 쿼리가 이 문서들의 점수를 50% 낮췄기 때문에 이 문서들이 상위 10개 문서에 포함되지 않았기 때문입니다.

Atlas Search를 사용한 복합 쿼리에 대해 자세히 알아보려면 MongoDB University에서 MongoDB 소개 과정의 9단원을 수강하세요. 1.5시간 분량의 이 단원에는 Atlas Search에 대한 개요와 Atlas Search 인덱스 만들기, 복합 연산자를 사용한 $search 쿼리 실행, 패싯을 사용한 결과 그룹화에 대한 강의가 포함되어 있습니다.

돌아가기

Atlas Search 복합 Geo JSON 쿼리를 실행하는 방법