Docs Menu
Docs Home
/
Atlas
/ /

Atlas Search에서 동의어를 사용하는 방법

이 튜토리얼에서는 단어를 동의어로 구성하는 컬렉션을 추가하고, sample_mflix.movies 컬렉션에 동의어 매핑을 정의하는 인덱스를 만들고, 동의어로 구성된 단어를 사용하여 title 필드에 대해 Atlas Search 쿼리를 실행하는 방법에 대해 설명합니다.

이 튜토리얼은 다음 단계를 안내합니다.

  1. sample_mflix 데이터베이스에 하나 이상의 샘플 동의어 컬렉션을 로드합니다.

  2. sample_mflix.movies 컬렉션에 대한 하나 이상의 동의어 매핑을 사용하여 Atlas Search 인덱스를 만듭니다.

  3. 동의어 소스 컬렉션에서 동의어로 구성된 단어에 대해 sample_mflix.movies 컬렉션의 title 필드에 대해 Atlas Search 쿼리를 실행합니다.

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

참고

이 튜토리얼에서 여러 동의어 매핑을 생성하고 고급 샘플 쿼리를 실행하려면 M10 이상의 클러스터가 필요합니다.

동의어 소스 컬렉션의 각 문서는 하나 이상의 단어가 해당 단어가 가진 하나 이상의 동의어에 어떻게 매핑되는지 설명합니다. 동의어 소스 컬렉션 문서의 필드 및 단어 매핑 유형에 대해 자세히 알아보려면 동의어 소스 컬렉션 문서 형식을 참조하세요.

시작하려면 동의어 소스 컬렉션을 만든 다음 동의어 소스 컬렉션을 사용하려는 데이터베이스에 컬렉션을 추가합니다. 이 섹션에서는 데이터베이스에서 하나 또는 두 개의 샘플 동의어 sample_mflix 소스 컬렉션을 만든 다음, 동일한 데이터베이스 내의 movies 컬렉션에서 컬렉션의 인덱스와 함께 동의어 소스 컬렉션을 사용합니다.

1

경고

탐색 기능 개선 작업 진행 중

현재 새롭고 향상된 탐색 환경을 출시하고 있습니다. 다음 단계가 Atlas UI 의 보기와 일치하지 않으면 미리 보기 문서를 참조하세요.

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

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

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

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

2

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

데이터 탐색기 가 표시됩니다.

3

무료 계층 클러스터 또는 Flex 클러스터 를 실행 하는 경우 운송 동의어 탭 의 단계에 따라 인덱스 에 단일 동의어 매핑 정의에 대한 M10 컬렉션 만듭니다. 이상의 클러스터 가 있고 인덱스 에 여러 동의어 매핑을 생성하려는 경우 두 탭의 단계에 따라 운송 동의어의복 동의어 컬렉션을 모두 생성합니다.

  1. sample_mflix 데이터베이스를 확장하고 아이콘을 클릭하여 Create Collection 모달을 엽니다.

  2. Collection name 필드에 transport_synonyms을 입력합니다.

  3. Create을(를) 클릭하여 sample_mflix 데이터베이스에 컬렉션을 생성합니다.

  1. sample_mflix 데이터베이스를 확장하고 아이콘을 클릭하여 Create Collection 모달을 엽니다.

  2. Collection name 필드에 attire_synonyms을 입력합니다.

  3. Create을(를) 클릭하여 sample_mflix 데이터베이스에 컬렉션을 생성합니다.

4

탭의 단계에 따라 각 컬렉션에 데이터를 로드합니다.

  1. Collection이 선택되지 않은 경우 transport_synonyms collection을 선택합니다.

  2. 컬렉션에 추가할 각 샘플 문서에 대해 Insert Document 를 클릭합니다.

  3. JSON 보기({})를 클릭하여 기본 문서를 바꿉니다.

  4. 다음 샘플 문서를 한 번에 하나씩 복사하여 붙여넣고 Insert을 클릭하여 컬렉션에 문서를 한 번에 하나씩 추가합니다.

    {
    "mappingType": "equivalent",
    "synonyms": ["car", "vehicle", "automobile"]
    }
    {
    "mappingType": "explicit",
    "input": ["boat"],
    "synonyms": ["boat", "vessel", "sail"]
    }
  1. Collection이 선택되지 않은 경우 attire_synonyms collection을 선택합니다.

  2. 컬렉션에 추가할 각 샘플 문서에 대해 Insert Document 를 클릭합니다.

  3. 기본값 문서를 바꾸려면 JSON 보기({})를 클릭하세요.

  4. 다음 샘플 문서를 한 번에 하나씩 복사하여 붙여넣고 Insert을 클릭하여 컬렉션에 문서를 한 번에 하나씩 추가합니다.

    {
    "mappingType": "equivalent",
    "synonyms": ["dress", "apparel", "attire"]
    }
    {
    "mappingType": "explicit",
    "input": ["hat"],
    "synonyms": ["hat", "fedora", "headgear"]
    }

컬렉션 인덱스의 동의어 매핑은 동의어 소스 컬렉션과 컬렉션에 사용할 분석기를 지정합니다.

이 섹션에서는 sample_mflix.movies 컬렉션에 대한 하나 이상의 동의어 매핑을 정의하는 Atlas Search 인덱스를 만듭니다. 인덱스의 매핑 정의는 sample_mflix 데이터베이스에서 만든 동의어 원본 컬렉션을 참고합니다.

1

경고

탐색 기능 개선 작업 진행 중

현재 새롭게 개선된 탐색 환경을 배포하고 있습니다. 다음 단계가 Atlas UI에서 보이는 것과 일치하지 않으면 미리 보기 문서를 참조하세요.

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

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

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

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

2

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

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

    클러스터가 없는 경우 Create cluster를 클릭하여 클러스터를 생성합니다. 자세히 알아보려면 클러스터 생성을 참조하세요.

  2. 프로젝트에 여러 클러스터가 있는 경우 Select cluster 드롭다운에서 사용할 클러스터를 선택한 후 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: synonyms-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.

참고

Atlas Search 인덱스의 기본값 이름은 default입니다. 이 이름을 유지하면 해당 연산자에서 다른 index 옵션을 지정하지 않는 모든 Atlas Search 쿼리에 대한 기본 검색 인덱스가 됩니다. 여러 인덱스를 생성하는 경우 인덱스 전반에 걸쳐 일관되고 설명적인 명명 규칙을 유지하는 것이 좋습니다.

5

간단한 예시 쿼리만 실행하려면 아래 단일 동의어 매핑 탭의 인덱스 정의를 사용하세요. 클러스터가 M10 이상이고 예시 동의어 소스 컬렉션을 모두 로드한 경우 아래의 다중 동의어 매핑 탭에서 다중 동의어 매핑을 지정하는 인덱스 정의를 사용하여 단순 예시 쿼리와 고급 예시 쿼리를 모두 실행할 수 있습니다.

다음 인덱스 정의는 다음과 같습니다.

  • 언어 분석기 lucene.english을(를) title 필드 인덱싱 및 쿼리 모두에 대한 기본 분석기로 사용합니다.

  • 이 동의어 매핑의 이름으로 transportSynonyms인 이름입니다.

  • transportSynonyms 매핑을 사용하여 쿼리의 동의어를 찾기 위한 소스 동의어 컬렉션인 transport_synonyms 컬렉션입니다. transportSynonyms은(는) lucene.english 분석기로 인덱싱된 모든 필드(이 예에서는 title 필드 포함)에 대한 텍스트 쿼리에 사용될 수 있습니다.

  1. Refine Your Index를 클릭합니다.

  2. Field Mappings 섹션에서 Add Field을(를) 클릭합니다.

  3. Customized Configuration를 클릭합니다.

  4. Add Field Mapping 창에서 다음 필드를 구성하고 그 후에 Add을(를) 클릭합니다.

    UI 필드 이름
    구성

    Field Name

    title을(를) 입력합니다.

    Enable Dynamic Mapping

    Off(으)로 전환합니다.

    Data Type Configuration

    1. Add Data Type를 클릭합니다.

    2. String0}을 선택합니다.

    3. Index AnalyzerSearch Analyzer의 경우 드롭다운을 클릭하여 lucene.language 분석기 드롭다운에서 lucene.english을(를) 선택합니다.

    위에 나열되지 않은 다른 모든 필드의 경우 기본값을 그대로 사용합니다.

  5. Synonym Mappings 섹션에서 Add Synonym Mapping을(를) 클릭합니다.

  6. Add Synonym Mapping 창에서 다음 필드를 구성하고 그 후에 Add을(를) 클릭합니다.

    UI 필드 이름
    구성

    Synonym Mapping Name

    transportSynonyms을(를) 입력합니다.

    Synonym Source Collection

    transport_synonyms0}을 선택합니다.

    Analyzer

    lucene.english0}을 선택합니다.

  7. Save Changes를 클릭합니다.

  1. 기본 인덱스 정의를 다음 인덱스 정의로 바꾸세요.

    {
    "mappings": {
    "dynamic": false,
    "fields": {
    "title": {
    "analyzer": "lucene.english",
    "type": "string"
    }
    }
    },
    "synonyms": [
    {
    "analyzer": "lucene.english",
    "name": "transportSynonyms",
    "source": {
    "collection": "transport_synonyms"
    }
    }
    ]
    }
  2. Next를 클릭합니다.

다음 인덱스 정의는 다음과 같습니다.

  • lucene.english 언어 분석기title 필드 인덱싱 및 쿼리 모두에 대한 기본 분석기로 사용합니다.

  • 동의어 매핑의 이름으로 transportSynonymsattireSynonyms라는 이름이 사용됩니다.

    • transport_synonyms 컬렉션을 transportSynonyms 매핑을 사용한 쿼리의 동의어를 찾기 위한 소스 동의어 컬렉션으로 사용합니다. transportSynonymslucene.english 분석기로 인덱싱된 모든 필드(이 튜토리얼의 샘플 쿼리에 있는 title 필드 포함)에 대한 텍스트 쿼리에 사용할 수 있습니다.

    • attire_synonyms 컬렉션을 attireSynonyms 매핑을 사용한 쿼리의 동의어를 찾기 위한 소스 동의어 컬렉션으로 사용합니다. attireSynonymslucene.english 분석기로 인덱싱된 모든 필드(이 튜토리얼의 샘플 쿼리에 있는 title 필드 포함)에 대한 텍스트 쿼리에 사용할 수 있습니다.

  1. Refine Your Index를 클릭합니다.

  2. Field Mappings 섹션에서 Add Field을(를) 클릭합니다.

  3. Add Field Mapping 창 에서 다음 필드를 구성한 다음 Add를 클릭합니다.

    UI 필드 이름
    구성

    Field Name

    title을(를) 입력합니다.

    Enable Dynamic Mapping

    Off(으)로 전환합니다.

    Data Type Configuration

    1. String0}을 선택합니다.

    2. Index AnalyzerSearch Analyzer의 경우 드롭다운을 클릭하여 lucene.language 분석기 드롭다운에서 lucene.english을(를) 선택합니다.

    위에 나열되지 않은 다른 모든 필드의 경우 기본값을 그대로 사용합니다.

  4. Synonym Mappings 섹션에서 Add Synonym Mapping을(를) 클릭합니다.

  5. Add Synonym Mapping 창 에서 다음 필드를 구성한 다음 Add를 클릭합니다.

    UI 필드 이름
    구성

    Synonym Mapping Name

    transportSynonyms을(를) 입력합니다.

    Synonym Source Collection

    transport_synonyms0}을 선택합니다.

    Analyzer

    lucene.english0}을 선택합니다.

  6. Synonym Mappings 섹션에서 Add Synonym Mapping을 다시 클릭하세요.

  7. Add Synonym Mapping 창에서 다음 필드를 구성하고 그 후에 Add을(를) 클릭합니다.

    UI 필드 이름
    구성

    Synonym Mapping Name

    attireSynonyms을(를) 입력합니다.

    Synonym Source Collection

    attire_synonyms0}을 선택합니다.

    Analyzer

    lucene.english0}을 선택합니다.

  8. Save Changes를 클릭합니다.

  1. 기본 인덱스 정의를 다음 인덱스 정의로 바꾸세요.

    {
    "mappings": {
    "dynamic": false,
    "fields": {
    "title": {
    "analyzer": "lucene.english",
    "type": "string"
    }
    }
    },
    "synonyms": [
    {
    "analyzer": "lucene.english",
    "name": "transportSynonyms",
    "source": {
    "collection": "transport_synonyms"
    }
    },
    {
    "analyzer": "lucene.english",
    "name": "attireSynonyms",
    "source": {
    "collection": "attire_synonyms"
    }
    }
    ]
    }
  2. Next를 클릭합니다.

6
7

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

8

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


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


동의어는 텍스트 연산자를 사용하는 쿼리에서만 사용할 수 있습니다. 이 섹션에서는 Atlas 클러스터에 연결하고 sample_mflix.movies 컬렉션 title 필드에 대해 text 연산자를 사용하여 샘플 쿼리를 실행합니다. 샘플 쿼리에서는 동의어 소스 컬렉션에서 다양한 매핑 유형의 동의어로 구성된 단어를 사용합니다. 소스 컬렉션은 쿼리가 사용하는 동의어 매핑에서 참조됩니다.

1

경고

탐색 기능 개선 작업 진행 중

현재 새롭게 개선된 탐색 환경을 배포하고 있습니다. 다음 단계가 Atlas UI에서 보이는 것과 일치하지 않으면 미리 보기 문서를 참조하세요.

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

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

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

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

2

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

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

    클러스터가 없는 경우 Create cluster를 클릭하여 클러스터를 생성합니다. 자세히 알아보려면 클러스터 생성을 참조하세요.

  2. 프로젝트에 여러 클러스터가 있는 경우 Select cluster 드롭다운에서 사용할 클러스터를 선택한 후 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

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

5

단일 동의어 매핑 정의로 인덱스를 생성한 경우 다음 간단한 예시 탭에서 쿼리를 실행합니다. 인덱스에 여러 동의어 매핑을 정의한 경우 다음 탭 모두에서 쿼리를 실행할 수 있습니다.

다음 쿼리는 다음과 같습니다.

  • title 필드를 제외한 모든 필드 제외

  • score(이)라는 필드를 추가합니다.

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

다음 쿼리는 title 필드에서 automobile을(를) 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 구성한 automobile의 동의어를 검색합니다.

[
{
$search: {
index: "synonyms-tutorial",
text: {
path: "title",
query: "automobile",
synonyms: "transportSynonyms"
}
}
}
]
SCORE: 4.197734832763672 _id: “573a13a9f29313caabd1f18a”
fullplot: "While traveling to California for the dispute of the final race of the…"
imdb: Object
year: 2006
...
title: "Cars"
SCORE: 3.8511905670166016 _id: “573a1398f29313caabcea94c”
plot: "A man must struggle to travel home for Thanksgiving with an obnoxious …"
genres: Array
runtime: 93
...
title: "Planes, Trains, and Automobiles"
SCORE: 3.39473032951355 _id: “573a1397f29313caabce5fb0”
plot: "Car Wash is about a close-knit group of employees who one day have all…"
genres: Array
runtime: 97
...
title: "Car Wash"
SCORE: 3.39473032951355 _id: “573a1397f29313caabce7bd2”
plot: "When the owner of a struggling used car lot is killed, it's up to the …"
genres: Array
runtime: 113
...
title: "Used Cars"
SCORE: 3.39473032951355 _id: “573a13a6f29313caabd18bfe”
fullplot: "Gifted 18-year-old Meg has been abandoned by her father and neglected …"
imdb: Object
year: 2002
...
title: "Blue Car"
SCORE: 3.39473032951355 _id: “573a13c1f29313caabd64e3d”
fullplot: "After Mater gets his best friend, star race car Lightning McQueen, a s…"
imdb: Object
year: 2011
...
title: "Cars 2"
SCORE: 3.39473032951355 _id: “573a13eaf29313caabdce62c”
plot: "A rebellious teenager navigates his way through the juvenile court sys…"
genres: Array
runtime: 94
...
title: "Stealing Cars"
SCORE: 3.39473032951355 _id: “573a13f1f29313caabddc93f”
plot: "A small town sheriff sets out to find the two kids who have taken his …"
genres: Array
runtime: 86
...
title: "Cop Car"
SCORE: 2.8496146202087402 _id: “573a1396f29313caabce5480”
plot: "The small town of Paris, Australia deliberately causes car accidents, …"
genres: Array
runtime: 91
...
title: "The Cars That Eat People"
SCORE: 2.8496146202087402 _id: “573a139df29313caabcf9636”
plot: "Military doctor General Klenski is arrested in Stalin's Russia in 1953…"
genres: Array
runtime: 137
...
title: "Khrustalyov, My Car!"

쿼리 용어가 automobile인 경우에도 automobile을(를) 이름이 컬렉션에 대한 인덱스에 지정된 sample_synonyms인 동의어 소스 컬렉션에서 car, vehicle, automobile의 동의어로 구성했기 때문에 title 필드에 carautomobile이(가) 포함된 영화가 Atlas Search 결과에 포함됩니다. Atlas Search는 carvehicle 단어를 검색할 때 동일한 결과를 반환합니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle 중 하나로 바꾸고 쿼리를 실행합니다.

쿼리는 title 필드에서 boat를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 구성한 boat의 동의어를 검색합니다.

[
{
$search: {
index: "synonyms-tutorial",
text: {
path: "title",
query: "boat",
synonyms: "transportSynonyms"
}
}
}
]
SCORE: 5.373150825500488 _id: “573a13e9f29313caabdcd013”
plot: "A fearless sea captain sails a ship through loopholes in international…"
genres: Array
runtime: 90
...
title: "Vessel"
SCORE: 4.589139938354492 _id: “573a13e8f29313caabdc9e72”
countries: Array
genres: Array
runtime: 7
...
title: "Boats"
SCORE: 4.3452959060668945 _id: “573a1398f29313caabce90b6”
plot: "In 1914, a luxury ship leaves Italy in order to scatter the ashes of a…"
genres: Array
runtime: 128
...
title: "And the Ship Sails On"
SCORE: 4.3452959060668945 _id: “573a139cf29313caabcf7c75”
plot: "A young Pennsylvania man moves to Los Angeles to begin work for an amb…"
genres: Array
runtime: 90
...
title: "Broken Vessels"
SCORE: 4.3452959060668945 _id: “573a13f0f29313caabdda2dd”
plot: "A young man struggling with the death of his parents meets an extrover…"
genres: Array
runtime: 80
...
title: "Sailing to Paradise"
SCORE: 3.711261749267578 _id: “573a1397f29313caabce8796”
plot: "A Japanese photojournalist revisits Vietnam after the Liberation and l…"
genres: Array
runtime: 109
...
title: "Boat People"
SCORE: 3.711261749267578 _id: “573a13a6f29313caabd17a98”
plot: "Two straight men mistakenly end up on a "gays only" cruise."
genres: Array
runtime: 94
...
title: "Boat Trip"
SCORE: 3.1153182983398438 _id: “573a1394f29313caabce036c”
plot: "Three London gentlemen take vacation rowing down the Thames, encounter…"
genres: Array
runtime: 84
...
title: "Three Men in a Boat"
SCORE: 3.1153182983398438 _id: “573a1395f29313caabce2c28”
plot: "After a series of misunderstandings, the head of an aerospace research…"
genres: Array
runtime: 110
...
title: "The Glass Bottom Boat"
SCORE: 3.1153182983398438 _id: “573a13c2f29313caabd68772”
fullplot: "Jack is a shy and awkward man who drives a limo and lives an unassumin…"
imdb: Object
runtime: 2010
...
title: "Jack Goes Boating"

title 필드에 boat, vessel, sail이 있는 영화가 Atlas Search 결과에 포함됩니다. 이는 컬렉션의 인덱스에 지정된 sample_synonyms라는 동의어 소스 컬렉션에서 boat, vessel, sailboat 동의어로 구성했기 때문입니다.

Atlas Search는 결과에서 vessel 단어를 검색한 경우에만 다음 문서를 반환합니다.

{ "title" : "Vessel", "score" : 5.373150825500488 }
{ "title" : "Broken Vessels", "score" : 4.3452959060668945 }

Atlas Search는 title 필드에 boat 또는 sail이 포함된 문서를 결과에 포함하지 않습니다. 이는 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 vessel로 바꾸고 쿼리를 다시 실행합니다.

마찬가지로, Atlas Search는 sail 검색어에 대한 검색 결과에서만 다음 문서를 반환합니다.

{ "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
{ "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

Atlas Search는 결과에서 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 이는 우리가 synonyms 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 설정하지 않았기 때문입니다. 이 예시를 테스트하려면 위의 쿼리에서 query 필드의 값을 sail로 바꾼 후 쿼리를 다시 실행해 보세요.

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

쿼리는 title 필드에서 automobile를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 구성한 automobile의 동의어를 검색합니다. 또한 쿼리는 title 필드에서 attire를 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 구성한 attire의 동의어를 검색합니다.

[
{
$search: {
"index": "synonyms-tutorial",
"compound": {
"should": [{
"text": {
"path": "title",
"query": "automobile",
"synonyms": "transportSynonyms"
}
},
{
"text": {
"path": "title",
"query": "attire",
"synonyms": "attireSynonyms"
}
}]
}
}
}
]
SCORE: 4.812004089355469 _id: “573a139af29313caabcf003f”
plot: "The Dress is a tale filled with sex, violence, comedy and drama as it …"
genres: Array
runtime: 103
...
title: "The Dress"
SCORE: 4.197734832763672 _id: “573a13a9f29313caabd1f18a”
fullplot: "While traveling to California for the dispute of the final race of the…"
imdb: Object
year: 2006
...
title: "Cars"
SCORE: 3.891493320465088 _id: “573a1397f29313caabce77cd”
plot: "A mysterious blonde woman kills one of a psychiatrist's patients, and …"
genres: Array
runtime: 105
...
title: "Dressed to Kill"
SCORE: 3.891493320465088 _id: “573a13bcf29313caabd57e07”
fullplot: "Two things about Jane: she never says no to her friends (she's been a …"
imdb Object
year: 2008
...
title: "27 Dresses"
SCORE: 3.8511905670166016 _id: “573a1398f29313caabcea94c”
plot: "A man must struggle to travel home for Thanksgiving with an obnoxious …"
genres: Array
runtime: 93
...
title: "Planes, Trains, and Automobiles"
SCORE: 3.39473032951355 _id: “573a1397f29313caabce5fb0”
plot: "Car Wash is about a close-knit group of employees who one day have all…"
genres: Array
runtime: 97
...
title: "Car Wash"
SCORE: 3.39473032951355 _id: “573a1397f29313caabce7bd2”
plot: "When the owner of a struggling used car lot is killed, it's up to the …"
genres: Array
runtime: 113
...
title: "Used Cars"
SCORE: 3.39473032951355 _id: “573a13a6f29313caabd18bfe”
fullplot: "Gifted 18-year-old Meg has been abandoned by her father and neglected …"
imdb: Object
year: 2002
...
title: "Blue Car"
SCORE: 3.39473032951355 _id: “573a13c1f29313caabd64e3d”
fullplot: "After Mater gets his best friend, star race car Lightning McQueen, a s…"
imdb: Object
year: 2011
...
title: "Cars 2"
SCORE: 3.39473032951355 _id: “573a13eaf29313caabdce62c”
plot: "A rebellious teenager navigates his way through the juvenile court sys…"
genres: Array
runtime: 94
...
title: "Stealing Cars"

Atlas Search 결과에는 두 검색어에 대한 문서가 모두 포함되어 있습니다. 결과에는 쿼리 용어 automobile에 대하여 title 필드에 car이(가) 포함된 영화가 포함됩니다. 이는 transport_synonyms 동의어 소스 컬렉션에서 automobile을(를) car, vehicleautomobile의 동의어로 구성했기 때문입니다. 결과에는 쿼리 용어 attire에 대하여 제목 필드에 dress이(가) 포함된 영화도 포함됩니다. 이는 attire_synonyms 동의어 소스 컬렉션에서 attire을(를) dress, apparelattire의 동의어로 구성했기 때문입니다.

Atlas Search는 transport_synonyms 소스 컬렉션에서 car 또는 vehicle을(를) 검색하고 attire_synonyms 소스 컬렉션에서 dress 또는 apparel을(를) 검색할 때 동일한 결과를 반환합니다. 이 예시를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle(으)로 바꾸고 위 쿼리의 query 필드 값을 dress 또는 apparel(으)로 바꾼 다음 쿼리를 다시 실행합니다.

쿼리는 title 필드에서 boat를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 구성한 boat의 동의어를 검색합니다. 또한 쿼리는 title 필드에서 hat를 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 구성한 hat의 동의어를 검색합니다.

[
{
$search: {
index: "synonyms-tutorial",
compound: {
should: [{
text: {
path: "title",
query: "boat",
synonyms: "transportSynonyms"
}
},
{
text: {
path: "title",
query: "hat",
synonyms: "attireSynonyms"
}
}]
}
}
}
]
SCORE: 5.673145294189453 _id: “573a1397f29313caabce6bed”
plot: "Down-on-his-luck Hollywood producer Barry 'Dutch' Detweiler attempts t…"
genres: Array
runtime: 114
...
title: "Fedora"
SCORE: 5.373150825500488 _id: “573a13e9f29313caabdcd013”
plot: "A fearless sea captain sails a ship through loopholes in international…"
genres: Array
runtime: 90
...
title: "Vessel"
SCORE: 4.589139938354492 _id: “573a13e8f29313caabdc9e72”
countries: Array
genres: Array
runtime: 7
...
title: "Boats"
SCORE: 4.3452959060668945 _id: “573a1398f29313caabce90b6”
plot: "In 1914, a luxury ship leaves Italy in order to scatter the ashes of a…"
genres: Array
runtime: 128
...
title: "And the Ship Sails On"
SCORE: 4.3452959060668945 _id: “573a139cf29313caabcf7c75”
plot: "A young Pennsylvania man moves to Los Angeles to begin work for an amb…"
genres: Array
runtime: 90
...
title: "Broken Vessels"
SCORE: 4.3452959060668945 _id: “573a13f0f29313caabdda2dd”
plot: "A young man struggling with the death of his parents meets an extrover…"
genres: Array
runtime: 80
...
title: "Sailing to Paradise"
SCORE: 4.066137313842773 _id: “573a1392f29313caabcdaae8”
plot: "An American dancer comes to Britain and falls for a model whom he init…"
genres: Array
runtime: 101
...
title: "Top Hat"
SCORE: 4.066137313842773 _id: “573a1394f29313caabce05e8”
plot: "A Korean War veteran's morphine addiction wreaks havoc upon his family…"
genres: Array
runtime: 109
...
title: "A Hatful of Rain"
SCORE: 3.711261749267578 _id: “573a1397f29313caabce8796”
plot: "A Japanese photojournalist revisits Vietnam after the Liberation and l…"
genres: Array
runtime: 109
...
title: "Boat People"
SCORE: 3.711261749267578 _id: “573a13a6f29313caabd17a98”
plot: "Two straight men mistakenly end up on a "gays only" cruise."
genres: Array
runtime: 94
...
title: "Boat Trip"

Atlas Search 결과에 두 검색어에 대한 문서가 모두 포함됩니다. 검색어 boat에 대해 title 필드에 vessel, boat, sail이 있는 영화가 결과에 포함됩니다. 이는 transport_synonyms라는 동의어 소스 컬렉션에서 boatboat, vessel, sail의 동의어로 구성했기 때문입니다.

Atlas Search는 vessel 용어 검색 결과에서 title 필드에 boat 또는 sail이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 sail 용어 검색 결과의 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 vessel 또는 sail로 바꾸고 쿼리를 다시 실행하세요.

검색어 hat에 대하여 제목 필드에 fedorahat이 있는 동영상도 결과에 포함됩니다. attire_synonyms라는 동의어 소스 컬렉션에서 hathat, fedora, headgear 동의어로 구성했기 때문입니다.

Atlas Search는 headgear 용어 검색 결과에서 title 필드에 hat 또는 fedora이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 headgearhat 또는 fedora의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 fedora 용어 검색 결과의 title 필드에 hat 또는 headgear이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 fedorahat 또는 headgear의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 fedora 또는 headgear로 바꾸고 쿼리를 다시 실행하세요.

6

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

1

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

2

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

use sample_mflix
3

단일 동의어 매핑 정의로 인덱스를 생성한 경우 아래의 간단한 예시 탭에서 쿼리를 실행하세요. 인덱스에 여러 동의어 매핑을 정의한 경우 아래 탭 모두에서 쿼리를 실행할 수 있습니다.

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

  • $search 컬렉션을 검색하는 단계입니다.

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

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

    • title 필드를 제외한 모든 필드 제외

    • score(이)라는 필드를 추가합니다.

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

쿼리는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms라는 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색합니다.

db.movies.aggregate([
{
$search: {
"index": "synonyms-tutorial",
"text": {
"path": "title",
"query": "automobile",
"synonyms": "transportSynonyms"
}
}
},
{
$limit: 10
},
{
$project: {
"_id": 0,
"title": 1,
"score": { $meta: "searchScore" }
}
}
])
{ "title" : "Cars", "score" : 4.197734832763672 }
{ "title" : "Planes, Trains & Automobiles", "score" : 3.8511905670166016 }
{ "title" : "Car Wash", "score" : 3.39473032951355 }
{ "title" : "Used Cars", "score" : 3.39473032951355 }
{ "title" : "Blue Car", "score" : 3.39473032951355 }
{ "title" : "Cars 2", "score" : 3.39473032951355 }
{ "title" : "Stealing Cars", "score" : 3.39473032951355 }
{ "title" : "Cop Car", "score" : 3.39473032951355 }
{ "title" : "The Cars That Eat People", "score" : 2.8496146202087402 }
{ "title" : "Khrustalyov, My Car!", "score" : 2.8496146202087402 }

쿼리 용어가 automobile인 경우에도 automobile을(를) 이름이 컬렉션에 대한 인덱스에 지정된 sample_synonyms인 동의어 소스 컬렉션에서 car, vehicle, automobile의 동의어로 구성했기 때문에 title 필드에 carautomobile이(가) 포함된 영화가 Atlas Search 결과에 포함됩니다. Atlas Search는 carvehicle 단어를 검색할 때 동일한 결과를 반환합니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle 중 하나로 바꾸고 쿼리를 실행합니다.

쿼리는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms라는 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색합니다.

db.movies.aggregate([
{
$search: {
"index": "synonyms-tutorial",
"text": {
"path": "title",
"query": "boat",
"synonyms": "transportSynonyms"
}
}
},
{
$limit: 10
},
{
$project: {
"_id": 0,
"title": 1,
"score": { $meta: "searchScore" }
}
}
])
{ "title" : "Vessel", "score" : 5.373150825500488 }
{ "title" : "Boats", "score" : 4.589139938354492 }
{ "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
{ "title" : "Broken Vessels", "score" : 4.3452959060668945 }
{ "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }
{ "title" : "Boat People", "score" : 3.711261749267578 }
{ "title" : "Boat Trip", "score" : 3.711261749267578 }
{ "title" : "Three Men in a Boat", "score" : 3.1153182983398438 }
{ "title" : "The Glass Bottom Boat", "score" : 3.1153182983398438 }
{ "title" : "Jack Goes Boating", "score" : 3.1153182983398438 }

title 필드에 boat, vessel, sail이 있는 영화가 Atlas Search 결과에 포함됩니다. 이는 컬렉션의 인덱스에 지정된 sample_synonyms라는 동의어 소스 컬렉션에서 boat, vessel, sailboat 동의어로 구성했기 때문입니다.

Atlas Search는 결과에서 vessel 단어를 검색한 경우에만 다음 문서를 반환합니다.

{ "title" : "Vessel", "score" : 5.373150825500488 }
{ "title" : "Broken Vessels", "score" : 4.3452959060668945 }

Atlas Search는 title 필드에 boat 또는 sail이 포함된 문서를 결과에 포함하지 않습니다. 이는 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 vessel로 바꾸고 쿼리를 다시 실행합니다.

마찬가지로, Atlas Search는 sail 검색어에 대한 검색 결과에서만 다음 문서를 반환합니다.

{ "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
{ "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

Atlas Search는 결과에서 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 이는 우리가 synonyms 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 설정하지 않았기 때문입니다. 이 예시를 테스트하려면 위의 쿼리에서 query 필드의 값을 sail로 바꾼 후 쿼리를 다시 실행해 보세요.

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

쿼리는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms라는 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색합니다. 이 쿼리는 title 필드에서도 단어 attire를 검색하며 attireSynonyms라는 이름의 동의어 매핑 정의를 사용하여 attire_synonyms라는 이름의 동의어 소스 컬렉션에서 쿼리 단어 attire의 동의어로 설정된 단어들을 검색합니다

db.movies.aggregate([
{
$search: {
"index": "synonyms-tutorial",
"compound": {
"should": [{
"text": {
"path": "title",
"query": "automobile",
"synonyms": "transportSynonyms"
}
},
{
"text": {
"path": "title",
"query": "attire",
"synonyms": "attireSynonyms"
}
}]
}
}
},
{
$limit: 10
},
{
$project: {
"_id": 0,
"title": 1,
"score": { $meta: "searchScore" }
}
}
])
[
{ title: 'The Dress', score: 4.812004089355469 },
{ title: 'Cars', score: 4.197734832763672 },
{ title: 'Dressed to Kill', score: 3.891493320465088 },
{ title: '27 Dresses', score: 3.891493320465088 },
{ title: 'Planes, Trains & Automobiles', score: 3.8511905670166016 },
{ title: 'Car Wash', score: 3.39473032951355 },
{ title: 'Used Cars', score: 3.39473032951355 },
{ title: 'Blue Car', score: 3.39473032951355 },
{ title: 'Cars 2', score: 3.39473032951355 },
{ title: 'Stealing Cars', score: 3.39473032951355 }
]

Atlas Search 결과에는 두 검색어에 대한 문서가 모두 포함되어 있습니다. 결과에는 쿼리 용어 automobile에 대하여 title 필드에 car이(가) 포함된 영화가 포함됩니다. 이는 transport_synonyms 동의어 소스 컬렉션에서 automobile을(를) car, vehicleautomobile의 동의어로 구성했기 때문입니다. 결과에는 쿼리 용어 attire에 대하여 제목 필드에 dress이(가) 포함된 영화도 포함됩니다. 이는 attire_synonyms 동의어 소스 컬렉션에서 attire을(를) dress, apparelattire의 동의어로 구성했기 때문입니다.

Atlas Search는 transport_synonyms 소스 컬렉션에서 car 또는 vehicle을(를) 검색하고 attire_synonyms 소스 컬렉션에서 dress 또는 apparel을(를) 검색할 때 동일한 결과를 반환합니다. 이 예시를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle(으)로 바꾸고 위 쿼리의 query 필드 값을 dress 또는 apparel(으)로 바꾼 다음 쿼리를 다시 실행합니다.

쿼리는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms라는 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색합니다. 이 쿼리는 title 필드에서도 단어 hat를 검색하며 attireSynonyms라는 이름의 동의어 매핑 정의를 사용하여 attire_synonyms라는 이름의 동의어 소스 컬렉션에서 쿼리 단어 hat의 동의어로 설정된 단어들을 검색합니다

db.movies.aggregate([
{
$search: {
"index": "synonyms-tutorial",
"compound": {
"should": [{
"text": {
"path": "title",
"query": "boat",
"synonyms": "transportSynonyms"
}
},
{
"text": {
"path": "title",
"query": "hat",
"synonyms": "attireSynonyms"
}
}]
}
}
},
{
$limit: 10
},
{
$project: {
"_id": 0,
"title": 1,
"score": { $meta: "searchScore" }
}
}
])
[
{ title: 'Fedora', score: 5.673145294189453 },
{ title: 'Vessel', score: 5.373150825500488 },
{ title: 'Boats', score: 4.589139938354492 },
{ title: 'And the Ship Sails On', score: 4.3452959060668945 },
{ title: 'Broken Vessels', score: 4.3452959060668945 },
{ title: 'Sailing to Paradise', score: 4.3452959060668945 },
{ title: 'Top Hat', score: 4.066137313842773 },
{ title: 'A Hatful of Rain', score: 4.066137313842773 },
{ title: 'Boat People', score: 3.711261749267578 },
{ title: 'Boat Trip', score: 3.711261749267578 }
]

Atlas Search 결과에 두 검색어에 대한 문서가 모두 포함됩니다. 검색어 boat에 대해 title 필드에 vessel, boat, sail이 있는 영화가 결과에 포함됩니다. 이는 transport_synonyms라는 동의어 소스 컬렉션에서 boatboat, vessel, sail의 동의어로 구성했기 때문입니다.

Atlas Search는 vessel 용어 검색 결과에서 title 필드에 boat 또는 sail이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 sail 용어 검색 결과의 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 vessel 또는 sail로 바꾸고 쿼리를 다시 실행하세요.

검색어 hat에 대하여 제목 필드에 fedorahat이 있는 동영상도 결과에 포함됩니다. attire_synonyms라는 동의어 소스 컬렉션에서 hathat, fedora, headgear 동의어로 구성했기 때문입니다.

Atlas Search는 headgear 용어 검색 결과에서 title 필드에 hat 또는 fedora이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 headgearhat 또는 fedora의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 fedora 용어 검색 결과의 title 필드에 hat 또는 headgear이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 fedorahat 또는 headgear의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 fedora 또는 headgear로 바꾸고 쿼리를 다시 실행하세요.

1

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

2

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

3

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

쿼리는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색합니다. 쿼리에는 다음과 같은 단계가 포함됩니다.

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

  • $project 단계에서 title 외에 모든 필드를 제외하고 score라는 필드를 추가합니다.

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

  1. Aggregations 탭을 클릭합니다.

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

    파이프라인 단계
    쿼리

    $search

    {
    "index": "synonyms-tutorial",
    "text": {
    "path": "title",
    "query": "automobile",
    "synonyms": "transportSynonyms"
    }
    }

    $limit

    10

    $project

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

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

    {title Cars} {score 4.197734832763672}
    {title Planes, Trains & Automobiles} {score 3.8511905670166016}
    {title Car Wash} {score 3.39473032951355}
    {title Used Cars} {score 3.39473032951355}
    {title Blue Car} {score 3.39473032951355}
    {title Cars 2} {score 3.39473032951355}
    {title Stealing Cars} {score 3.39473032951355}
    {title Cop Car} {score 3.39473032951355}
    {title The Cars That Eat People} {score 2.8496146202087402}
    {title Khrustalyov, My Car!} {score 2.8496146202087402}

    쿼리 용어가 automobile인 경우에도 automobile을(를) 이름이 컬렉션에 대한 인덱스에 지정된 sample_synonyms인 동의어 소스 컬렉션에서 car, vehicle, automobile의 동의어로 구성했기 때문에 title 필드에 carautomobile이(가) 포함된 영화가 Atlas Search 결과에 포함됩니다. Atlas Search는 carvehicle 단어를 검색할 때 동일한 결과를 반환합니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle 중 하나로 바꾸고 쿼리를 실행합니다.

쿼리는 title 필드에서 boat 단어를 검색하고 transportSynonyms라는 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색합니다. 다음 단계가 포함됩니다.

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

  • $project 단계에서 title 외에 모든 필드를 제외하고 score라는 필드를 추가합니다.

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

  1. Aggregations 탭을 클릭합니다.

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

    파이프라인 단계
    쿼리

    $search

    {
    "index": "synonyms-tutorial",
    "text": {
    "path": "title",
    "query": "boat",
    "synonyms": "transportSynonyms"
    }
    }

    $limit

    10

    $project

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

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

    {title Vessel} {score 5.373150825500488}
    {title Boats} {score 4.589139938354492}
    {title And the Ship Sails On} {score 4.3452959060668945}
    {title Broken Vessels} {score 4.3452959060668945}
    {title Sailing to Paradise} {score 4.3452959060668945}
    {title Boat People} {score 3.711261749267578}
    {title Boat Trip} {score 3.711261749267578}
    {title Three Men in a Boat} {score 3.1153182983398438}
    {title The Glass Bottom Boat} {score 3.1153182983398438}
    {title Jack Goes Boating} {score 3.1153182983398438}

    title 필드에 boat, vessel, sail이 있는 영화가 Atlas Search 결과에 포함됩니다. 이는 컬렉션의 인덱스에 지정된 sample_synonyms라는 동의어 소스 컬렉션에서 boat, vessel, sailboat 동의어로 구성했기 때문입니다.

    Atlas Search는 결과에서 vessel 단어를 검색한 경우에만 다음 문서를 반환합니다.

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search는 title 필드에 boat 또는 sail이 포함된 문서를 결과에 포함하지 않습니다. 이는 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 vessel로 바꾸고 쿼리를 다시 실행합니다.

    마찬가지로, Atlas Search는 sail 검색어에 대한 검색 결과에서만 다음 문서를 반환합니다.

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search는 결과에서 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 이는 우리가 synonyms 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 설정하지 않았기 때문입니다. 이 예시를 테스트하려면 위의 쿼리에서 query 필드의 값을 sail로 바꾼 후 쿼리를 다시 실행해 보세요.

4

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

쿼리는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms라는 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색합니다. 이 쿼리는 title 필드에서도 단어 attire를 검색하며 attireSynonyms라는 이름의 동의어 매핑 정의를 사용하여 attire_synonyms라는 이름의 동의어 소스 컬렉션에서 쿼리 단어 attire의 동의어로 설정된 단어들을 검색합니다

쿼리에는 다음과 같은 파이프라인 단계가 포함됩니다.

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

  • $project 단계에서 title 외에 모든 필드를 제외하고 score라는 필드를 추가합니다.

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

  1. Aggregations 탭을 클릭합니다.

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

    파이프라인 단계
    쿼리

    $search

    {
    "index": "synonyms-tutorial",
    "compound": {
    "should": [{
    "text": {
    "path": "title",
    "query": "automobile",
    "synonyms": "transportSynonyms"
    }
    },
    {
    "text": {
    "path": "title",
    "query": "attire",
    "synonyms": "attireSynonyms"
    }
    }]
    }
    }

    $limit

    10

    $project

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

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

    { title: 'The Dress', score: 4.812004089355469 },
    { title: 'Cars', score: 4.197734832763672 },
    { title: 'Dressed to Kill', score: 3.891493320465088 },
    { title: '27 Dresses', score: 3.891493320465088 },
    { title: 'Planes, Trains & Automobiles', score: 3.8511905670166016 },
    { title: 'Car Wash', score: 3.39473032951355 },
    { title: 'Used Cars', score: 3.39473032951355 },
    { title: 'Blue Car', score: 3.39473032951355 },
    { title: 'Cars 2', score: 3.39473032951355 },
    { title: 'Stealing Cars', score: 3.39473032951355 }

    Atlas Search 결과에는 두 검색어에 대한 문서가 모두 포함되어 있습니다. 결과에는 쿼리 용어 automobile에 대하여 title 필드에 car이(가) 포함된 영화가 포함됩니다. 이는 transport_synonyms 동의어 소스 컬렉션에서 automobile을(를) car, vehicleautomobile의 동의어로 구성했기 때문입니다. 결과에는 쿼리 용어 attire에 대하여 제목 필드에 dress이(가) 포함된 영화도 포함됩니다. 이는 attire_synonyms 동의어 소스 컬렉션에서 attire을(를) dress, apparelattire의 동의어로 구성했기 때문입니다.

    Atlas Search는 transport_synonyms 소스 컬렉션에서 car 또는 vehicle을(를) 검색하고 attire_synonyms 소스 컬렉션에서 dress 또는 apparel을(를) 검색할 때 동일한 결과를 반환합니다. 이 예시를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle(으)로 바꾸고 위 쿼리의 query 필드 값을 dress 또는 apparel(으)로 바꾼 다음 쿼리를 다시 실행합니다.

쿼리는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms라는 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색합니다. 이 쿼리는 title 필드에서도 단어 hat를 검색하며 attireSynonyms라는 이름의 동의어 매핑 정의를 사용하여 attire_synonyms라는 이름의 동의어 소스 컬렉션에서 쿼리 단어 hat의 동의어로 설정된 단어들을 검색합니다

쿼리에는 다음과 같은 파이프라인 단계가 포함됩니다.

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

  • $project 단계에서 title 외에 모든 필드를 제외하고 score라는 필드를 추가합니다.

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

  1. Aggregations 탭을 클릭합니다.

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

    파이프라인 단계
    쿼리

    $search

    {
    "index": "synonyms-tutorial",
    "compound": {
    "should": [{
    "text": {
    "path": "title",
    "query": "boat",
    "synonyms": "transportSynonyms"
    }
    },
    {
    "text": {
    "path": "title",
    "query": "hat",
    "synonyms": "attireSynonyms"
    }
    }]
    }
    }

    $limit

    10

    $project

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

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

    { title: 'Fedora', score: 5.673145294189453 },
    { title: 'Vessel', score: 5.373150825500488 },
    { title: 'Boats', score: 4.589139938354492 },
    { title: 'And the Ship Sails On', score: 4. 3452959060668945 },
    { title: 'Broken Vessels', score: 4.3452959060668945 },
    { title: 'Sailing to Paradise', score: 4.3452959060668945 },
    { title: 'Top Hat', score: 4.066137313842773 },
    { title: 'A Hatful of Rain', score: 4.066137313842773 },
    { title: 'Boat People', score: 3.711261749267578 },
    { title: 'Boat Trip', score: 3.711261749267578 }

    Atlas Search 결과에 두 검색어에 대한 문서가 모두 포함됩니다. 검색어 boat에 대해 title 필드에 vessel, boat, sail이 있는 영화가 결과에 포함됩니다. 이는 transport_synonyms라는 동의어 소스 컬렉션에서 boatboat, vessel, sail의 동의어로 구성했기 때문입니다.

    Atlas Search는 vessel 용어 검색 결과에서 title 필드에 boat 또는 sail이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 sail 용어 검색 결과의 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 vessel 또는 sail로 바꾸고 쿼리를 다시 실행하세요.

    검색어 hat에 대하여 제목 필드에 fedorahat이 있는 동영상도 결과에 포함됩니다. attire_synonyms라는 동의어 소스 컬렉션에서 hathat, fedora, headgear 동의어로 구성했기 때문입니다.

    Atlas Search는 headgear 용어 검색 결과에서 title 필드에 hat 또는 fedora이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 headgearhat 또는 fedora의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 fedora 용어 검색 결과의 title 필드에 hat 또는 headgear이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 fedorahat 또는 headgear의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 fedora 또는 headgear로 바꾸고 쿼리를 다시 실행하세요.

1

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

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

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

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

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

  1. synonyms-equivalent-query.go이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색하는 단계입니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/v2/bson"
    9 "go.mongodb.org/mongo-driver/v2/mongo"
    10 "go.mongodb.org/mongo-driver/v2/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(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.D{{"index", "synonyms-tutorial"}, {"text", bson.D{{"path", "title"}, {"query", "automobile"}, {"synonyms", "transportSynonyms"}}}}}}
    31 limitStage := bson.D{{"$limit", 10}}
    32 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    33 // specify the amount of time the operation can run on the server
    34 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    35 // run pipeline
    36 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    37 if err != nil {
    38 panic(err)
    39 }
    40 // print results
    41 var results []bson.D
    42 if err = cursor.All(context.TODO(), &results); err != nil {
    43 panic(err)
    44 }
    45 for _, result := range results {
    46 fmt.Println(result)
    47 }
    48}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

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

    go run synonyms-equivalent-query.go

    synonyms-equivalent-query.go를 실행하면 프로그램은 다음 문서를 터미널에 출력합니다.

    [{title Cars} {score 4.197734832763672}]
    [{title Planes, Trains & Automobiles} {score 3.8511905670166016}]
    [{title Car Wash} {score 3.39473032951355}]
    [{title Used Cars} {score 3.39473032951355}]
    [{title Blue Car} {score 3.39473032951355}]
    [{title Cars 2} {score 3.39473032951355}]
    [{title Stealing Cars} {score 3.39473032951355}]
    [{title Cop Car} {score 3.39473032951355}]
    [{title The Cars That Eat People} {score 2.8496146202087402}]
    [{title Khrustalyov, My Car!} {score 2.8496146202087402}]

    쿼리 용어가 automobile인 경우에도 automobile을(를) 이름이 컬렉션에 대한 인덱스에 지정된 sample_synonyms인 동의어 소스 컬렉션에서 car, vehicle, automobile의 동의어로 구성했기 때문에 title 필드에 carautomobile이(가) 포함된 영화가 Atlas Search 결과에 포함됩니다. Atlas Search는 carvehicle 단어를 검색할 때 동일한 결과를 반환합니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle 중 하나로 바꾸고 쿼리를 실행합니다.

  1. synonyms-explicit-query.go이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색하는 단계입니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/v2/bson"
    9 "go.mongodb.org/mongo-driver/v2/mongo"
    10 "go.mongodb.org/mongo-driver/v2/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(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.D{{"text", bson.D{{"index", "synonyms-tutorial"}, {"path", "title"}, {"query", "boat"}, {"synonyms", "transportSynonyms"}}}}}}
    31 limitStage := bson.D{{"$limit", 10}}
    32 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}, {"score", bson.D{{"$meta", "searchScore"}}}}}}
    33 // specify the amount of time the operation can run on the server
    34 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    35 // run pipeline
    36 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    37 if err != nil {
    38 panic(err)
    39 }
    40 // print results
    41 var results []bson.D
    42 if err = cursor.All(context.TODO(), &results); err != nil {
    43 panic(err)
    44 }
    45 for _, result := range results {
    46 fmt.Println(result)
    47 }
    48}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

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

    go run synonyms-explicit-query.go
    [{title Vessel} {score 5.373150825500488}]
    [{title Boats} {score 4.589139938354492}]
    [{title And the Ship Sails On} {score 4.3452959060668945}]
    [{title Broken Vessels} {score 4.3452959060668945}]
    [{title Sailing to Paradise} {score 4.3452959060668945}]
    [{title Boat People} {score 3.711261749267578}]
    [{title Boat Trip} {score 3.711261749267578}]
    [{title Three Men in a Boat} {score 3.1153182983398438}]
    [{title The Glass Bottom Boat} {score 3.1153182983398438}]
    [{title Jack Goes Boating} {score 3.1153182983398438}]

    title 필드에 boat, vessel, sail이 있는 영화가 Atlas Search 결과에 포함됩니다. 이는 컬렉션의 인덱스에 지정된 sample_synonyms라는 동의어 소스 컬렉션에서 boat, vessel, sailboat 동의어로 구성했기 때문입니다.

    Atlas Search는 결과에서 vessel 단어를 검색한 경우에만 다음 문서를 반환합니다.

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search는 title 필드에 boat 또는 sail이 포함된 문서를 결과에 포함하지 않습니다. 이는 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 vessel로 바꾸고 쿼리를 다시 실행합니다.

    마찬가지로, Atlas Search는 sail 검색어에 대한 검색 결과에서만 다음 문서를 반환합니다.

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search는 결과에서 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 이는 우리가 synonyms 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 설정하지 않았기 때문입니다. 이 예시를 테스트하려면 위의 쿼리에서 query 필드의 값을 sail로 바꾼 후 쿼리를 다시 실행해 보세요.

2

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

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

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

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

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

  1. synonyms-equivalent-query.go이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색하는 단계입니다. 쿼리는 attire 단어에 대한 title 필드도 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 쿼리 단어 attire의 동의어로 구성된 단어를 검색합니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/v2/bson"
    9 "go.mongodb.org/mongo-driver/v2/mongo"
    10 "go.mongodb.org/mongo-driver/v2/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(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": "synonyms-tutorial",
    32 "compound": bson.M{
    33 "should": bson.A{
    34 bson.M{
    35 "text": bson.D{
    36 {"path", "title"}, {"query", "automobile"}, {"synonyms", "transportSynonyms"},
    37 },
    38 },
    39 bson.M{
    40 "text": bson.D{
    41 {"path", "title"}, {"query", "attire"}, {"synonyms", "attireSynonyms"},
    42 },
    43 },
    44 },
    45 },
    46 }}}
    47 limitStage := bson.D{{"$limit", 10}}
    48 projectStage := bson.D{{"$project", bson.D{{"title", 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}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

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

    go run synonyms-equivalent-query.go
    [{title The Dress} {score 4.812004089355469}]
    [{title Cars} {score 4.197734832763672}]
    [{title Dressed to Kill} {score 3.891493320465088}]
    [{title 27 Dresses} {score 3.891493320465088}]
    [{title Planes, Trains & Automobiles} {score 3.8511905670166016}]
    [{title Car Wash} {score 3.39473032951355}]
    [{title Used Cars} {score 3.39473032951355}]
    [{title Blue Car} {score 3.39473032951355}]
    [{title Cars 2} {score 3.39473032951355}]
    [{title Stealing Cars} {score 3.39473032951355}]

    Atlas Search 결과에는 두 검색어에 대한 문서가 모두 포함되어 있습니다. 결과에는 쿼리 용어 automobile에 대하여 title 필드에 car이(가) 포함된 영화가 포함됩니다. 이는 transport_synonyms 동의어 소스 컬렉션에서 automobile을(를) car, vehicleautomobile의 동의어로 구성했기 때문입니다. 결과에는 쿼리 용어 attire에 대하여 제목 필드에 dress이(가) 포함된 영화도 포함됩니다. 이는 attire_synonyms 동의어 소스 컬렉션에서 attire을(를) dress, apparelattire의 동의어로 구성했기 때문입니다.

    Atlas Search는 transport_synonyms 소스 컬렉션에서 car 또는 vehicle을(를) 검색하고 attire_synonyms 소스 컬렉션에서 dress 또는 apparel을(를) 검색할 때 동일한 결과를 반환합니다. 이 예시를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle(으)로 바꾸고 위 쿼리의 query 필드 값을 dress 또는 apparel(으)로 바꾼 다음 쿼리를 다시 실행합니다.

  1. synonyms-explicit-query.go이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색하는 단계입니다. 쿼리는 hat 단어에 대한 title 필드도 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 쿼리 단어 hat의 동의어로 구성된 단어를 검색합니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1package main
    2
    3import (
    4 "context"
    5 "fmt"
    6 "time"
    7
    8 "go.mongodb.org/mongo-driver/v2/bson"
    9 "go.mongodb.org/mongo-driver/v2/mongo"
    10 "go.mongodb.org/mongo-driver/v2/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(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": "synonyms-tutorial",
    32 "compound": bson.M{
    33 "must": bson.A{
    34 bson.M{
    35 "text": bson.D{
    36 {"path", "title"}, {"query", "boat"}, {"synonyms", "transportSynonyms"},
    37 },
    38 },
    39 bson.M{
    40 "text": bson.D{
    41 {"path", "title"}, {"query", "hat"}, {"synonyms", "attireSynonyms"},
    42 },
    43 },
    44 },
    45 },
    46 }}}
    47 limitStage := bson.D{{"$limit", 10}}
    48 projectStage := bson.D{{"$project", bson.D{{"title", 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}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

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

    go run synonyms-explicit-query.go
    [{title Fedora} {score 5.673145294189453}]
    [{title Vessel} {score 5.373150825500488}]
    [{title Boats} {score 4.589139938354492}]
    [{title And the Ship Sails On} {score 4.3452959060668945}]
    [{title Broken Vessels} {score 4.3452959060668945}]
    [{title Sailing to Paradise} {score 4.3452959060668945}]
    [{title Top Hat} {score 4.066137313842773}]
    [{title A Hatful of Rain} {score 4.066137313842773}]
    [{title Boat People} {score 3.711261749267578}]
    [{title Boat Trip} {score 3.711261749267578}]

    Atlas Search 결과에 두 검색어에 대한 문서가 모두 포함됩니다. 검색어 boat에 대해 title 필드에 vessel, boat, sail이 있는 영화가 결과에 포함됩니다. 이는 transport_synonyms라는 동의어 소스 컬렉션에서 boatboat, vessel, sail의 동의어로 구성했기 때문입니다.

    Atlas Search는 vessel 용어 검색 결과에서 title 필드에 boat 또는 sail이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 sail 용어 검색 결과의 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 vessel 또는 sail로 바꾸고 쿼리를 다시 실행하세요.

    검색어 hat에 대하여 제목 필드에 fedorahat이 있는 동영상도 결과에 포함됩니다. attire_synonyms라는 동의어 소스 컬렉션에서 hathat, fedora, headgear 동의어로 구성했기 때문입니다.

    Atlas Search는 headgear 용어 검색 결과에서 title 필드에 hat 또는 fedora이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 headgearhat 또는 fedora의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 fedora 용어 검색 결과의 title 필드에 hat 또는 headgear이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 fedorahat 또는 headgear의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 fedora 또는 headgear로 바꾸고 쿼리를 다시 실행하세요.

1

junit

4.11 또는 그 이상의 버전

mongodb-driver-sync

4.3.0 또는 그 이상의 버전

slf4j-log4j12

1.7.30 또는 그 이상의 버전

2

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

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

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

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

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

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

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색하는 단계입니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    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.excludeId;
    6import static com.mongodb.client.model.Projections.fields;
    7import static com.mongodb.client.model.Projections.include;
    8import static com.mongodb.client.model.Projections.computed;
    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 SynonymsEquivalentQuery {
    16 public static void main( String[] args ) {
    17 // define query
    18 Document agg = new Document("$search",
    19 new Document("index", "synonyms-tutorial")
    20 .append("text",
    21 new Document("query", "automobile")
    22 .append("path","title")
    23 .append("synonyms", "transportSynonyms")));
    24
    25 // specify connection
    26 String uri = "<connection-string>";
    27
    28 // establish connection and set namespace
    29 try (MongoClient mongoClient = MongoClients.create(uri)) {
    30 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    31 MongoCollection<Document> collection = database.getCollection("movies");
    32
    33 // run query and print results
    34 collection.aggregate(Arrays.asList(agg,
    35 limit(10),
    36 project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore")))))
    37 ).forEach(doc -> System.out.println(doc.toJson()));
    38 }
    39 }
    40}

    참고

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

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

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

    javac SynonymsEquivalentQuery.java
    java SynonymsEquivalentQuery
    {"title": "Cars", "score": 4.197734832763672}
    {"title": "Planes, Trains & Automobiles", "score": 3.8511905670166016}
    {"title": "Car Wash", "score": 3.39473032951355}
    {"title": "Used Cars", "score": 3.39473032951355}
    {"title": "Blue Car", "score": 3.39473032951355}
    {"title": "Cars 2", "score": 3.39473032951355}
    {"title": "Stealing Cars", "score": 3.39473032951355}
    {"title": "Cop Car", "score": 3.39473032951355}
    {"title": "The Cars That Eat People", "score": 2.8496146202087402}
    {"title": "Khrustalyov, My Car!", "score": 2.8496146202087402}

    쿼리 용어가 automobile인 경우에도 automobile을(를) 이름이 컬렉션에 대한 인덱스에 지정된 sample_synonyms인 동의어 소스 컬렉션에서 car, vehicle, automobile의 동의어로 구성했기 때문에 title 필드에 carautomobile이(가) 포함된 영화가 Atlas Search 결과에 포함됩니다. Atlas Search는 carvehicle 단어를 검색할 때 동일한 결과를 반환합니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle 중 하나로 바꾸고 쿼리를 실행합니다.

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

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색하는 단계입니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    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.excludeId;
    6import static com.mongodb.client.model.Projections.fields;
    7import static com.mongodb.client.model.Projections.include;
    8import static com.mongodb.client.model.Projections.computed;
    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 SynonymsExplicitQuery {
    16 public static void main( String[] args ) {
    17 // define query
    18 Document agg = new Document("$search",
    19 new Document("index", "synonyms-tutorial")
    20 .append("text",
    21 new Document("query", "boat")
    22 .append("path","title")
    23 .append("synonyms", "transportSynonyms")));
    24
    25 // specify connection
    26 String uri = "<connection-string>";
    27
    28 // establish connection and set namespace
    29 try (MongoClient mongoClient = MongoClients.create(uri)) {
    30 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    31 MongoCollection<Document> collection = database.getCollection("movies");
    32
    33 // run query and print results
    34 collection.aggregate(Arrays.asList(agg,
    35 limit(10),
    36 project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore")))))
    37 ).forEach(doc -> System.out.println(doc.toJson()));
    38 }
    39 }
    40}

    참고

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

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

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

    javac SynonymsExplicitQuery.java
    java SynonymsExplicitQuery
    {"title": "Vessel", "score": 5.373150825500488}
    {"title": "Boats", "score": 4.589139938354492}
    {"title": "And the Ship Sails On", "score": 4.3452959060668945}
    {"title": "Broken Vessels", "score": 4.3452959060668945}
    {"title": "Sailing to Paradise", "score": 4.3452959060668945}
    {"title": "Boat People", "score": 3.711261749267578}
    {"title": "Boat Trip", "score": 3.711261749267578}
    {"title": "Three Men in a Boat", "score": 3.1153182983398438}
    {"title": "The Glass Bottom Boat", "score": 3.1153182983398438}
    {"title": "Jack Goes Boating", "score": 3.1153182983398438}

    title 필드에 boat, vessel, sail이 있는 영화가 Atlas Search 결과에 포함됩니다. 이는 컬렉션의 인덱스에 지정된 sample_synonyms라는 동의어 소스 컬렉션에서 boat, vessel, sailboat 동의어로 구성했기 때문입니다.

    Atlas Search는 결과에서 vessel 단어를 검색한 경우에만 다음 문서를 반환합니다.

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search는 title 필드에 boat 또는 sail이 포함된 문서를 결과에 포함하지 않습니다. 이는 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 vessel로 바꾸고 쿼리를 다시 실행합니다.

    마찬가지로, Atlas Search는 sail 검색어에 대한 검색 결과에서만 다음 문서를 반환합니다.

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search는 결과에서 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 이는 우리가 synonyms 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 설정하지 않았기 때문입니다. 이 예시를 테스트하려면 위의 쿼리에서 query 필드의 값을 sail로 바꾼 후 쿼리를 다시 실행해 보세요.

3

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

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

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

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

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

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

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색하는 단계입니다. 쿼리는 attire 단어에 대한 title 필드도 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 쿼리 단어 attire의 동의어로 구성된 단어를 검색합니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    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 SynonymsEquivalentQuery {
    16 public static void main( String[] args ) {
    17 Document agg = new Document("$search",
    18 new Document("index", "synonyms-tutorial")
    19 .append("compound",
    20 new Document("should", Arrays.asList(new Document("text",
    21 new Document("path", "title")
    22 .append("query", "automobile")
    23 .append("synonyms", "transportSynonyms")),
    24 new Document("text",
    25 new Document("path", "title")
    26 .append("query", "attire")
    27 .append("synonyms", "attireSynonyms"))))));
    28
    29 String uri = "<connection-string>";
    30
    31 try (MongoClient mongoClient = MongoClients.create(uri)) {
    32 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    33 MongoCollection<Document> collection = database.getCollection("movies");
    34
    35 collection.aggregate(Arrays.asList(agg,
    36 limit(10),
    37 project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore")))))
    38 ).forEach(doc -> System.out.println(doc.toJson()));
    39 }
    40 }
    41}

    참고

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

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

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

    javac SynonymsEquivalentQuery.java
    java SynonymsEquivalentQuery
    {"title": "The Dress", "score": 4.812004089355469}
    {"title": "Cars", "score": 4.197734832763672}
    {"title": "Dressed to Kill", "score": 3.891493320465088}
    {"title": "27 Dresses", "score": 3.891493320465088}
    {"title": "Planes, Trains & Automobiles", "score": 3.8511905670166016}
    {"title": "Car Wash", "score": 3.39473032951355}
    {"title": "Used Cars", "score": 3.39473032951355}
    {"title": "Blue Car", "score": 3.39473032951355}
    {"title": "Cars 2", "score": 3.39473032951355}
    {"title": "Stealing Cars", "score": 3.39473032951355}

    Atlas Search 결과에는 두 검색어에 대한 문서가 모두 포함되어 있습니다. 결과에는 쿼리 용어 automobile에 대하여 title 필드에 car이(가) 포함된 영화가 포함됩니다. 이는 transport_synonyms 동의어 소스 컬렉션에서 automobile을(를) car, vehicleautomobile의 동의어로 구성했기 때문입니다. 결과에는 쿼리 용어 attire에 대하여 제목 필드에 dress이(가) 포함된 영화도 포함됩니다. 이는 attire_synonyms 동의어 소스 컬렉션에서 attire을(를) dress, apparelattire의 동의어로 구성했기 때문입니다.

    Atlas Search는 transport_synonyms 소스 컬렉션에서 car 또는 vehicle을(를) 검색하고 attire_synonyms 소스 컬렉션에서 dress 또는 apparel을(를) 검색할 때 동일한 결과를 반환합니다. 이 예시를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle(으)로 바꾸고 위 쿼리의 query 필드 값을 dress 또는 apparel(으)로 바꾼 다음 쿼리를 다시 실행합니다.

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

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색하는 단계입니다. 쿼리는 hat 단어에 대한 title 필드도 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 쿼리 단어 hat의 동의어로 구성된 단어를 검색합니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    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 SynonymsExplicitQuery {
    16 public static void main( String[] args ) {
    17 Document agg = new Document("$search",
    18 new Document("index", "synonyms-tutorial")
    19 .append("compound",
    20 new Document("should", Arrays.asList(new Document("text",
    21 new Document("path", "title")
    22 .append("query", "boat")
    23 .append("synonyms", "transportSynonyms")),
    24 new Document("text",
    25 new Document("path", "title")
    26 .append("query", "hat")
    27 .append("synonyms", "attireSynonyms"))))));
    28
    29 String uri = "<connection-string>";
    30
    31 try (MongoClient mongoClient = MongoClients.create(uri)) {
    32 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    33 MongoCollection<Document> collection = database.getCollection("movies");
    34
    35 collection.aggregate(Arrays.asList(agg,
    36 limit(10),
    37 project(fields(excludeId(), include("title"), computed("score", new Document("$meta", "searchScore")))))
    38 ).forEach(doc -> System.out.println(doc.toJson()));
    39 }
    40 }
    41}

    참고

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

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

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

    javac SynonymsExplicitQuery.java
    java SynonymsExplicitQuery
    {"title": "Fedora", "score": 5.673145294189453}
    {"title": "Vessel", "score": 5.373150825500488}
    {"title": "Boats", "score": 4.589139938354492}
    {"title": "And the Ship Sails On", "score": 4.3452959060668945}
    {"title": "Broken Vessels", "score": 4.3452959060668945}
    {"title": "Sailing to Paradise", "score": 4.3452959060668945}
    {"title": "Top Hat", "score": 4.066137313842773}
    {"title": "A Hatful of Rain", "score": 4.066137313842773}
    {"title": "Boat People", "score": 3.711261749267578}
    {"title": "Boat Trip", "score": 3.711261749267578}

    Atlas Search 결과에 두 검색어에 대한 문서가 모두 포함됩니다. 검색어 boat에 대해 title 필드에 vessel, boat, sail이 있는 영화가 결과에 포함됩니다. 이는 transport_synonyms라는 동의어 소스 컬렉션에서 boatboat, vessel, sail의 동의어로 구성했기 때문입니다.

    Atlas Search는 vessel 용어 검색 결과에서 title 필드에 boat 또는 sail이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 sail 용어 검색 결과의 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 vessel 또는 sail로 바꾸고 쿼리를 다시 실행하세요.

    검색어 hat에 대하여 제목 필드에 fedorahat이 있는 동영상도 결과에 포함됩니다. attire_synonyms라는 동의어 소스 컬렉션에서 hathat, fedora, headgear 동의어로 구성했기 때문입니다.

    Atlas Search는 headgear 용어 검색 결과에서 title 필드에 hat 또는 fedora이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 headgearhat 또는 fedora의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 fedora 용어 검색 결과의 title 필드에 hat 또는 headgear이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 fedorahat 또는 headgear의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 fedora 또는 headgear로 바꾸고 쿼리를 다시 실행하세요.

1

mongodb-driver-kotlin-coroutine

4.10.0 또는 그 이상의 버전

2

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

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

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

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

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

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

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색하는 단계입니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    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 query
    17 val agg = Document(
    18 "\$search",
    19 Document("index", "synonyms-tutorial")
    20 .append(
    21 "text",
    22 Document("query", "automobile")
    23 .append("path", "title")
    24 .append("synonyms", "transportSynonyms")
    25 )
    26 )
    27
    28 // run query and print results
    29 val resultsFlow = collection.aggregate<Document>(
    30 listOf(
    31 agg,
    32 limit(10),
    33 project(fields(
    34 excludeId(),
    35 include("title"),
    36 computed("score", Document("\$meta", "searchScore"))
    37 ))
    38 )
    39 )
    40 resultsFlow.collect { println(it) }
    41 }
    42 mongoClient.close()
    43}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

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

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

    Document{{title=Cars, score=4.140600204467773}}
    Document{{title=Planes, Trains & Automobiles, score=3.8122920989990234}}
    Document{{title=Blue Car, score=3.348478317260742}}
    Document{{title=Used Cars, score=3.348478317260742}}
    Document{{title=Cars 2, score=3.348478317260742}}
    Document{{title=Stealing Cars, score=3.348478317260742}}
    Document{{title=Cop Car, score=3.348478317260742}}
    Document{{title=Car Wash, score=3.348478317260742}}
    Document{{title=The Cars That Eat People, score=2.810762405395508}}
    Document{{title=Revenge of the Electric Car, score=2.810762405395508}}

    쿼리 용어가 automobile인 경우에도 automobile을(를) 이름이 컬렉션에 대한 인덱스에 지정된 sample_synonyms인 동의어 소스 컬렉션에서 car, vehicle, automobile의 동의어로 구성했기 때문에 title 필드에 carautomobile이(가) 포함된 영화가 Atlas Search 결과에 포함됩니다. Atlas Search는 carvehicle 단어를 검색할 때 동일한 결과를 반환합니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle 중 하나로 바꾸고 쿼리를 실행합니다.

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

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색하는 단계입니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    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 query
    17 val agg = Document(
    18 "\$search",
    19 Document("index", "synonyms-tutorial")
    20 .append(
    21 "text",
    22 Document("query", "boat")
    23 .append("path", "title")
    24 .append("synonyms", "transportSynonyms")
    25 )
    26 )
    27
    28 // run query and print results
    29 val resultsFlow = collection.aggregate<Document>(
    30 listOf(
    31 agg,
    32 limit(10),
    33 project(fields(
    34 excludeId(),
    35 include("title"),
    36 computed("score", Document("\$meta", "searchScore"))
    37 ))
    38 )
    39 )
    40 resultsFlow.collect { println(it) }
    41 }
    42 mongoClient.close()
    43}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

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

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

    Document{{title=Vessel, score=5.3159894943237305}}
    Document{{title=Boats, score=4.597315311431885}}
    Document{{title=Sailing to Paradise, score=4.299008369445801}}
    Document{{title=And the Ship Sails On, score=4.299008369445801}}
    Document{{title=Broken Vessels, score=4.299008369445801}}
    Document{{title=Boat Trip, score=3.717820644378662}}
    Document{{title=Boat People, score=3.717820644378662}}
    Document{{title=Jack Goes Boating, score=3.1207938194274902}}
    Document{{title=The Glass Bottom Boat, score=3.1207938194274902}}
    Document{{title=Raspberry Boat Refugee, score=3.1207938194274902}}

    title 필드에 boat, vessel, sail이 있는 영화가 Atlas Search 결과에 포함됩니다. 이는 컬렉션의 인덱스에 지정된 sample_synonyms라는 동의어 소스 컬렉션에서 boat, vessel, sailboat 동의어로 구성했기 때문입니다.

    Atlas Search는 결과에서 vessel 단어를 검색한 경우에만 다음 문서를 반환합니다.

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search는 title 필드에 boat 또는 sail이 포함된 문서를 결과에 포함하지 않습니다. 이는 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 vessel로 바꾸고 쿼리를 다시 실행합니다.

    마찬가지로, Atlas Search는 sail 검색어에 대한 검색 결과에서만 다음 문서를 반환합니다.

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search는 결과에서 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 이는 우리가 synonyms 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 설정하지 않았기 때문입니다. 이 예시를 테스트하려면 위의 쿼리에서 query 필드의 값을 sail로 바꾼 후 쿼리를 다시 실행해 보세요.

3

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

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

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

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

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

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

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색하는 단계입니다. 쿼리는 attire 단어에 대한 title 필드도 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 쿼리 단어 attire의 동의어로 구성된 단어를 검색합니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    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 query
    17 val agg = Document(
    18 "\$search",
    19 Document("index", "synonyms-tutorial")
    20 .append(
    21 "compound",
    22 Document(
    23 "should", listOf(
    24 Document(
    25 "text",
    26 Document("path", "title")
    27 .append("query", "automobile")
    28 .append("synonyms", "transportSynonyms")
    29 ),
    30 Document(
    31 "text",
    32 Document("path", "title")
    33 .append("query", "attire")
    34 .append("synonyms", "attireSynonyms")
    35 )
    36 )
    37 )
    38 )
    39 )
    40
    41 // run query and print results
    42 val resultsFlow = collection.aggregate<Document>(
    43 listOf(
    44 agg,
    45 limit(10),
    46 project(fields(
    47 excludeId(),
    48 include("title"),
    49 computed("score", Document("\$meta", "searchScore"))
    50 ))
    51 )
    52 )
    53 resultsFlow.collect { println(it) }
    54 }
    55 mongoClient.close()
    56}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

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

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

    Document{{title=The Dress, score=4.852960586547852}}
    Document{{title=Cars, score=4.140600204467773}}
    Document{{title=27 Dresses, score=3.9245595932006836}}
    Document{{title=Planes, Trains & Automobiles, score=3.8122920989990234}}
    Document{{title=Car Wash, score=3.348478317260742}}
    Document{{title=Used Cars, score=3.348478317260742}}
    Document{{title=Blue Car, score=3.348478317260742}}
    Document{{title=Cars 2, score=3.348478317260742}}
    Document{{title=Stealing Cars, score=3.348478317260742}}
    Document{{title=Cop Car, score=3.348478317260742}}

    Atlas Search 결과에는 두 검색어에 대한 문서가 모두 포함되어 있습니다. 결과에는 쿼리 용어 automobile에 대하여 title 필드에 car이(가) 포함된 영화가 포함됩니다. 이는 transport_synonyms 동의어 소스 컬렉션에서 automobile을(를) car, vehicleautomobile의 동의어로 구성했기 때문입니다. 결과에는 쿼리 용어 attire에 대하여 제목 필드에 dress이(가) 포함된 영화도 포함됩니다. 이는 attire_synonyms 동의어 소스 컬렉션에서 attire을(를) dress, apparelattire의 동의어로 구성했기 때문입니다.

    Atlas Search는 transport_synonyms 소스 컬렉션에서 car 또는 vehicle을(를) 검색하고 attire_synonyms 소스 컬렉션에서 dress 또는 apparel을(를) 검색할 때 동일한 결과를 반환합니다. 이 예시를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle(으)로 바꾸고 위 쿼리의 query 필드 값을 dress 또는 apparel(으)로 바꾼 다음 쿼리를 다시 실행합니다.

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

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색하는 단계입니다. 쿼리는 hat 단어에 대한 title 필드도 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 쿼리 단어 hat의 동의어로 구성된 단어를 검색합니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    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 query
    17 val agg = Document(
    18 "\$search",
    19 Document("index", "synonyms-tutorial")
    20 .append(
    21 "compound",
    22 Document(
    23 "should", listOf(
    24 Document(
    25 "text",
    26 Document("path", "title")
    27 .append("query", "boat")
    28 .append("synonyms", "transportSynonyms")
    29 ),
    30 Document(
    31 "text",
    32 Document("path", "title")
    33 .append("query", "hat")
    34 .append("synonyms", "attireSynonyms")
    35 )
    36 )
    37 )
    38 )
    39 )
    40
    41 // run query and print results
    42 val resultsFlow = collection.aggregate<Document>(
    43 listOf(
    44 agg,
    45 limit(10),
    46 project(fields(
    47 excludeId(),
    48 include("title"),
    49 computed("score", Document("\$meta", "searchScore"))
    50 ))
    51 )
    52 )
    53
    54 resultsFlow.collect { println(it) }
    55 }
    56
    57 mongoClient.close()
    58}
  3. 샘플을 실행하기 전에 <connection-string>을 Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

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

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

    Document{{title=Fedora, score=5.6159772872924805}}
    Document{{title=Vessel, score=5.3159894943237305}}
    Document{{title=Boats, score=4.597315311431885}}
    Document{{title=And the Ship Sails On, score=4.299008369445801}}
    Document{{title=Broken Vessels, score=4.299008369445801}}
    Document{{title=Sailing to Paradise, score=4.299008369445801}}
    Document{{title=Top Hat, score=4.01986026763916}}
    Document{{title=A Hatful of Rain, score=4.01986026763916}}
    Document{{title=Boat People, score=3.717820644378662}}
    Document{{title=Boat Trip, score=3.717820644378662}}

    Atlas Search 결과에 두 검색어에 대한 문서가 모두 포함됩니다. 검색어 boat에 대해 title 필드에 vessel, boat, sail이 있는 영화가 결과에 포함됩니다. 이는 transport_synonyms라는 동의어 소스 컬렉션에서 boatboat, vessel, sail의 동의어로 구성했기 때문입니다.

    Atlas Search는 vessel 용어 검색 결과에서 title 필드에 boat 또는 sail이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 sail 용어 검색 결과의 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 vessel 또는 sail로 바꾸고 쿼리를 다시 실행하세요.

    검색어 hat에 대하여 제목 필드에 fedorahat이 있는 동영상도 결과에 포함됩니다. attire_synonyms라는 동의어 소스 컬렉션에서 hathat, fedora, headgear 동의어로 구성했기 때문입니다.

    Atlas Search는 headgear 용어 검색 결과에서 title 필드에 hat 또는 fedora이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 headgearhat 또는 fedora의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 fedora 용어 검색 결과의 title 필드에 hat 또는 headgear이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 fedorahat 또는 headgear의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 fedora 또는 headgear로 바꾸고 쿼리를 다시 실행하세요.

1

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

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

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

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

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

  1. synonyms-equivalent-query.js이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색하는 단계입니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 $search: {
    7 index: "synonyms-tutorial",
    8 text: {
    9 path: "title",
    10 query: "automobile",
    11 synonyms: "transportSynonyms",
    12 },
    13 },
    14 },
    15 {
    16 $limit: 10,
    17 },
    18 {
    19 $project: {
    20 _id: 0,
    21 title: 1,
    22 score: { $meta: "searchScore" },
    23 },
    24 },
    25];
    26
    27MongoClient.connect(
    28 "<connection-string>",
    29 { useNewUrlParser: true, useUnifiedTopology: true },
    30 async function (connectErr, client) {
    31 assert.equal(null, connectErr);
    32 const coll = client.db("sample_mflix").collection("movies");
    33 let cursor = await coll.aggregate(agg);
    34 await cursor.forEach((doc) => console.log(doc));
    35 client.close();
    36 }
    37);
  3. 샘플을 실행하기 전에 <connection-string>을(를) Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다.

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

    node synonyms-equivalent-query.js
    { title: 'Cars', score: 4.197734832763672 }
    { title: 'Planes, Trains & Automobiles', score: 3.8511905670166016 }
    { title: 'Car Wash', score: 3.39473032951355 }
    { title: 'Used Cars', score: 3.39473032951355 }
    { title: 'Blue Car', score: 3.39473032951355 }
    { title: 'Cars 2', score: 3.39473032951355 }
    { title: 'Stealing Cars', score: 3.39473032951355 }
    { title: 'Cop Car', score: 3.39473032951355 }
    { title: 'The Cars That Eat People', score: 2.8496146202087402 }
    { title: 'Khrustalyov, My Car!', score: 2.8496146202087402 }

    쿼리 용어가 automobile인 경우에도 automobile을(를) 이름이 컬렉션에 대한 인덱스에 지정된 sample_synonyms인 동의어 소스 컬렉션에서 car, vehicle, automobile의 동의어로 구성했기 때문에 title 필드에 carautomobile이(가) 포함된 영화가 Atlas Search 결과에 포함됩니다. Atlas Search는 carvehicle 단어를 검색할 때 동일한 결과를 반환합니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle 중 하나로 바꾸고 쿼리를 실행합니다.

  1. synonyms-explicit-query.js이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색하는 단계입니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 $search: {
    7 index: "synonyms-tutorial",
    8 text: {
    9 path: "title",
    10 query: "boat",
    11 synonyms: "transportSynonyms",
    12 },
    13 },
    14 },
    15 {
    16 $limit: 10,
    17 },
    18 {
    19 $project: {
    20 _id: 0,
    21 title: 1,
    22 score: { $meta: "searchScore" },
    23 },
    24 },
    25];
    26
    27MongoClient.connect(
    28 "<connection-string>",
    29 { useNewUrlParser: true, useUnifiedTopology: true },
    30 async function (connectErr, client) {
    31 assert.equal(null, connectErr);
    32 const coll = client.db("sample_mflix").collection("movies");
    33 let cursor = await coll.aggregate(agg);
    34 await cursor.forEach((doc) => console.log(doc));
    35 client.close();
    36 }
    37);
  3. 샘플을 실행하기 전에 <connection-string>을(를) Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다.

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

    node synonyms-explicit-query.js
    { title: 'Vessel', score: 5.373150825500488 }
    { title: 'Boats', score: 4.589139938354492 }
    { title: 'And the Ship Sails On', score: 4.3452959060668945 }
    { title: 'Broken Vessels', score: 4.3452959060668945 }
    { title: 'Sailing to Paradise', score: 4.3452959060668945 }
    { title: 'Boat People', score: 3.711261749267578 }
    { title: 'Boat Trip', score: 3.711261749267578 }
    { title: 'Three Men in a Boat', score: 3.1153182983398438 }
    { title: 'The Glass Bottom Boat', score: 3.1153182983398438 }
    { title: 'Jack Goes Boating', score: 3.1153182983398438 }

    title 필드에 boat, vessel, sail이 있는 영화가 Atlas Search 결과에 포함됩니다. 이는 컬렉션의 인덱스에 지정된 sample_synonyms라는 동의어 소스 컬렉션에서 boat, vessel, sailboat 동의어로 구성했기 때문입니다.

    Atlas Search는 결과에서 vessel 단어를 검색한 경우에만 다음 문서를 반환합니다.

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search는 title 필드에 boat 또는 sail이 포함된 문서를 결과에 포함하지 않습니다. 이는 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 vessel로 바꾸고 쿼리를 다시 실행합니다.

    마찬가지로, Atlas Search는 sail 검색어에 대한 검색 결과에서만 다음 문서를 반환합니다.

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search는 결과에서 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 이는 우리가 synonyms 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 설정하지 않았기 때문입니다. 이 예시를 테스트하려면 위의 쿼리에서 query 필드의 값을 sail로 바꾼 후 쿼리를 다시 실행해 보세요.

2

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

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

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

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

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

  1. synonyms-equivalent-query.js이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색하는 단계입니다. 쿼리는 attire 단어에 대한 title 필드도 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 쿼리 단어 attire의 동의어로 구성된 단어를 검색합니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1pconst MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 '$search': {
    7 'index': 'synonyms-tutorial',
    8 'compound': {
    9 'should': [
    10 {
    11 'text': {
    12 'path': 'title',
    13 'query': 'automobile',
    14 'synonyms': 'transportSynonyms'
    15 }
    16 }, {
    17 'text': {
    18 'path': 'title',
    19 'query': 'attire',
    20 'synonyms': 'attireSynonyms'
    21 }
    22 }
    23 ]
    24 }
    25 }
    26 }, {
    27 '$limit': 10
    28 }, {
    29 '$project': {
    30 '_id': 0,
    31 'title': 1,
    32 'score': {
    33 '$meta': 'searchScore'
    34 }
    35 }
    36 }
    37];
    38
    39MongoClient.connect(
    40 "<connection-string>",
    41 { useNewUrlParser: true, useUnifiedTopology: true },
    42 async function (connectErr, client) {
    43 assert.equal(null, connectErr);
    44 const coll = client.db("sample_mflix").collection("movies");
    45 let cursor = await coll.aggregate(agg);
    46 await cursor.forEach((doc) => console.log(doc));
    47 client.close();
    48 }
    49);
  3. 샘플을 실행하기 전에 <connection-string>을(를) Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다.

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

    node synonyms-equivalent-query.js
    { title: 'The Dress', score: 4.812004089355469 }
    { title: 'Cars', score: 4.197734832763672 }
    { title: 'Dressed to Kill', score: 3.891493320465088 }
    { title: '27 Dresses', score: 3.891493320465088 }
    { title: 'Planes, Trains & Automobiles', score: 3.8511905670166016 }
    { title: 'Car Wash', score: 3.39473032951355 }
    { title: 'Used Cars', score: 3.39473032951355 }
    { title: 'Blue Car', score: 3.39473032951355 }
    { title: 'Cars 2', score: 3.39473032951355 }
    { title: 'Stealing Cars', score: 3.39473032951355 }

    Atlas Search 결과에는 두 검색어에 대한 문서가 모두 포함되어 있습니다. 결과에는 쿼리 용어 automobile에 대하여 title 필드에 car이(가) 포함된 영화가 포함됩니다. 이는 transport_synonyms 동의어 소스 컬렉션에서 automobile을(를) car, vehicleautomobile의 동의어로 구성했기 때문입니다. 결과에는 쿼리 용어 attire에 대하여 제목 필드에 dress이(가) 포함된 영화도 포함됩니다. 이는 attire_synonyms 동의어 소스 컬렉션에서 attire을(를) dress, apparelattire의 동의어로 구성했기 때문입니다.

    Atlas Search는 transport_synonyms 소스 컬렉션에서 car 또는 vehicle을(를) 검색하고 attire_synonyms 소스 컬렉션에서 dress 또는 apparel을(를) 검색할 때 동일한 결과를 반환합니다. 이 예시를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle(으)로 바꾸고 위 쿼리의 query 필드 값을 dress 또는 apparel(으)로 바꾼 다음 쿼리를 다시 실행합니다.

  1. synonyms-explicit-query.js이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색하는 단계입니다. 쿼리는 hat 단어에 대한 title 필드도 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 쿼리 단어 hat의 동의어로 구성된 단어를 검색합니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 '$search': {
    7 'index': 'synonyms-tutorial',
    8 'compound': {
    9 'should': [
    10 {
    11 'text': {
    12 'path': 'title',
    13 'query': 'boat',
    14 'synonyms': 'transportSynonyms'
    15 }
    16 }, {
    17 'text': {
    18 'path': 'title',
    19 'query': 'hat',
    20 'synonyms': 'attireSynonyms'
    21 }
    22 }
    23 ]
    24 }
    25 }
    26 }, {
    27 '$limit': 10
    28 }, {
    29 '$project': {
    30 '_id': 0,
    31 'title': 1,
    32 'score': {
    33 '$meta': 'searchScore'
    34 }
    35 }
    36 }
    37];
    38
    39MongoClient.connect(
    40 "<connection-string>",
    41 { useNewUrlParser: true, useUnifiedTopology: true },
    42 async function (connectErr, client) {
    43 assert.equal(null, connectErr);
    44 const coll = client.db("sample_mflix").collection("movies");
    45 let cursor = await coll.aggregate(agg);
    46 await cursor.forEach((doc) => console.log(doc));
    47 client.close();
    48 }
    49);
  3. 샘플을 실행하기 전에 <connection-string>을(를) Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다.

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

    node synonyms-explicit-query.js
    { title: 'Fedora', score: 5.673145294189453 }
    { title: 'Vessel', score: 5.373150825500488 }
    { title: 'Boats', score: 4.589139938354492 }
    { title: 'And the Ship Sails On', score: 4.3452959060668945 }
    { title: 'Broken Vessels', score: 4.3452959060668945 }
    { title: 'Sailing to Paradise', score: 4.3452959060668945 }
    { title: 'Top Hat', score: 4.066137313842773 }
    { title: 'A Hatful of Rain', score: 4.066137313842773 }
    { title: 'Boat People', score: 3.711261749267578 }
    { title: 'Boat Trip', score: 3.711261749267578 }

    Atlas Search 결과에 두 검색어에 대한 문서가 모두 포함됩니다. 검색어 boat에 대해 title 필드에 vessel, boat, sail이 있는 영화가 결과에 포함됩니다. 이는 transport_synonyms라는 동의어 소스 컬렉션에서 boatboat, vessel, sail의 동의어로 구성했기 때문입니다.

    Atlas Search는 vessel 용어 검색 결과에서 title 필드에 boat 또는 sail이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 sail 용어 검색 결과의 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 vessel 또는 sail로 바꾸고 쿼리를 다시 실행하세요.

    검색어 hat에 대하여 제목 필드에 fedorahat이 있는 동영상도 결과에 포함됩니다. attire_synonyms라는 동의어 소스 컬렉션에서 hathat, fedora, headgear 동의어로 구성했기 때문입니다.

    Atlas Search는 headgear 용어 검색 결과에서 title 필드에 hat 또는 fedora이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 headgearhat 또는 fedora의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 fedora 용어 검색 결과의 title 필드에 hat 또는 headgear이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 fedorahat 또는 headgear의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 fedora 또는 headgear로 바꾸고 쿼리를 다시 실행하세요.

1

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

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

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

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

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

  1. synonyms-equivalent-query.py이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색하는 단계입니다.

    • $limit 출력을 10 결과로 제한하는 단계

    • $project 단계에서 title 를 제외한 모든 필드를 제외하고 score라는 필드를 추가합니다.

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'index': 'synonyms-tutorial',
    9 'text': {
    10 'path': 'title',
    11 'query': 'automobile',
    12 'synonyms': 'transportSynonyms'
    13 }
    14 }
    15 },
    16 {
    17 '$limit': 10
    18 },
    19 {
    20 '$project': {
    21 '_id': 0,
    22 'title': 1,
    23 'score': {
    24 '$meta': 'searchScore'
    25 }
    26 }
    27 }
    28])
    29
    30for i in result:
    31 print(i)
  3. 샘플을 실행하기 전에 <connection-string>을(를) Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다.

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

    python synonyms-equivalent-query.py
    {'title': 'Cars', 'score': 4.197734832763672}
    {'title': 'Planes, Trains & Automobiles', 'score': 3.8511905670166016}
    {'title': 'Car Wash', 'score': 3.39473032951355}
    {'title': 'Used Cars', 'score': 3.39473032951355}
    {'title': 'Blue Car', 'score': 3.39473032951355}
    {'title': 'Cars 2', 'score': 3.39473032951355}
    {'title': 'Stealing Cars', 'score': 3.39473032951355}
    {'title': 'Cop Car', 'score': 3.39473032951355}
    {'title': 'The Cars That Eat People', 'score': 2.8496146202087402}
    {'title': 'Khrustalyov, My Car!', 'score': 2.8496146202087402}

    쿼리 용어가 automobile인 경우에도 automobile을(를) 이름이 컬렉션에 대한 인덱스에 지정된 sample_synonyms인 동의어 소스 컬렉션에서 car, vehicle, automobile의 동의어로 구성했기 때문에 title 필드에 carautomobile이(가) 포함된 영화가 Atlas Search 결과에 포함됩니다. Atlas Search는 carvehicle 단어를 검색할 때 동일한 결과를 반환합니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle 중 하나로 바꾸고 쿼리를 실행합니다.

  1. synonyms-explicit-query.py이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색하는 단계입니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'index': 'synonyms-tutorial',
    9 'text': {
    10 'path': 'title',
    11 'query': 'boat',
    12 'synonyms': 'transportSynonyms'
    13 }
    14 }
    15 },
    16 {
    17 '$limit': 10
    18 },
    19 {
    20 '$project': {
    21 '_id': 0,
    22 'title': 1,
    23 'score': {
    24 '$meta': 'searchScore'
    25 }
    26 }
    27 }
    28])
    29
    30for i in result:
    31 print(i)
  3. 샘플을 실행하기 전에 <connection-string>을(를) Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다.

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

    python synonyms-explicit-query.py
    {'title': 'Vessel', 'score': 5.373150825500488}
    {'title': 'Boats', 'score': 4.589139938354492}
    {'title': 'And the Ship Sails On', 'score': 4.3452959060668945}
    {'title': 'Broken Vessels', 'score': 4.3452959060668945}
    {'title': 'Sailing to Paradise', 'score': 4.3452959060668945}
    {'title': 'Boat People', 'score': 3.711261749267578}
    {'title': 'Boat Trip', 'score': 3.711261749267578}
    {'title': 'Three Men in a Boat', 'score': 3.1153182983398438}
    {'title': 'The Glass Bottom Boat', 'score': 3.1153182983398438}
    {'title': 'Jack Goes Boating', 'score': 3.1153182983398438}

    title 필드에 boat, vessel, sail이 있는 영화가 Atlas Search 결과에 포함됩니다. 이는 컬렉션의 인덱스에 지정된 sample_synonyms라는 동의어 소스 컬렉션에서 boat, vessel, sailboat 동의어로 구성했기 때문입니다.

    Atlas Search는 결과에서 vessel 단어를 검색한 경우에만 다음 문서를 반환합니다.

    { "title" : "Vessel", "score" : 5.373150825500488 }
    { "title" : "Broken Vessels", "score" : 4.3452959060668945 }

    Atlas Search는 title 필드에 boat 또는 sail이 포함된 문서를 결과에 포함하지 않습니다. 이는 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 이를 테스트하려면 위 쿼리의 query 필드 값을 vessel로 바꾸고 쿼리를 다시 실행합니다.

    마찬가지로, Atlas Search는 sail 검색어에 대한 검색 결과에서만 다음 문서를 반환합니다.

    { "title" : "And the Ship Sails On", "score" : 4.3452959060668945 }
    { "title" : "Sailing to Paradise", "score" : 4.3452959060668945 }

    Atlas Search는 결과에서 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 이는 우리가 synonyms 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 설정하지 않았기 때문입니다. 이 예시를 테스트하려면 위의 쿼리에서 query 필드의 값을 sail로 바꾼 후 쿼리를 다시 실행해 보세요.

2

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

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

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

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

Atlas Search 쿼리 결과는 동의어 소스 컬렉션에 정의된 단어 매핑 유형에 따라 달라집니다.

  1. synonyms-equivalent-query.py이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 automobile 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 automobile의 동의어로 구성된 단어를 검색하는 단계입니다. 쿼리는 attire 단어에 대한 title 필드도 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 쿼리 단어 attire의 동의어로 구성된 단어를 검색합니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'index': 'synonyms-tutorial',
    9 'compound': {
    10 'should': [
    11 {
    12 'text': {
    13 'path': 'title',
    14 'query': 'automobile',
    15 'synonyms': 'transportSynonyms'
    16 }
    17 }, {
    18 'text': {
    19 'path': 'title',
    20 'query': 'attire',
    21 'synonyms': 'attireSynonyms'
    22 }
    23 }
    24 ]
    25 }
    26 }
    27 }, {
    28 '$limit': 10
    29 }, {
    30 '$project': {
    31 '_id': 0,
    32 'title': 1,
    33 'score': {
    34 '$meta': 'searchScore'
    35 }
    36 }
    37 }
    38])
    39
    40for i in result:
    41 print(i)
  3. 샘플을 실행하기 전에 <connection-string>을(를) Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다.

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

    python synonyms-equivalent-query.py
    {'title': 'The Dress', 'score': 4.812004089355469}
    {'title': 'Cars', 'score': 4.197734832763672}
    {'title': 'Dressed to Kill', 'score': 3.891493320465088}
    {'title': '27 Dresses', 'score': 3.891493320465088}
    {'title': 'Planes, Trains & Automobiles', 'score': 3.8511905670166016}
    {'title': 'Car Wash', 'score': 3.39473032951355}
    {'title': 'Used Cars', 'score': 3.39473032951355}
    {'title': 'Blue Car', 'score': 3.39473032951355}
    {'title': 'Cars 2', 'score': 3.39473032951355}
    {'title': 'Stealing Cars', 'score': 3.39473032951355}

    Atlas Search 결과에는 두 검색어에 대한 문서가 모두 포함되어 있습니다. 결과에는 쿼리 용어 automobile에 대하여 title 필드에 car이(가) 포함된 영화가 포함됩니다. 이는 transport_synonyms 동의어 소스 컬렉션에서 automobile을(를) car, vehicleautomobile의 동의어로 구성했기 때문입니다. 결과에는 쿼리 용어 attire에 대하여 제목 필드에 dress이(가) 포함된 영화도 포함됩니다. 이는 attire_synonyms 동의어 소스 컬렉션에서 attire을(를) dress, apparelattire의 동의어로 구성했기 때문입니다.

    Atlas Search는 transport_synonyms 소스 컬렉션에서 car 또는 vehicle을(를) 검색하고 attire_synonyms 소스 컬렉션에서 dress 또는 apparel을(를) 검색할 때 동일한 결과를 반환합니다. 이 예시를 테스트하려면 위 쿼리의 query 필드 값을 car 또는 vehicle(으)로 바꾸고 위 쿼리의 query 필드 값을 dress 또는 apparel(으)로 바꾼 다음 쿼리를 다시 실행합니다.

  1. synonyms-explicit-query.py이라는 파일을 만듭니다.

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

    코드 예시에는 다음 단계가 포함되어 있습니다.

    • $search 단계는 title 필드에서 boat 단어를 검색하고 transportSynonyms 동의어 매핑 정의를 사용하여 transport_synonyms 동의어 소스 컬렉션에서 쿼리 단어 boat의 동의어로 구성된 단어를 검색하는 단계입니다. 쿼리는 hat 단어에 대한 title 필드도 검색하고 attireSynonyms 동의어 매핑 정의를 사용하여 attire_synonyms 동의어 소스 컬렉션에서 쿼리 단어 hat의 동의어로 구성된 단어를 검색합니다.

    • $limit 출력을 결과 10개로 제한하는 [$limit] 단계

    • title을 제외한 모든 필드를 제외하고 score라는 필드를 추가하려면 $project 단계를 수행합니다.

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'index': 'synonyms-tutorial',
    9 'compound': {
    10 'should': [
    11 {
    12 'text': {
    13 'path': 'title',
    14 'query': 'boat',
    15 'synonyms': 'transportSynonyms'
    16 }
    17 }, {
    18 'text': {
    19 'path': 'title',
    20 'query': 'hat',
    21 'synonyms': 'attireSynonyms'
    22 }
    23 }
    24 ]
    25 }
    26 }
    27 }, {
    28 '$limit': 10
    29 }, {
    30 '$project': {
    31 '_id': 0,
    32 'title': 1,
    33 'score': {
    34 '$meta': 'searchScore'
    35 }
    36 }
    37 }
    38])
    39
    40for i in result:
    41 print(i)
  3. 샘플을 실행하기 전에 <connection-string>을(를) Atlas 연결 문자열로 바꿉니다. 연결 문자열에는 데이터베이스 사용자의 자격 증명이 포함되어 있어야 합니다.

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

    python synonyms-explicit-query.py
    {'title': 'Fedora', 'score': 5.673145294189453}
    {'title': 'Vessel', 'score': 5.373150825500488}
    {'title': 'Boats', 'score': 4.589139938354492}
    {'title': 'And the Ship Sails On', 'score': 4.3452959060668945}
    {'title': 'Broken Vessels', 'score': 4.3452959060668945}
    {'title': 'Sailing to Paradise', 'score': 4.3452959060668945}
    {'title': 'Top Hat', 'score': 4.066137313842773}
    {'title': 'A Hatful of Rain', 'score': 4.066137313842773}
    {'title': 'Boat People', 'score': 3.711261749267578}
    {'title': 'Boat Trip', 'score': 3.711261749267578}

    Atlas Search 결과에 두 검색어에 대한 문서가 모두 포함됩니다. 검색어 boat에 대해 title 필드에 vessel, boat, sail이 있는 영화가 결과에 포함됩니다. 이는 transport_synonyms라는 동의어 소스 컬렉션에서 boatboat, vessel, sail의 동의어로 구성했기 때문입니다.

    Atlas Search는 vessel 용어 검색 결과에서 title 필드에 boat 또는 sail이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 vesselboat 또는 sail의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 sail 용어 검색 결과의 title 필드에 boat 또는 vessel이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 sailboat 또는 vessel의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 vessel 또는 sail로 바꾸고 쿼리를 다시 실행하세요.

    검색어 hat에 대하여 제목 필드에 fedorahat이 있는 동영상도 결과에 포함됩니다. attire_synonyms라는 동의어 소스 컬렉션에서 hathat, fedora, headgear 동의어로 구성했기 때문입니다.

    Atlas Search는 headgear 용어 검색 결과에서 title 필드에 hat 또는 fedora이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 headgearhat 또는 fedora의 동의어로 구성하지 않았기 때문입니다. 마찬가지로, Atlas Search는 fedora 용어 검색 결과의 title 필드에 hat 또는 headgear이 포함된 문서를 제외합니다. 동의어 소스 컬렉션에서 fedorahat 또는 headgear의 동의어로 구성하지 않았기 때문입니다. 이러한 예를 테스트하려면 위 쿼리의 query 필드 값을 fedora 또는 headgear로 바꾸고 쿼리를 다시 실행하세요.

돌아가기

하이브리드 검색

이 페이지의 내용