가중치 필드로 Atlas Search 복합 쿼리를 실행하는 방법
이 튜토리얼에서는 검색 필드에 가중치를 추가하여 결과나 결과 카테고리에서 문서를 순위를 높이거나 낮추는 방법을 보여줍니다. 하나 이상의 값을 필드에 할당하여 더 높거나 낮은 점수의 결과를 반환하는 방법을 보여 줍니다.
특히, 자습서에서는 sample_mflix.movies
컬렉션에서 동적 매핑을 사용하여 인덱스를 만드는 방법을 보여줍니다. , constant
, function
, boost
를 사용하여 복합 쿼리를 실행하고 점수를 변경하는 방법을 보여줍니다. 다음 단계에 따르세요.
sample_mflix.movies
collection에 대한 동적 매핑을 사용하여 Atlas Search 인덱스를 설정합니다.다음 Atlas Search 쿼리를 실행하세요.
year
필드를 쿼리하고title
필드의 특정 단어를 사용하여 점수를 변경해서 결과의 문서를 부스트합니다.title
과plot
필드를 쿼리하여genres
필드에서 특정 장르에 따라 점수를 변경하여 해당 장르의 결과를 낮춥니다.
시작하기 전에 Atlas 클러스터가 필수구성 요소에 설명된 요건을 충족하는지 확인하십시오.
Atlas Search 인덱스를 생성하려면 프로젝트에 대한 Project Data Access Admin
이상의 액세스 권한이 있어야 합니다.
동적 매핑으로 Atlas Search 인덱스 만들기
이 섹션에서는 동적 매핑을 사용하여 sample_mflix.movies
컬렉션의 필드를 인덱싱하는 Atlas Search 인덱스를 생성합니다.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
클러스터 페이지가 표시됩니다.
인덱스 구성을 시작하세요.
페이지에서 다음 항목을 선택한 후 Next을 클릭하세요.
Search Type | Atlas Search 인덱스 유형을 선택하세요. |
Index Name and Data Source | 다음 정보를 지정하십시오:
|
Configuration Method | For a guided experience, select Visual Editor. To edit the raw index definition, select JSON Editor. |
인덱스 정의를 지정합니다.
동적 매핑 또는 정적 매핑을 사용하는 Atlas Search 인덱스를 만들 수 있습니다. 동적 및 정적 매핑에 대해 자세히 알아보려면 정적 및 동적 매핑을 참조하세요.
다음 인덱스 정의는 movies
컬렉션에서 지원되는 유형의 필드를 동적으로 인덱싱합니다. Atlas user 인터페이스에서 Atlas Search Visual Editor 또는 Atlas Search JSON Editor을(를) 사용하여 인덱스를 생성할 수 있습니다.
movies
컬렉션에 대한 "default"
인덱스 정의를 검토합니다.
인덱스 정의를 검토합니다.
인덱스 정의는 다음과 비슷해야 합니다:
{ "mappings": { "dynamic": true } } 위의 인덱스 정의는
movies
컬렉션의 각 문서에서 지원되는 유형의 필드를 동적으로 인덱싱합니다.Next를 클릭합니다.
복합 쿼리 실행
복합 연산자를 사용하여 두 개 이상의 연산자를 단일 쿼리로 결합합니다. Atlas Search는 쿼리에 대해 반환하는 모든 문서에 관련성에 따라 가장 높은 점수부터 가장 낮은 점수 순으로 점수를 부여합니다. 쿼리는 결과에서 문서를 부스트(boost)하거나 묻는(bury) 방법을 보여줍니다.
➤ 언어 선택 드롭다운 메뉴를 사용하여 이 섹션에 있는 예시의 언어를 설정합니다.
팁
Atlas Search는 지침과 함께 샘플 복합 쿼리 템플릿을 제공합니다. 자세히 알아보려면 쿼리 지침 템플릿 보기를 참조하세요.
복합 쿼리를 실행하여 결과 개선
이 섹션에서는 Atlas 클러스터에 연결하고 sample_mflix.movies
컬렉션의 title
및 year
필드에 대해 복합 연산자를 사용하여 샘플 쿼리를 실행합니다. 샘플 쿼리는 사용자 지정 점수를 사용하여 snow
용어가 포함된 영화 제목에 대해 Atlas Search에서 반환한 관련성 점수를 변경합니다.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
컬렉션에서 연산자를 사용하여 다음 compound
movies
Atlas Search 쿼리를 실행합니다.
다음 쿼리를 복사하여 Query Editor에 붙여 넣은 다음 Query Editor에서 Search 버튼을 클릭합니다.
다음 예에서는 하위 쿼리와 함께 compound
연산자를 사용하여 title
필드에 snow
이라는 용어가 포함된 2013
~ 2015
년 사이의 영화를 검색합니다.
다음 쿼리입니다:
다음
compound
연산자 절을 사용합니다: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
연산자 절을 사용합니다: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
연산자 절을 사용합니다: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
쿼리 결과를 확장합니다.
Search Tester는 반환하는 문서의 모든 필드를 표시하지 않을 수 있습니다. 쿼리 경로에 지정한 필드를 비롯하여 모든 필드를 보려면 결과에서 문서를 펼칩니다.
mongosh
에서 클러스터에 연결합니다.
터미널 창에서 mongosh
를 열고 클러스터에 연결합니다. 연결에 대한 자세한 지침은 mongosh
를 통한 연결을 참조하세요.
sample_mflix
데이터베이스를 사용합니다.
mongosh
프롬프트에서 다음 명령을 실행합니다.
use sample_mflix
컬렉션에서 연산자를 사용하여 다음 compound
movies
Atlas Search 쿼리를 실행합니다.
다음 예에서는 하위 쿼리와 함께 compound
연산자를 사용하여 title
필드에 snow
이라는 용어가 포함된 2013
~ 2015
년 사이의 영화를 검색합니다.
이 쿼리는 다음 파이프라인 단계를 사용합니다:
$search
를 클릭하여 collection을 쿼리합니다. 쿼리:다음
compound
연산자 절을 사용합니다:title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.
$limit
단계는 출력을10
결과로만 제한합니다.$project
단계로 이동합니다:title
및year
을 제외한 모든 필드를 제외합니다.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
연산자 절을 사용합니다:title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.
$limit
단계는 출력을10
결과로만 제한합니다.$project
단계로 이동합니다:title
및year
을 제외한 모든 필드를 제외합니다.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
연산자 절을 사용합니다:title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.
$limit
단계는 출력을10
결과로만 제한합니다.$project
단계로 이동합니다:title
및year
을 제외한 모든 필드를 제외합니다.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
MongoDB Compass에서 cluster에 연결합니다.
MongoDB Compass를 열고 cluster에 연결합니다. 연결에 대한 자세한 내용은 Compass를 통한 연결을 참조하세요.
constant
옵션을 사용하여 점수를 변경하는 Atlas Search 복합 쿼리를 실행합니다.
이 쿼리는 다음 작업을 수행합니다.
다음
compound
연산자 절을 사용합니다:title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.다음 파이프라인 단계를 사용합니다:
MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.
Aggregations 탭을 클릭합니다.
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
boost
옵션을 사용하여 점수를 변경하는 Atlas Search 복합 쿼리를 실행합니다.
Aggregations 탭을 클릭합니다.
Select...를 클릭한 다음 드롭다운에서 단계를 선택하고 해당 단계에 대한 쿼리를 추가하여 다음 파이프라인 단계를 각각 구성합니다. 단계를 추가하려면 Add Stage을 클릭합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
$search
다음 작업을 수행합니다.다음
compound
연산자 절을 사용하는 쿼리:title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.
$limit 단계를 사용하여 출력 결과를 10개로 제한합니다.
$project 단계에서 다음을 수행합니다:
title
및year
을 제외한 모든 필드를 제외합니다.score
및highlights
이라는 두 필드를 추가합니다.
파이프라인 단계쿼리$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
다음 작업을 수행합니다.
$limit 단계를 사용하여 출력 결과를 10개로 제한합니다.
$project 단계에서 다음을 수행합니다:
title
및year
을 제외한 모든 필드를 제외합니다.score
및highlights
이라는 두 필드를 추가합니다.
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 } ]
function
옵션을 사용하여 점수를 변경하는 Atlas Search 복합 쿼리를 실행합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
$search
다음 작업을 수행하기 위한 단계입니다.다음
compound
연산자 절을 사용하는 쿼리:title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.
$limit 단계를 사용하여 출력 결과를 10개로 제한합니다.
$project 단계에서 다음을 수행합니다:
title
및year
을 제외한 모든 필드를 제외합니다.score
및highlights
이라는 두 필드를 추가합니다.
MongoDB Compass에서 이 쿼리를 실행하려면 다음 안내를 따르세요.
Aggregations 탭을 클릭합니다.
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
constant
옵션을 사용하여 점수를 변경하는 Atlas Search 복합 쿼리를 실행합니다.
compound-constant-example
라는 새 디렉토리를 만들고dotnet new
명령으로 프로젝트를 초기화합니다.mkdir compound-constant-example cd compound-constant-example dotnet new console .NET/C# 드라이버를 프로젝트에 종속성으로 추가합니다.
dotnet add package MongoDB.Driver Program.cs
파일의 내용을 다음 코드로 바꿉니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 복합 절을 사용하여 컬렉션을 쿼리합니다.
title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundConstantExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Filter(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015))) 26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Constant(5))), 27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title), 28 indexName: "compound-query-custom-score-tutorial") 29 .Project<MovieDocument>(Builders<MovieDocument>.Projection 30 .Include(movie => movie.Title) 31 .Include(movie => movie.Year) 32 .Exclude(movie => movie.Id) 33 .MetaSearchScore(movie => movie.Score) 34 .MetaSearchHighlights("highlights")) 35 .Limit(10) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string Title { get; set; } 52 public int Year { get; set; } 53 [ ]54 public List<SearchHighlight> Highlights { get; set; } 55 public double Score { get; set; } 56 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.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
boost
옵션을 사용하여 점수를 변경하는 Atlas Search 복합 쿼리를 실행합니다.
compound-boost-example
라는 새 디렉토리를 만들고dotnet new
명령으로 프로젝트를 초기화합니다.mkdir compound-boost-example cd compound-boost-example dotnet new console .NET/C# 드라이버를 프로젝트에 종속성으로 추가합니다.
dotnet add package MongoDB.Driver Program.cs
파일의 내용을 다음 코드로 바꿉니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
$search
단계를 통해 collection을 쿼리할 수 있습니다. 쿼리:다음
compound
연산자 절을 사용합니다:
title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.
$limit 단계를 사용하여 출력 결과를 10개로 제한합니다.
$project 단계에서 다음을 수행합니다:
title
및year
을 제외한 모든 필드를 제외합니다.score
및highlights
이라는 두 필드를 추가합니다.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundBoostSingleExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015))) 26 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(2))), 27 new SearchHighlightOptions<MovieDocument>(movie => movie.Title), 28 indexName: "compound-query-custom-score-tutorial") 29 .Project<MovieDocument>(Builders<MovieDocument>.Projection 30 .Include(movie => movie.Title) 31 .Include(movie => movie.Year) 32 .Exclude(movie => movie.Id) 33 .MetaSearchScore(movie => movie.Score) 34 .MetaSearchHighlights("highlights")) 35 .Limit(10) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string Title { get; set; } 52 public int Year { get; set; } 53 [ ]54 public List<SearchHighlight> Highlights { get; set; } 55 public double Score { get; set; } 56 } 이 쿼리는
boost
옵션과 함께 다음compound
연산자 절을 사용하여 일부 필드의 우선 순위를 다른 필드보다 더 높습니다.must
절로 가장 우선시하는 장르comedy
를 텍스트 연산자와 함께 지정한 다음title
필드에snow
라는 텀을 추가합니다. boost 옵션은 필드에 가중치를 적용합니다.boost
옵션은 필드에 가중치를 적용합니다.should
2013
~2015
년 사이의 영화를 검색하기 위한 범위 연산자가 있는 절입니다.
참고
boost
옵션은 필드에 다른 가중치를 적용하여 필드의 우선 순위를 지정합니다.1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundBoostMultipleExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 // define and run pipeline 23 var results = moviesCollection.Aggregate() 24 .Search(Builders<MovieDocument>.Search.Compound() 25 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Genres, "comedy", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(9))) 26 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(5))) 27 .Should(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015), score: new SearchScoreDefinitionBuilder<MovieDocument>().Boost(3))), 28 indexName: "compound-query-custom-score-tutorial") 29 .Project<MovieDocument>(Builders<MovieDocument>.Projection 30 .Include(movie => movie.Genres) 31 .Include(movie => movie.Title) 32 .Include(movie => movie.Year) 33 .Exclude(movie => movie.Id) 34 .MetaSearchScore(movie => movie.Score)) 35 .Limit(10) 36 .ToList(); 37 38 // print results 39 foreach (var movie in results) 40 { 41 Console.WriteLine(movie.ToJson()); 42 } 43 } 44 } 45 46 [ ]47 public class MovieDocument 48 { 49 [ ]50 public ObjectId Id { get; set; } 51 public string [] Genres { get; set; } 52 public string Title { get; set; } 53 public int Year { get; set; } 54 public double Score { get; set; } 55 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.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 }
function
옵션을 사용하여 점수를 변경하는 Atlas Search 복합 쿼리를 실행합니다.
compound-function-example
라는 새 디렉토리를 만들고dotnet new
명령으로 프로젝트를 초기화합니다.mkdir compound-function-example cd compound-function-example dotnet new console .NET/C# 드라이버를 프로젝트에 종속성으로 추가합니다.
dotnet add package MongoDB.Driver Program.cs
파일의 내용을 다음 코드로 바꿉니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 파이프라인 단계를 사용하여 컬렉션을 쿼리합니다.
다음 파이프라인 단계를 사용합니다:
title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Attributes; 3 using MongoDB.Bson.Serialization.Conventions; 4 using MongoDB.Driver; 5 using MongoDB.Driver.Search; 6 7 public class CompoundFunctionExample 8 { 9 private const string MongoConnectionString = "<connection-string>"; 10 11 public static void Main(string[] args) 12 { 13 // allow automapping of the camelCase database fields to our MovieDocument 14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; 15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true); 16 17 // connect to your Atlas cluster 18 var mongoClient = new MongoClient(MongoConnectionString); 19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix"); 20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies"); 21 22 var scoreFunction = Builders<MovieDocument>.SearchScore.Function(Builders<MovieDocument>.SearchScoreFunction.Add(Builders<MovieDocument>.SearchScoreFunction.Path(movie => movie.Imdb.Rating, 2), Builders<MovieDocument>.SearchScoreFunction.Relevance())); 23 // define and run pipeline 24 var results = moviesCollection.Aggregate() 25 .Search(Builders<MovieDocument>.Search.Compound() 26 .Must(Builders<MovieDocument>.Search.Range(movie => movie.Year, SearchRangeBuilder.Gte(2013).Lte(2015))) 27 .Should(Builders<MovieDocument>.Search.Text(movie => movie.Title, "snow", score: scoreFunction)), 28 new SearchHighlightOptions<MovieDocument>(movie => movie.Title), 29 indexName: "compound-query-custom-score-tutorial") 30 .Project<MovieDocument>(Builders<MovieDocument>.Projection 31 .Include(movie => movie.Genres) 32 .Include(movie => movie.Title) 33 .Include(movie => movie.Year) 34 .Exclude(movie => movie.Id) 35 .MetaSearchScore(movie => movie.Score) 36 .MetaSearchHighlights("highlights")) 37 .Limit(10) 38 .ToList(); 39 40 // print results 41 foreach (var movie in results) 42 { 43 Console.WriteLine(movie.ToJson()); 44 } 45 } 46 } 47 48 [ ]49 public class MovieDocument 50 { 51 [ ]52 public ObjectId Id { get; set; } 53 public string [] Genres { get; set; } 54 public IMDB Imdb { get; set; } 55 public string Title { get; set; } 56 public int Year { get; set; } 57 [ ]58 public List<SearchHighlight> Highlights { get; set; } 59 public double Score { get; set; } 60 } 61 62 [ ]63 public class IMDB 64 { 65 public double Rating { get; set; } 66 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.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
constant
옵션을 사용하여 점수를 변경하는 Atlas Search 복합 쿼리를 실행합니다.
compound-constant-query.go
이라는 파일을 만듭니다.코드 예시를 복사하여
compound-constant-query.go
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다:
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
다음 복합 절을 사용하여 컬렉션을 쿼리합니다.
title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.다음 파이프라인 단계를 사용합니다:
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 func main() { 14 // connect to your Atlas cluster 15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>")) 16 if err != nil { 17 panic(err) 18 } 19 defer client.Disconnect(context.TODO()) 20 21 // set namespace 22 collection := client.Database("sample_mflix").Collection("movies") 23 24 // define pipeline stages 25 searchStage := bson.D{{"$search", bson.M{ 26 "index": "compound-query-custom-score-tutorial", 27 "compound": bson.M{ 28 "filter": bson.M{ 29 "range": bson.M{ 30 "path": "year", "gte": 2013, "lte": 2015, 31 }, 32 }, 33 "should": bson.D{ 34 {"text", bson.M{ 35 "path": "title", "query": "snow", "score": bson.M{ 36 "constant": bson.D{{"value", 5}}, 37 }}}}, 38 }, 39 "highlight": bson.D{{"path", "title"}}, 40 }}} 41 limitStage := bson.D{{"$limit", 10}} 42 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}, {"highlights", bson.D{{"$meta", "searchHighlights"}}}}}} 43 44 // specify the amount of time the operation can run on the server 45 opts := options.Aggregate().SetMaxTime(5 * time.Second) 46 47 // run pipeline 48 cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 49 if err != nil { 50 panic(err) 51 } 52 53 // print results 54 var results []bson.D 55 if err = cursor.All(context.TODO(), &results); err != nil { 56 panic(err) 57 } 58 for _, result := range results { 59 fmt.Println(result) 60 } 61 } 샘플을 실행하기 전에
<connection-string>
을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.다음 명령을 실행하여 컬렉션을 쿼리합니다.
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
boost
옵션을 사용하여 점수를 변경하는 Atlas Search 복합 쿼리를 실행합니다.
compound-boost-query.go
이라는 파일을 만듭니다.코드 예시를 복사하여
compound-boost-query.go
파일에 붙여넣습니다.이 코드 예시에서는 다음 작업을 수행합니다.
mongodb
패키지 및 종속성을 가져옵니다.Atlas 클러스터에 대한 연결을 설정합니다.
커서 위를 반복하여 쿼리와 일치하는 문서를 인쇄합니다.
쿼리는 다음 파이프라인 단계를 사용합니다:
$search
단계를 통해 collection을 쿼리할 수 있습니다. 쿼리:다음
compound
절을 사용하여 컬렉션을 쿼리합니다.title
필드에서 쿼리와 일치하는 텍스트 스니펫을 반환하는강조 표시 옵션을 지정합니다. 스니펫에는type: 'hit'
으로 지정된 일치하는 텍스트와type: 'text'
로 지정된 인접 텍스트가 포함되어 있습니다.
$limit 단계를 사용하여 출력 결과를 10개로 제한합니다.
$project 단계에서 다음을 수행합니다:
title
및year
을 제외한 모든 필드를 제외합니다.score
및highlights
이라는 두 필드를 추가합니다.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "go.mongodb.org/mongo-driver/bson" 9 "go.mongodb.org/mongo-driver/mongo" 10 "go.mongodb.org/mongo-driver/mongo/options" 11 ) 12 13 // define structure of movies collection 14 type MovieCollection struct { 15 title string `bson:"Title,omitempty"` 16 } 17 18 func main() { 19 var err error 20 // connect to the Atlas cluster 21 ctx := context.Background() 22 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>")) 23 if err != nil { 24 panic(err) 25 } 26 defer client.Disconnect(ctx) 27 // set namespace 28 collection := client.Database("sample_mflix").Collection("movies") 29 // define pipeline 30 searchStage := bson.D{{"$search", bson.M{ 31 "index": "compound-query-custom-score-tutorial", 32 "compound": bson.M{ 33 "must": bson.M{ 34 "range": bson.M{ 35 "path": "year", "gte": 2013, "lte": 2015, 36 }, 37 }, 38 "should": bson.D{ 39 {"text", bson.M{ 40 "path": "title", "query": "snow", "score": bson.M{ 41 "boost": bson.D{{"value", 2}}, 42 }, 43 }}, 44 }, 45 }, 46 }}} 47 limitStage := bson.D{{"$limit", 10}} 48 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"year", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}} 49 // specify the amount of time the operation can run on the server 50 opts := options.Aggregate().SetMaxTime(5 * time.Second) 51 // run pipeline 52 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts) 53 if err !=