Docs Menu

벡터 검색을 위해 필드를 인덱싱하는 방법

vectorSearch 유형을 사용하면 $vectorSearch 쿼리를 실행하기 위해 필드를 인덱싱할 수 있습니다. 쿼리하려는 벡터 임베딩의 인덱스와 데이터를 사전 필터링하는 데 사용할 부울, 날짜, objectId, 숫자, string 또는 UUID 값을 정의할 수 있습니다. 데이터를 필터링하면 시맨틱 검색의 범위를 좁히고 멀티테넌트 환경과 같이 특정 벡터 임베딩이 비교 대상으로 고려되지 않도록 하는 데 유용합니다.

Atlas UI, Atlas 관리 API, Atlas CLI, mongosh 또는 지원되는 MongoDB 드라이버를 사용하여 Atlas Vector Search 인덱스를 만들 수 있습니다.

참고

더 이상 사용되지 않는 knnBeta 연산자를 사용하여 vectorSearch 유형 인덱스 정의로 인덱싱된 필드를 쿼리할 수 없습니다.

vectorSearch 유형 인덱스 정의에서는 단일 요소로만 배열을 인덱싱할 수 있습니다. 문서 배열 내의 필드나 객체 배열 내의 필드를 인덱싱할 수 없습니다. 점 표기법을 사용하여 문서 내부의 필드를 인덱싱할 수 있습니다.

임베딩을 인덱싱 전에 Atlas cluster 에 효율적으로 저장 하려면 임베딩을 하위 유형이 float32, int1 또는 int8BSON BinData 벡터로 변환하는 것이 좋습니다. 자세한 학습 은 임베딩을 BSON 벡터로 변환하는 방법을 참조하세요.

참고

다음에 대한 Atlas Vector Search 지원 Preview 기능 으로 사용할 수 있습니다.

  • 하위 유형이 있는 BSON BinData 벡터를 int1 수집합니다.

  • 자동 스칼라 양자화.

  • 자동 이진 양자화.

Atlas Vector Search 인덱스를 사용할 때, Atlas 클러스터의 유휴 노드에서 리소스 소비가 증가할 수 있습니다. 이는 Atlas Vector Search에 필수적인 다양한 작업을 수행하는 기본 mongot 프로세스 때문입니다. 유휴 노드에서의 CPU 사용률은 인덱스의 수, 복잡성, 크기에 따라 달라질 수 있습니다.

Atlas UI,, Atlas CLI, Atlas Administration API 및 다음 MongoDBmongosh드라이버를 통해 Atlas Vector Search 인덱스를 생성하고 관리 할 수 있습니다.

MongoDB 드라이버
버전

1.28.0 이상

3.11.0 이상

3.1.0 이상

1.16.0 이상

5.2.0 이상

5.2.0 이상

6.6.0 이상

1.20.0 이상

4.7 이상

3.1.0 이상

5.2.0 이상

다음 구문은 vectorSearch 인덱스 유형을 정의합니다.

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": "<field-to-index>",
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary"
9 },
10 {
11 "type": "filter",
12 "path": "<field-to-index>"
13 },
14 ...
15 ]
16}

Atlas Vector Search 인덱스 정의에는 다음 필드가 사용됩니다.

옵션
유형
필요성
목적

fields

문서 배열

필수 사항

벡터 및 필터 필드를 인덱싱하려면 문서당 하나씩 지정합니다. 최소한 하나의 문서에 벡터 필드에 대한 필드 정의가 포함되어야 합니다. 선택적으로 부울, 날짜, 숫자, objectId, 문자열 및 UUID 필드를 문서당 하나씩 인덱싱하여 데이터를 사전 필터링할 수 있습니다.

fields.type

문자열

필수 사항

$vectorSearch 필드를 인덱싱하는 데 사용할 필드 유형입니다. 다음 값 중 하나를 지정할 수 있습니다.

  • vector - 벡터 임베딩이 포함된 필드의 경우.

  • filter - 부울, 날짜, objectId, 숫자, 문자열 또는 UUID 값이 포함된 필드의 경우.

fields.path

문자열

필수 사항

인덱싱할 필드의 이름입니다. 중첩된 필드의 경우 점 표기법을 사용하여 임베디드 필드의 경로를 지정합니다.

두 개의 연속된 점이나 점으로 끝나는 필드 이름은 인덱싱할 수 없습니다. 예를 들어 Atlas Vector Search는 foo..bar 또는 foo_bar. 필드 이름의 인덱싱을 지원하지 않습니다.

fields.numDimensions

int

필수 사항

Atlas Vector Search 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. 8192보다 작거나 같은 값을 지정해야 합니다. BinData 또는 양자화된 벡터를 인덱싱 하려면 값이 다음 중 하나여야 합니다.

  • 수집을 위한 int8 벡터의 경우 1 ~ 8192.

  • 수집을 위한 int1 벡터에 대한 8 의 배수입니다.

  • binData(float32) 의 경우 1 ~ 8192, 자동 스칼라 양자화의 경우 array(float32) 벡터.

  • 자동 이진 양자화를 위한 binData(float32)array(float32) 벡터에 대한 8 의 배수입니다.

이 필드 vector 유형 필드에 대해서만 설정하다 수 있습니다.

fields.similarity

문자열

필수 사항

상위 K-최근접 이웃을 검색하는 데 사용하는 벡터 유사성 함수입니다. 이 필드는 vector 유형 필드에 대해서만 설정할 수 있습니다. 값은 다음 중 하나일 수 있습니다.

  • euclidean - 벡터의 끝과 끝 사이의 거리를 측정합니다.

  • cosine - 벡터 사이의 각도를 기준으로 유사성을 측정합니다.

  • dotProduct - cosine와(과) 같이 유사성을 측정하지만 벡터의 크기를 고려합니다.

자세한 학습 유사성 함수 정보를 참조하세요.

fields.quantization

문자열

옵션

벡터에 대한 자동 벡터 양자화 유형입니다. 벡터에 적용 할 양자화 유형을 지정할 수 있습니다. 임베딩이 float 또는 double 벡터인 경우에만 이 설정을 사용합니다. 값은 다음 중 하나일 수 있습니다.

  • none - 벡터 임베딩에 대한 자동 양자화를 수행하지 않음을 나타냅니다. 수집을 위해 사전에 양자화된 벡터가 있는 경우 이 설정을 사용합니다. 생략하면 이 값이 기본값 입니다.

  • scalar - 값을 1 바이트 정수로 변환하는 스칼라 양자화를 나타냅니다.

  • binary - 값을 단일 비트로 변환하는 이진 양자화를 나타냅니다. 이 양자화를 사용하려면 numDimensions 이 8의 배수여야 합니다.

정밀도가 중요한 경우 binary 대신 none 또는 scalar 를 선택합니다.

자세한 학습 은 벡터 양자화를 참조하세요.

인덱스 정의의 vector 필드에는 다음 유형 중 하나의 숫자 배열이 포함되어야 합니다.

  • BSON double

  • BSON BinData vector 하위 유형 float32

  • BSON BinData vector 하위 유형 int1

  • BSON BinData vector 하위 유형 int8

참고

데이터에 대해 하위 유형이 float32 int1 또는 인 BSON BinData 벡터를 생성하는 방법에 대해 int8 자세히 학습 사전 양자화된 벡터를 수집하는 방법을 참조하세요.

다음에 대한 Atlas Vector Search 지원 Preview 기능 으로 사용할 수 있습니다.

  • 하위 유형이 있는 BSON BinData 벡터를 int1 수집합니다.

  • 자동 스칼라 양자화.

  • 자동 이진 양자화.

벡터 필드를 fields 배열 내에서 vector 유형으로 인덱싱해야 합니다.

다음 구문은 vector 필드 유형을 정의합니다.

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": <field-to-index>,
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary"
9 },
10 ...
11 ]
12}

Atlas Vector Search 다음과 같은 유사성 함수를 지원합니다.

  • euclidean - 벡터의 끝과 끝 사이의 거리를 측정합니다. 이 값을 사용하면 다양한 차원을 기반으로 유사성을 측정할 수 있습니다. 자세한 내용은 유클리드를 참조하세요.

  • cosine - 벡터 사이의 각도를 기준으로 유사성을 측정합니다. 이 값을 사용하면 크기에 따라 배율이 조정되지 않는 유사성을 측정할 수 있습니다. cosine에는 크기가 0인 벡터를 사용할 수 없습니다. 코사인 유사성을 측정하려면 벡터를 정규화하고 대신 dotProduct 를 사용하는 것이 좋습니다.

  • dotProduct - cosine처럼 유사성을 측정하지만 벡터의 크기를 고려합니다. 크기를 정규화하면 유사성 측정에서 cosinedotProduct은(는) 거의 동일합니다.

    dotProduct를 사용하려면 인덱스 타임 및 쿼리 타임에 벡터를 단위 길이로 정규화해야 합니다.

다음 표는 다양한 유형에 대한 유사성 함수를 보여줍니다.

벡터 임베딩 유형
euclidean
cosine
dotProduct

binData(int1)

binData(int8)

binData(float32)

array(float32)

벡터 수집용입니다.

자동 스칼라 또는 이진 양자화에 사용됩니다.

최상의 성능을 위해 임베딩 모델을 확인하여 임베딩 모델의 교육 프로세스 에 맞는 유사성 함수를 확인하세요. 지침 이 없는 경우 dotProduct(으)로 시작하세요. fields.similaritydotProduct 값으로 설정하면 각도와 크기를 기준으로 유사성을 효율적으로 측정할 수 있습니다. dotProductcosine 보다 계산 리소스를 덜 소비하며 벡터의 길이가 단위일 때 효율적입니다. 그러나 벡터가 정규화되지 않은 경우 euclidean 거리 및 cosine 유사성에 대한 샘플 쿼리 결과의 유사성 점수를 평가하여 어느 것이 합리적인 결과에 해당하는지 결정합니다.

선택적으로 부울, 날짜, 숫자, ObjectId, 문자열 및 UUID 필드를 인덱스 데이터를 사전 필터링할 수 있습니다. 데이터 필터링은 시맨틱 검색 의 범위를 좁히고 모든 벡터가 비교 대상으로 고려되지 않도록 하는 데 유용합니다. 유사성 비교를 실행 문서 수를 줄여 쿼리 지연 시간 줄이고 검색 결과의 정확성을 높일 수 있습니다.

fields 배열 내부의 filter 유형을 사용하여 필터하다 하려는 필드를 인덱스 해야 합니다.

다음 구문은 filter 필드 유형을 정의합니다.

1{
2 "fields":[
3 {
4 "type": "vector",
5 ...
6 },
7 {
8 "type": "filter",
9 "path": "<field-to-index>"
10 },
11 ...
12 ]
13}

참고

데이터를 사전 필터링해도 Atlas Vector Search가 $vectorSearch 쿼리에 대해 $vectorSearchScore를 사용하여 반환하는 점수에는 영향을 주지 않습니다.

Atlas UI, Atlas 관리 API, Atlas CLI, mongosh, 또는 지원되는 MongoDB 드라이버를 통해 Atlas 클러스터의 다른 데이터와 함께 모든 종류의 데이터에 대해 길이가 8192 차원 이하인 벡터 임베딩이 포함된 모든 컬렉션에 대한 Atlas Vector Search 인덱스를 만들 수 있습니다.

Atlas Vector Search 인덱스를 생성하려면 다음 전제 조건을 갖춘 Atlas 클러스터가 있어야 합니다.

  • MongoDB 버전 6.0.11, 7.0.2 이상

  • Atlas Vector Search 인덱스를 생성할 컬렉션입니다.

참고

mongosh 명령 또는 운전자 헬퍼 메서드를 사용하여 모든 Atlas cluster 계층에서 Atlas Vector Search 인덱스를 생성할 수 있습니다. 지원되는 운전자 버전 목록은 지원되는 클라이언트를 참조하세요.

Atlas Vector Search 인덱스를 생성하고 관리하려면 Project Data Access Admin 이상의 역할이 있어야 합니다.

초과하여 만들 수 없습니다.

  • M0 클러스터의 인덱스 3개.

  • M2 클러스터의 인덱스 5개.

  • M5 클러스터의 인덱스 10개.

  • Flex 클러스터의 인덱스 10개.

단일 M10+ 클러스터 에 2,500 이하의 검색 인덱스를 생성하는 것이 좋습니다.


언어 선택 드롭다운 메뉴를 사용하여 인덱스를 만드는 데 사용할 클라이언트를 선택합니다.


참고

이 절차에는 sample_mflix 데이터베이스 의 embedded_movies 컬렉션 에 대한 인덱스 정의 예제가 포함되어 있습니다. 클러스터 에 샘플 데이터를 로드하고 이 컬렉션 에 대한 예시 Atlas Vector Search 인덱스를 $vectorSearch 만들면 이 컬렉션 에 대해 샘플 쿼리를 실행 수 있습니다. 실행 수 있는 샘플 쿼리에 대해 자세히 학습 $vectorSearch 예제를 참조하세요.

Atlas 관리 API를 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 생성하려면 필수 파라미터와 함께 Atlas Search indexes 엔드포인트에 POST 요청을 보냅니다.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "<name-of-database>",
9 "collectionName": "<name-of-collection>",
10 "type": "vectorSearch",
11 "name": "<index-name>",
12 "definition": {
13 "fields":[
14 {
15 "type": "vector",
16 "path": <field-to-index>,
17 "numDimensions": <number-of-dimensions>,
18 "similarity": "euclidean | cosine | dotProduct"
19 },
20 {
21 "type": "filter",
22 "path": "<field-to-index>"
23 },
24 ...
25 }
26 ]
27 }'

To learn more about the syntax and parameters for the endpoint, see 1개의 Atlas Search 인덱스 만들기.

예시

다음 인덱스 정의는 plot_embedding 필드를 vector 유형으로 인덱싱합니다. plot_embedding 필드에는 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536 벡터 차원을 지정하고 dotProduct 함수를 사용하여 유사성을 측정합니다.

다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드만 인덱싱합니다.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "sample_mflix",
9 "collectionName": "embedded_movies",
10 "type": "vectorSearch",
11 "name": "vector_index",
12 "definition: {
13 "fields":[
14 {
15 "type": "vector",
16 "path": "plot_embedding",
17 "numDimensions": 1536,
18 "similarity": "dotProduct"
19 }
20 ]
21 }
22 }'

이 인덱스 정의는 다음 필드를 인덱싱합니다:

  • 데이터를 사전 필터링하기 위한 문자열 필드(genres) 및 숫자 필드(year).

  • 사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(plot_embedding)입니다.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2--header "Accept: application/json" \
3--header "Content-Type: application/json" \
4--include \
5--request POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \
6--data '
7 {
8 "database": "sample_mflix",
9 "collectionName": "embedded_movies",
10 "type": "vectorSearch",
11 "name": "vector_index",
12 "definition: {
13 "fields":[
14 {
15 "type": "vector",
16 "path": "plot_embedding",
17 "numDimensions": 1536,
18 "similarity": "dotProduct"
19 },
20 {
21 "type": "filter",
22 "path": "genres"
23 },
24 {
25 "type": "filter",
26 "path": "year"
27 }
28 ]
29 }
30 }'

Atlas CLI v1.14.3 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 생성하려면 다음 단계를 수행하세요.

1

인덱스 정의는 다음 형식과 유사해야 합니다.

1{
2 "database": "<name-of-database>",
3 "collectionName": "<name-of-collection>",
4 "type": "vectorSearch",
5 "name": "<index-name>",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "<field-to-index>",
10 "numDimensions": <number-of-dimensions>,
11 "similarity": "euclidean | cosine | dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "<field-to-index>"
16 },
17 ...
18 ]
19}

예시

vector-index.json이라는 파일을 만듭니다.

2

<name-of-database>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<name-of-collection>

인덱스를 생성하려는 컬렉션입니다.

<index-name>

인덱스의 이름입니다. 인덱스 이름을 생략하는 경우 Atlas Vector Search는 인덱스 이름을 vector_index로 지정합니다.

<number-of-dimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<field-to-index>

인덱싱할 벡터 및 필터 필드입니다.

예시

다음 인덱스 정의를 복사하여 vector-index.json 파일 에 붙여넣습니다. 다음 인덱스 정의는 Atlas Vector Search 인덱스 에서 plot_embedding 필드 vector 유형으로, genresyear 필드를 filter 유형으로 인덱싱합니다. plot_embedding 필드 에는 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536 벡터 차원을 지정하고 dotProduct 함수를 사용하여 유사성을 측정합니다.

다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드만 인덱싱합니다.

1{
2 "database": "sample_mflix",
3 "collectionName": "embedded_movies",
4 "type": "vectorSearch",
5 "name": "vector_index",
6 "fields": [
7 {
8 "type": "vector",
9 "path": "plot_embedding",
10 "numDimensions": 1536,
11 "similarity": "dotProduct"
12 }
13 ]
14}

이 인덱스 정의는 다음 필드를 인덱싱합니다:

  • 데이터를 사전 필터링하기 위한 문자열 필드(genres) 및 숫자 필드(year).

  • 사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(plot_embedding)입니다.

1{
2 "database": "sample_mflix",
3 "collectionName": "embedded_movies",
4 "type": "vectorSearch",
5 "name": "vector_index",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "plot_embedding",
10 "numDimensions": 1536,
11 "similarity": "dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "genres"
16 },
17 {
18 "type": "filter",
19 "path": "year"
20 }
21 ]
22}
3
atlas clusters search indexes create --clusterName [cluster_name] --file [vector_index].json

명령에서 다음 자리 표시자 값을 바꿉니다.

  • cluster_name은(는) 인덱스를 만들려는 컬렉션이 포함된 Atlas 클러스터의 이름입니다.

  • vector_index은(는) Atlas Vector Search 인덱스에 대한 인덱스 정의가 포함된 JSON 파일의 이름입니다.

예시

atlas clusters search indexes create --clusterName [cluster_name] --file vector-index.json

명령 구문 및 매개변수에 대한 자세한 내용은 Atlas CLI 문서에서 Atlas 클러스터 검색 인덱스 생성 명령을 참조하세요.

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

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

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

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

2

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

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

    참고

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

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

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

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

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

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

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

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

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

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

3
4

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

Search Type

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

Index Name and Data Source

다음 정보를 지정합니다.

  • Index Name: vector_index는 기본값 인덱스 이름입니다. 인덱스 이름은 인덱스 유형에 관계없이 네임스페이스 내에서 고유해야 합니다. 이 컬렉션에 이름이 vector_index인 인덱스가 이미 있는 경우 다른 이름을 입력하세요.

  • Database and Collection:

    • 인덱스를 생성할 데이터베이스를 선택합니다. 예를 들어 sample_mflix입니다.

    • 인덱스를 생성할 컬렉션을 선택합니다. 예를 들어 embedded_movies입니다.

Configuration Method

For a guided experience, select Visual Editor.

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

Atlas는 벡터 임베딩을 포함하는 필드와 해당 차원을 자동으로 감지하고 최대 세 개의 벡터 필드를 미리 채웁니다. 인덱스를 구성하려면 다음을 수행합니다.

  1. 필요한 경우 Path 드롭다운에서 인덱싱할 벡터 필드를 선택합니다.

    Add Another Field를 선택하여 추가 필드를 인덱싱합니다.

  2. Similarity Method 드롭다운 메뉴에서 인덱싱된 각 필드에 대한 유사성 메서드를 지정합니다.

  3. (선택 사항) Advanced를 클릭하고 드롭다운 메뉴에서 Scalar 또는 Binary 양자화를 선택하여 필드의 임베딩을 자동으로 양자화합니다.

  4. (선택 사항) Filter Field 섹션에서 데이터를 필터링할 수 있도록 컬렉션의 다른 필드를 지정합니다.

To learn more about the Atlas Vector Search index settings, see 벡터 검색을 위해 필드를 인덱싱하는 방법.

예시

embedded_movies 컬렉션에 대해 plot_embedding 필드가 표시됩니다.

인덱스를 구성하려면 Similarity Method 드롭다운에서 Dot Product를 선택합니다.

이 인덱스 정의는 벡터 임베딩 필드 (plot_embedding)만 인덱싱하여 벡터 검색을 수행합니다.

embedded_movies 컬렉션에 대해 plot_embedding 필드가 표시됩니다.

인덱스를 구성하려면 다음을 수행합니다.

  1. Similarity Method 드롭다운 메뉴에서 Dot Product을(를) 선택합니다.

  2. Advanced를 클릭한 후 드롭다운 메뉴에서 Scalar 양자화를 선택합니다.

  3. Filter Field 섹션에서 데이터를 필터링하기 위해 genresyear 필드를 지정합니다.

이 인덱스 정의는 다음 필드를 인덱싱합니다:

  • 데이터를 사전 필터링하기 위한 문자열 필드(genres) 및 숫자 필드(year).

  • 사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(plot_embedding)입니다.

또한 임베딩의 효율적인 처리를 위해 자동 양자화(scalar)를 활성화합니다.

Atlas Vector Search 인덱스는 다음 예시와 유사합니다.

1{
2 "fields":[
3 {
4 "type": "vector",
5 "path": <field-to-index>,
6 "numDimensions": <number-of-dimensions>,
7 "similarity": "euclidean | cosine | dotProduct",
8 "quantization": "none | scalar | binary"
9 },
10 {
11 "type": "filter",
12 "path": "<field-to-index>"
13 },
14 ...
15 ]
16}

To learn more about the fields in the index, see 벡터 검색을 위해 필드를 인덱싱하는 방법.

예시

다음 인덱스 정의는 plot_embedding 필드를 vector 유형으로 인덱싱합니다. plot_embedding 필드에는 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536 벡터 차원을 지정하고 dotProduct 함수를 사용하여 유사성을 측정합니다.

다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드만 인덱싱합니다.

1{
2 "fields": [{
3 "type": "vector",
4 "path": "plot_embedding",
5 "numDimensions": 1536,
6 "similarity": "dotProduct"
7 }]
8}

이 인덱스 정의는 다음 필드를 인덱싱합니다:

  • 데이터를 사전 필터링하기 위한 문자열 필드(genres) 및 숫자 필드(year).

  • 사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(plot_embedding)입니다.

또한 임베딩의 효율적인 처리를 위해 자동 양자화(scalar)를 활성화합니다.

1{
2 "fields": [{
3 "type": "vector",
4 "path": "plot_embedding",
5 "numDimensions": 1536,
6 "similarity": "dotProduct",
7 "quantization": "scalar"
8 },
9 {
10 "type": "filter",
11 "path": "genres"
12 },
13 {
14 "type": "filter",
15 "path": "year"
16 }]
17}
6
7

Atlas에서 인덱스가 작성 중임을 알려주는 모달 창이 표시됩니다.

8
9

새로 생성된 인덱스가 Atlas Search 탭에 표시됩니다. 인덱스가 생성되는 동안 Status 필드는 Build in Progress로 표시됩니다. 인덱스 생성이 완료되면 Status 필드에 Active가 표시됩니다.

참고

컬렉션이 클수록 인덱스를 생성하는 데 시간이 더 오래 걸립니다. 인덱스 빌드가 완료되면 이메일 알림을 받게 됩니다.

mongosh v2.1.2 이상을 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 만들려면 다음 단계를 수행하세요.

1

To learn more, see Connect via mongosh.

2

예시

use sample_mflix
switched to db sample_mflix
3

db.collection.createSearchIndex() 메서드의 구문은 다음과 같습니다.

1db.<collectionName>.createSearchIndex(
2 "<index-name>",
3 "vectorSearch", //index type
4 {
5 fields: [
6 {
7 "type": "vector",
8 "numDimensions": <number-of-dimensions>,
9 "path": "<field-to-index>",
10 "similarity": "euclidean | cosine | dotProduct"
11 },
12 {
13 "type": "filter",
14 "path": "<field-to-index>"
15 },
16 ...
17 ]
18 }
19);

예시

다음 인덱스 정의는 plot_embedding 필드를 vector 유형으로 인덱싱합니다. plot_embedding 필드에는 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536 벡터 차원을 지정하고 dotProduct 함수를 사용하여 유사성을 측정합니다.

다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드만 인덱싱합니다.

1db.embedded_movies.createSearchIndex(
2 "vector_index",
3 "vectorSearch",
4 {
5 "fields": [
6 {
7 "type": "vector",
8 "path": "plot_embedding",
9 "numDimensions": 1536,
10 "similarity": "dotProduct",
11 "quantization": "scalar"
12 }
13 ]
14 }
15);

이 인덱스 정의는 다음 필드를 인덱싱합니다:

  • 데이터를 사전 필터링하기 위한 문자열 필드(genres) 및 숫자 필드(year).

  • 사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(plot_embedding)입니다.

1db.embedded_movies.createSearchIndex(
2 "vector_index",
3 "vectorSearch",
4 {
5 "fields": [
6 {
7 "type": "vector",
8 "path": "plot_embedding",
9 "numDimensions": 1536,
10 "similarity": "dotProduct"
11 },
12 {
13 "type": "filter",
14 "path": "genres"
15 },
16 {
17 "type": "filter",
18 "path": "year"
19 }
20 ]
21 }
22);

C# 드라이버 v3.1.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 생성하려면 다음 단계를 수행하세요.

1
1using MongoDB.Bson;
2using MongoDB.Driver;
3using System;
4using System.Threading;
5
6// Connect to your Atlas deployment
7private const string MongoConnectionString = "<connectionString>";
8var client = new MongoClient(MongoConnectionString);
9
10// Access your database and collection
11var database = client.GetDatabase("<databaseName>");
12var collection = database.GetCollection<BsonDocument>("<collectionName>");
13
14// Create your index model, then create the search index
15var name = "<indexName>";
16var type = SearchIndexType.VectorSearch;
17
18var definition = new BsonDocument
19{
20 { "fields", new BsonArray
21 {
22 new BsonDocument
23 {
24 { "type", "vector" },
25 { "path", "<fieldToIndex>" },
26 { "numDimensions", <numberOfDimensions> },
27 { "similarity", "euclidean | cosine | dotProduct" }
28 }
29 }
30 }
31};
32
33var model = new CreateSearchIndexModel(name, type, definition);
34
35var searchIndexView = collection.SearchIndexes;
36searchIndexView.CreateOne(model);
37Console.WriteLine($"New search index named {name} is building.");
38
39// Wait for initial sync to complete
40Console.WriteLine("Polling to check if the index is ready. This may take up to a minute.");
41bool queryable = false;
42while (!queryable)
43{
44 var indexes = searchIndexView.List();
45 foreach (var index in indexes.ToEnumerable())
46 {
47 if (index["name"] == name)
48 {
49 queryable = index["queryable"].AsBoolean;
50 }
51 }
52 if (!queryable)
53 {
54 Thread.Sleep(5000);
55 }
56}
57Console.WriteLine($"{name} is ready for querying.");
1using MongoDB.Bson;
2using MongoDB.Driver;
3using System;
4using System.Threading;
5
6// Connect to your Atlas deployment
7private const string MongoConnectionString = "<connectionString>";
8var client = new MongoClient(MongoConnectionString);
9
10// Access your database and collection
11var database = client.GetDatabase("<databaseName>");
12var collection = database.GetCollection<BsonDocument>("<collectionName>");
13
14// Create your index models and add them to an array
15var type = SearchIndexType.VectorSearch;
16
17var definitionOne = new BsonDocument
18{
19 { "fields", new BsonArray
20 {
21 new BsonDocument
22 {
23 { "type", "vector" },
24 { "path", "<fieldToIndex>" },
25 { "numDimensions", <numberOfDimensions> },
26 { "similarity", "euclidean | cosine | dotProduct" }
27 }
28 }
29 }
30};
31var modelOne = new CreateSearchIndexModel("<indexName>", type, definitionOne);
32
33var definitionTwo = new BsonDocument
34{
35 { "fields", new BsonArray
36 {
37 new BsonDocument
38 {
39 { "type", "vector" },
40 { "path", "<fieldToIndex>" },
41 { "numDimensions", <numberOfDimensions> },
42 { "similarity", "euclidean | cosine | dotProduct" }
43 }
44 }
45 }
46};
47var modelTwo = new CreateSearchIndexModel("<indexName>", type, definitionTwo);
48
49var models = new CreateSearchIndexModel[] { modelOne, modelTwo };
50
51// Create the search indexes
52var searchIndexView = collection.SearchIndexes;
53searchIndexView.CreateMany(models);
54
55Console.WriteLine($"New search indexes are building. This may take up to a minute.");

예시

IndexService.cs이라는 파일을 만듭니다.

2

<connectionString>

Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

<numberOfDimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<fieldToIndex>

인덱싱할 벡터 및 필터 필드입니다.

예시

다음을 복사하여 IndexService.cs 에 붙여넣고 <connectionString> 자리 표시자 값을 바꿉니다. 다음 인덱스 정의는 Atlas Vector Search 인덱스 에서 plot_embedding 필드 vector 유형으로, genresyear 필드를 filter 유형으로 인덱싱합니다. plot_embedding 필드 에는 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536 벡터 차원을 지정하고 dotProduct 함수를 사용하여 유사성을 측정합니다.

다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드(plot_embedding)만 인덱싱합니다.

1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5using System;
6using System.Threading;
7
8public class IndexService
9{
10 // Replace the placeholder with your Atlas connection string
11 private const string MongoConnectionString = "<connection-string>";
12 public void CreateVectorIndex()
13 {
14 try
15 {
16 // Connect to your Atlas cluster
17 var client = new MongoClient(MongoConnectionString);
18 var database = client.GetDatabase("sample_mflix");
19 var collection = database.GetCollection<BsonDocument>("embedded_movies");
20
21 var searchIndexView = collection.SearchIndexes;
22 var name = "vector_index";
23 var type = SearchIndexType.VectorSearch;
24
25 var definition = new BsonDocument
26 {
27 { "fields", new BsonArray
28 {
29 new BsonDocument
30 {
31 { "type", "vector" },
32 { "path", "plot_embedding" },
33 { "numDimensions", 1536 },
34 { "similarity", "dotProduct" },
35 { "quantization", "scalar" }
36 }
37 }
38 }
39 };
40
41 var model = new CreateSearchIndexModel(name, type, definition);
42
43 searchIndexView.CreateOne(model);
44 Console.WriteLine($"New search index named {name} is building.");
45
46 // Polling for index status
47 Console.WriteLine("Polling to check if the index is ready. This may take up to a minute.");
48 bool queryable = false;
49 while (!queryable)
50 {
51 var indexes = searchIndexView.List();
52 foreach (var index in indexes.ToEnumerable())
53 {
54 if (index["name"] == name)
55 {
56 queryable = index["queryable"].AsBoolean;
57 }
58 }
59 if (!queryable)
60 {
61 Thread.Sleep(5000);
62 }
63 }
64 Console.WriteLine($"{name} is ready for querying.");
65 }
66 catch (Exception e)
67 {
68 Console.WriteLine($"Exception: {e.Message}");
69 }
70 }
71}

이 인덱스 정의는 다음 필드를 인덱싱합니다:

  • 데이터를 사전 필터링하기 위한 문자열 필드(genres) 및 숫자 필드(year).

  • 사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(plot_embedding)입니다.

1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5using System;
6using System.Threading;
7
8public class IndexService
9{
10 // Replace the placeholder with your Atlas connection string
11 private const string MongoConnectionString = "<connection-string>";
12 public void CreateVectorIndex()
13 {
14 try
15 {
16 // Connect to your Atlas cluster
17 var client = new MongoClient(MongoConnectionString);
18 var database = client.GetDatabase("sample_mflix");
19 var collection = database.GetCollection<BsonDocument>("embedded_movies");
20
21 var searchIndexView = collection.SearchIndexes;
22 var name = "vector_index";
23 var type = SearchIndexType.VectorSearch;
24
25 var definition = new BsonDocument
26 {
27 { "fields", new BsonArray
28 {
29 new BsonDocument
30 {
31 { "type", "vector" },
32 { "path", "plot_embedding" },
33 { "numDimensions", 1536 },
34 { "similarity", "dotProduct" },
35 { "quantization", "scalar"}
36 },
37 new BsonDocument
38 {
39 {"type", "filter"},
40 {"path", "genres"}
41 },
42 new BsonDocument
43 {
44 {"type", "filter"},
45 {"path", "year"}
46 }
47 }
48 }
49 };
50
51 var model = new CreateSearchIndexModel(name, type, definition);
52
53 searchIndexView.CreateOne(model);
54 Console.WriteLine($"New search index named {name} is building.");
55
56 // Polling for index status
57 Console.WriteLine("Polling to check if the index is ready. This may take up to a minute.");
58 bool queryable = false;
59 while (!queryable)
60 {
61 var indexes = searchIndexView.List();
62 foreach (var index in indexes.ToEnumerable())
63 {
64 if (index["name"] == name)
65 {
66 queryable = index["queryable"].AsBoolean;
67 }
68 }
69 if (!queryable)
70 {
71 Thread.Sleep(5000);
72 }
73 }
74 Console.WriteLine($"{name} is ready for querying.");
75 }
76 catch (Exception e)
77 {
78 Console.WriteLine($"Exception: {e.Message}");
79 }
80 }
81}
3
using query_quick_start;
var indexService = new IndexService();
indexService.CreateVectorIndex();
4
dotnet run

MongoDB Go 드라이버 v2.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 생성하려면 다음 단계를 수행하세요.

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
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
13func main() {
14 ctx := context.Background()
15
16 // Replace the placeholder with your Atlas connection string
17 const uri = "<connectionString>"
18
19 // Connect to your Atlas cluster
20 clientOptions := options.Client().ApplyURI(uri)
21 client, err := mongo.Connect(clientOptions)
22 if err != nil {
23 log.Fatalf("failed to connect to the server: %v", err)
24 }
25 defer func() { _ = client.Disconnect(ctx) }()
26
27 // Set the namespace
28 coll := client.Database("<databaseName>").Collection("<collectionName>")
29
30 // Define the index details
31 type vectorDefinitionField struct {
32 Type string `bson:"type"`
33 Path string `bson:"path"`
34 NumDimensions int `bson:"numDimensions"`
35 Similarity string `bson:"similarity"`
36 }
37
38 type vectorDefinition struct {
39 Fields []vectorDefinitionField `bson:"fields"`
40 }
41
42 indexName := "<indexName>"
43 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
44
45 indexModel := mongo.SearchIndexModel{
46 Definition: vectorDefinition{
47 Fields: []vectorDefinitionField{{
48 Type: "vector",
49 Path: "<fieldToIndex>",
50 NumDimensions: <numberOfDimensions>,
51 Similarity: "euclidean | cosine | dotProduct"}},
52 },
53 Options: opts,
54 }
55
56 // Create the index
57 log.Println("Creating the index.")
58 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
59 if err != nil {
60 log.Fatalf("failed to create the search index: %v", err)
61 }
62
63 // Await the creation of the index.
64 log.Println("Polling to confirm successful index creation.")
65 log.Println("NOTE: This may take up to a minute.")
66 searchIndexes := coll.SearchIndexes()
67 var doc bson.Raw
68 for doc == nil {
69 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
70 if err != nil {
71 fmt.Errorf("failed to list search indexes: %w", err)
72 }
73
74 if !cursor.Next(ctx) {
75 break
76 }
77
78 name := cursor.Current.Lookup("name").StringValue()
79 queryable := cursor.Current.Lookup("queryable").Boolean()
80 if name == searchIndexName && queryable {
81 doc = cursor.Current
82 } else {
83 time.Sleep(5 * time.Second)
84 }
85 }
86
87 log.Println("Name of Index Created: " + searchIndexName)
88}

참고

프로그래밍 방식의 인덱스 생성

MongoDB 고 (Go) 운전자 v1.16.0부터 프로그래밍 방식의 Atlas Vector Search 인덱스 관리 지원하지만, 앞의 코드는 v2.x 운전자 의 구문을 보여줍니다.

2

<connectionString>

Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

<numberOfDimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<fieldToIndex>

인덱싱할 벡터 및 필터 필드입니다.

예시

다음을 복사하여 create-index.go 파일 에 붙여넣고 <connectionString> 자리 표시자 값을 바꿉니다. 다음 인덱스 정의는 Atlas Vector Search 인덱스 에서 plot_embedding 필드 vector 유형으로, genresyear 필드를 filter 유형으로 인덱싱합니다. plot_embedding 필드 에는 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536 벡터 차원을 지정하고 dotProduct 함수를 사용하여 유사성을 측정합니다.

다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드(plot_embedding)만 인덱싱합니다.

1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7 "time"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connection-string>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("sample_mflix").Collection("embedded_movies")
30
31 // Define the index details
32 type vectorDefinitionField struct {
33 Type string `bson:"type"`
34 Path string `bson:"path"`
35 NumDimensions int `bson:"numDimensions"`
36 Similarity string `bson:"similarity"`
37 Quantization string `bson:"quantization"`
38 }
39
40 type vectorDefinition struct {
41 Fields []vectorDefinitionField `bson:"fields"`
42 }
43
44 indexName := "vector_index"
45 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
46
47 indexModel := mongo.SearchIndexModel{
48 Definition: vectorDefinition{
49 Fields: []vectorDefinitionField{{
50 Type: "vector",
51 Path: "plot_embedding",
52 NumDimensions: 1536,
53 Similarity: "dotProduct",
54 Quantization: "scalar"}},
55 },
56 Options: opts,
57 }
58
59 // Create the index
60 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
61 if err != nil {
62 log.Fatalf("failed to create the search index: %v", err)
63 }
64 log.Println("New search index named " + searchIndexName + " is building.")
65
66 // Await the creation of the index.
67 log.Println("Polling to check if the index is ready. This may take up to a minute.")
68 searchIndexes := coll.SearchIndexes()
69 var doc bson.Raw
70 for doc == nil {
71 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
72 if err != nil {
73 fmt.Errorf("failed to list search indexes: %w", err)
74 }
75
76 if !cursor.Next(ctx) {
77 break
78 }
79
80 name := cursor.Current.Lookup("name").StringValue()
81 queryable := cursor.Current.Lookup("queryable").Boolean()
82 if name == searchIndexName && queryable {
83 doc = cursor.Current
84 } else {
85 time.Sleep(5 * time.Second)
86 }
87 }
88
89 log.Println(searchIndexName + " is ready for querying.")
90}

이 인덱스 정의는 다음 필드를 인덱싱합니다:

  • 데이터를 사전 필터링하기 위한 문자열 필드(genres) 및 숫자 필드(year).

  • 사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(plot_embedding)입니다.

1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7 "time"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("sample_mflix").Collection("embedded_movies")
30 indexName := "vector_index"
31 opts := options.SearchIndexes().SetName(indexName).SetType("vectorSearch")
32
33 type vectorDefinitionField struct {
34 Type string `bson:"type"`
35 Path string `bson:"path"`
36 NumDimensions int `bson:"numDimensions"`
37 Similarity string `bson:"similarity"`
38 Quantization string `bson:"quantization"`
39 }
40
41 type filterField struct {
42 Type string `bson:"type"`
43 Path string `bson:"path"`
44 }
45
46 type indexDefinition struct {
47 Fields []vectorDefinitionField `bson:"fields"`
48 }
49
50 vectorDefinition := vectorDefinitionField{
51 Type: "vector",
52 Path: "plot_embedding",
53 NumDimensions: 1536,
54 Similarity: "dotProduct",
55 Quantization: "scalar"}
56 genreFilterDefinition := filterField{"filter", "genres"}
57 yearFilterDefinition := filterField{"filter", "year"}
58
59 indexModel := mongo.SearchIndexModel{
60 Definition: bson.D{{Key: "fields", Value: [3]interface{}{
61 vectorDefinition,
62 genreFilterDefinition,
63 yearFilterDefinition}}},
64 Options: opts,
65 }
66
67 // Create the index
68 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, indexModel)
69 if err != nil {
70 log.Fatalf("failed to create the search index: %v", err)
71 }
72 log.Println("New search index named " + searchIndexName + " is building.")
73
74 // Await the creation of the index.
75 log.Println("Polling to check if the index is ready. This may take up to a minute.")
76 searchIndexes := coll.SearchIndexes()
77 var doc bson.Raw
78 for doc == nil {
79 cursor, err := searchIndexes.List(ctx, options.SearchIndexes().SetName(searchIndexName))
80 if err != nil {
81 fmt.Errorf("failed to list search indexes: %w", err)
82 }
83
84 if !cursor.Next(ctx) {
85 break
86 }
87
88 name := cursor.Current.Lookup("name").StringValue()
89 queryable := cursor.Current.Lookup("queryable").Boolean()
90 if name == searchIndexName && queryable {
91 doc = cursor.Current
92 } else {
93 time.Sleep(5 * time.Second)
94 }
95 }
96
97 log.Println(searchIndexName + " is ready for querying.")
98}
3
go run create-index.go

MongoDB Java 드라이버 v5.2.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 생성하려면 다음 단계를 수행하세요.

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.model.SearchIndexModel;
6import com.mongodb.client.model.SearchIndexType;
7import org.bson.Document;
8import org.bson.conversions.Bson;
9
10import java.util.Arrays;
11import java.util.Collections;
12import java.util.List;
13
14public class VectorIndex {
15
16 public static void main(String[] args) {
17
18 // Replace the placeholder with your Atlas connection string
19 String uri = "<connectionString>";
20
21 // Connect to your Atlas cluster
22 try (MongoClient mongoClient = MongoClients.create(uri)) {
23
24 // Set the namespace
25 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
26 MongoCollection<Document> collection = database.getCollection("<collectionName>");
27
28 // Define the index details
29 String indexName = "<indexName>";
30 Bson definition = new Document(
31 "fields",
32 Arrays.asList(
33 new Document("type", "vector")
34 .append("path", "<fieldToIndex>")
35 .append("numDimensions", <numberOfDimensions>)
36 .append("similarity", "euclidean | cosine | dotProduct"),
37 new Document("type", "filter")
38 .append("path", "<fieldToIndex>"),
39 ...));
40
41 // Define the index model
42 SearchIndexModel indexModel = new SearchIndexModel(
43 indexName,
44 definition,
45 SearchIndexType.vectorSearch()
46 );
47
48 // Create the index using the defined model
49 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
50 System.out.println("Successfully created vector index named: " + result.get(0));
51 System.out.println("It may take up to a minute for the index to leave the BUILDING status and become queryable.");
52
53 // Wait for Atlas to build the index
54 System.out.println("Polling to confirm the index has left the BUILDING status.");
55 // No special handling in case of a timeout. Custom handling can be implemented.
56 waitForIndex(collection, indexName);
57 }
58 }
59
60 /**
61 * Polls the collection to check whether the specified index is ready to query.
62 */
63 public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) {
64 long startTime = System.nanoTime();
65 long timeoutNanos = TimeUnit.SECONDS.toNanos(60);
66 while (System.nanoTime() - startTime < timeoutNanos) {
67 Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
68 .filter(index -> indexName.equals(index.getString("name")))
69 .findAny().orElse(null);
70 if (indexRecord != null) {
71 if ("FAILED".equals(indexRecord.getString("status"))) {
72 throw new RuntimeException("Search index has FAILED status.");
73 }
74 if (indexRecord.getBoolean("queryable")) {
75 System.out.println(indexName + " index is ready to query");
76 return true;
77 }
78 }
79 try {
80 Thread.sleep(100); // busy-wait, avoid in production
81 } catch (InterruptedException e) {
82 Thread.currentThread().interrupt();
83 throw new RuntimeException(e);
84 }
85 }
86 return false;
87 }
88}
2

<connectionString>

Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

<numberOfDimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<fieldToIndex>

인덱싱할 벡터 및 필터 필드입니다.

다음은 인덱스 정의 예시입니다.

  • Atlas Vector Search 인덱스에서 plot_embedding 필드 를 vector 유형으로, genresyear 필드를 filter 유형으로 인덱싱합니다.

  • plot_embedding 필드를 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 만든 임베딩을 포함하는 벡터 임베딩 필드로 지정합니다.

  • 1536 벡터 차원을 지정하고 dotProduct 함수를 사용하여 유사성을 측정합니다.

이 인덱스 정의는 벡터 임베딩 필드 (plot_embedding)만 인덱싱하여 벡터 검색을 수행합니다.

복사하여 만든 파일에 다음을 붙여넣고 <connectionString> 자리 표시자 값을 바꿉니다.

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.model.SearchIndexModel;
6import com.mongodb.client.model.SearchIndexType;
7import org.bson.Document;
8import org.bson.conversions.Bson;
9
10import java.util.Collections;
11import java.util.List;
12
13public class VectorIndex {
14
15 public static void main(String[] args) {
16
17 // Replace the placeholder with your Atlas connection string
18 String uri = "<connectionString>";
19
20 // Connect to your Atlas cluster
21 try (MongoClient mongoClient = MongoClients.create(uri)) {
22
23 // Set the namespace
24 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
25 MongoCollection<Document> collection = database.getCollection("embedded_movies");
26
27 // Define the index details
28 String indexName = "vector_index";
29 Bson definition = new Document(
30 "fields",
31 Collections.singletonList(
32 new Document("type", "vector")
33 .append("path", "plot_embedding")
34 .append("numDimensions", 1536)
35 .append("similarity", "dotProduct")
36 .append("quantization", "scalar")));
37
38 // Define the index model
39 SearchIndexModel indexModel = new SearchIndexModel(
40 indexName,
41 definition,
42 SearchIndexType.vectorSearch());
43
44 // Create the index using the defined model
45 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
46 System.out.println("Successfully created vector index named: " + result.get(0));
47 System.out.println("It may take up to a minute for the index to leave the BUILDING status and become queryable.");
48
49 // Wait for Atlas to build the index
50 System.out.println("Polling to confirm the index has left the BUILDING status.");
51 // No special handling in case of a timeout. Custom handling can be implemented.
52 waitForIndex(collection, indexName);
53 }
54 }
55
56 /**
57 * Polls the collection to check whether the specified index is ready to query.
58 */
59 public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) {
60 long startTime = System.nanoTime();
61 long timeoutNanos = TimeUnit.SECONDS.toNanos(60);
62 while (System.nanoTime() - startTime < timeoutNanos) {
63 Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
64 .filter(index -> indexName.equals(index.getString("name")))
65 .findAny().orElse(null);
66 if (indexRecord != null) {
67 if ("FAILED".equals(indexRecord.getString("status"))) {
68 throw new RuntimeException("Search index has FAILED status.");
69 }
70 if (indexRecord.getBoolean("queryable")) {
71 System.out.println(indexName + " index is ready to query");
72 return true;
73 }
74 }
75 try {
76 Thread.sleep(100); // busy-wait, avoid in production
77 } catch (InterruptedException e) {
78 Thread.currentThread().interrupt();
79 throw new RuntimeException(e);
80 }
81 }
82 return false;
83 }
84}

이 인덱스 정의는 다음 필드를 인덱싱합니다:

  • 데이터를 사전 필터링하기 위한 문자열 필드(genres) 및 숫자 필드(year).

  • 사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(plot_embedding)입니다.

복사하여 만든 파일에 다음을 붙여넣고 <connectionString> 자리 표시자 값을 바꿉니다.

1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.model.SearchIndexModel;
6import com.mongodb.client.model.SearchIndexType;
7import org.bson.Document;
8import org.bson.conversions.Bson;
9
10import java.util.Arrays;
11import java.util.Collections;
12import java.util.List;
13
14public class VectorIndex {
15
16 public static void main(String[] args) {
17
18 // Replace the placeholder with your Atlas connection string
19 String uri = "<connectionString>";
20
21 // Connect to your Atlas cluster
22 try (MongoClient mongoClient = MongoClients.create(uri)) {
23
24 // Set the namespace
25 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
26 MongoCollection<Document> collection = database.getCollection("embedded_movies");
27
28 // Define the index details with the filter fields
29 String indexName = "vector_index";
30 Bson definition = new Document(
31 "fields",
32 Arrays.asList(
33 new Document("type", "vector")
34 .append("path", "plot_embedding")
35 .append("numDimensions", 1536)
36 .append("similarity", "dotProduct")
37 .append("quantization", "scalar"),
38 new Document("type", "filter")
39 .append("path", "genres"),
40 new Document("type", "filter")
41 .append("path", "year")));
42
43 // Define the index model
44 SearchIndexModel indexModel = new SearchIndexModel(
45 indexName,
46 definition,
47 SearchIndexType.vectorSearch());
48
49 // Create the index using the defined model
50 List<String> result = collection.createSearchIndexes(Collections.singletonList(indexModel));
51 System.out.println("Successfully created vector index named: " + result.get(0));
52 System.out.println("It may take up to a minute for the index to leave the BUILDING status and become queryable.");
53
54 // Wait for Atlas to build the index
55 System.out.println("Polling to confirm the index has left the BUILDING status.");
56 // No special handling in case of a timeout. Custom handling can be implemented.
57 waitForIndex(collection, indexName);
58 }
59 }
60
61 /**
62 * Polls the collection to check whether the specified index is ready to query.
63 */
64 public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) {
65 long startTime = System.nanoTime();
66 long timeoutNanos = TimeUnit.SECONDS.toNanos(60);
67 while (System.nanoTime() - startTime < timeoutNanos) {
68 Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
69 .filter(index -> indexName.equals(index.getString("name")))
70 .findAny().orElse(null);
71 if (indexRecord != null) {
72 if ("FAILED".equals(indexRecord.getString("status"))) {
73 throw new RuntimeException("Search index has FAILED status.");
74 }
75 if (indexRecord.getBoolean("queryable")) {
76 System.out.println(indexName + " index is ready to query");
77 return true;
78 }
79 }
80 try {
81 Thread.sleep(100); // busy-wait, avoid in production
82 } catch (InterruptedException e) {
83 Thread.currentThread().interrupt();
84 throw new RuntimeException(e);
85 }
86 }
87 return false;
88 }
89}
3

IDE에서 파일을 실행하여 인덱스를 만듭니다.

MongoDB Node 드라이버 v6.6.0 이상을 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 만들려면 다음 단계를 수행하세요.

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // define your Atlas Vector Search index
14 const index = {
15 name: "<indexName>",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": <numberOfDimensions>,
22 "path": "<fieldToIndex>",
23 "similarity": "euclidean | cosine | dotProduct"
24 },
25 {
26 "type": "filter",
27 "path": "<fieldToIndex>"
28 },
29 ...
30 ]
31 }
32 }
33
34 // run the helper method
35 const result = await collection.createSearchIndex(index);
36 console.log(`New search index named ${result} is building.`);
37 // wait for the index to be ready to query
38 console.log("Polling to check if the index is ready. This may take up to a minute.")
39 let isQueryable = false;
40 while (!isQueryable) {
41 const cursor = collection.listSearchIndexes();
42 for await (const index of cursor) {
43 if (index.name === result) {
44 if (index.queryable) {
45 console.log(`${result} is ready for querying.`);
46 isQueryable = true;
47 } else {
48 await new Promise(resolve => setTimeout(resolve, 5000));
49 }
50 }
51 }
52 }
53 } finally {
54 await client.close();
55 }
56}
57run().catch(console.dir);

예시

vector-index.js이라는 파일을 만듭니다.

2

<connectionString>

Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

<numberOfDimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<fieldToIndex>

인덱싱할 벡터 및 필터 필드입니다.

예시

다음을 복사하여 vector-index.js 파일 에 붙여넣고 <connectionString> 자리 표시자 값을 바꿉니다. 다음 인덱스 정의는 Atlas Vector Search 인덱스 에서 plot_embedding 필드 vector 유형으로, genresyear 필드를 filter 유형으로 인덱싱합니다. plot_embedding 필드 에는 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536 벡터 차원을 지정하고 dotProduct 함수를 사용하여 유사성을 측정합니다.

다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드(plot_embedding)만 인덱싱합니다.

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("embedded_movies");
12
13 // define your Atlas Vector Search index
14 const index = {
15 name: "vector_index",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": 1536,
22 "path": "plot_embedding",
23 "similarity": "dotProduct",
24 "quantization": "scalar"
25 }
26 ]
27 }
28 }
29
30 // run the helper method
31 const result = await collection.createSearchIndex(index);
32 console.log(`New search index named ${result} is building.`);
33
34 // wait for the index to be ready to query
35 console.log("Polling to check if the index is ready. This may take up to a minute.")
36 let isQueryable = false;
37 while (!isQueryable) {
38 const cursor = collection.listSearchIndexes();
39 for await (const index of cursor) {
40 if (index.name === result) {
41 if (index.queryable) {
42 console.log(`${result} is ready for querying.`);
43 isQueryable = true;
44 } else {
45 await new Promise(resolve => setTimeout(resolve, 5000));
46 }
47 }
48 }
49 }
50 } finally {
51 await client.close();
52 }
53}
54run().catch(console.dir);

이 인덱스 정의는 다음 필드를 인덱싱합니다:

  • 데이터를 사전 필터링하기 위한 문자열 필드(genres) 및 숫자 필드(year).

  • 사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(plot_embedding)입니다.

1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("sample_mflix");
11 const collection = database.collection("embedded_movies");
12
13 // define your Atlas Vector Search index
14 const index = {
15 name: "vector_index",
16 type: "vectorSearch",
17 definition: {
18 "fields": [
19 {
20 "type": "vector",
21 "numDimensions": 1536,
22 "path": "plot_embedding",
23 "similarity": "dotProduct",
24 "quantization": "scalar"
25 },
26 {
27 "type": "filter",
28 "path": "genres"
29 },
30 {
31 "type": "filter",
32 "path": "year"
33 }
34 ]
35 }
36 }
37
38 // run the helper method
39 const result = await collection.createSearchIndex(index);
40 console.log(`New search index named ${result} is building.`);
41
42 // wait for the index to be ready to query
43 console.log("Polling to check if the index is ready. This may take up to a minute.")
44 let isQueryable = false;
45 while (!isQueryable) {
46 const cursor = collection.listSearchIndexes();
47 for await (const index of cursor) {
48 if (index.name === result) {
49 if (index.queryable) {
50 console.log(`${result} is ready for querying.`);
51 isQueryable = true;
52 } else {
53 await new Promise(resolve => setTimeout(resolve, 5000));
54 }
55 }
56 }
57 }
58 } finally {
59 await client.close();
60 }
61}
62run().catch(console.dir);
3
node <file-name>.js

예시

node vector_index.js

Work with a runnable version of this example as a Python notebook.

PyMongo 드라이버 v4.7 이상을 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 생성하려면 다음 단계를 수행하세요.

1
1import pymongo
2from pymongo.mongo_client import MongoClient
3from pymongo.operations import SearchIndexModel
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["<databaseName>"]
11collection = database["<collectionName>"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "numDimensions": <numberofDimensions>,
20 "path": "<fieldToIndex>",
21 "similarity": "euclidean | cosine | dotProduct"
22 },
23 {
24 "type": "filter",
25 "path": "<fieldToIndex>"
26 },
27 ...
28 ]
29 },
30 name="<indexName>",
31 type="vectorSearch"
32)
33
34result = collection.create_search_index(model=search_index_model)
35print("New search index named " + result + " is building.")
36
37# Wait for initial sync to complete
38print("Polling to check if the index is ready. This may take up to a minute.")
39predicate=None
40if predicate is None:
41 predicate = lambda index: index.get("queryable") is True
42
43while True:
44 indices = list(collection.list_search_indexes(result))
45 if len(indices) and predicate(indices[0]):
46 break
47 time.sleep(5)
48print(result + " is ready for querying.")
49
50client.close()

자세한 내용은 create_search_index() 메서드.

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3
4def create_indexes():
5 # Connect to your Atlas deployment
6 uri = "<connectionString>"
7 client = MongoClient(uri)
8
9 # Access your database and collection
10 database = client["<databaseName>"]
11 collection = database["<collectionName>"]
12
13 # Create your index models and add them to an array
14 first_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "numDimensions": <numberOfDimensions>,
20 "path": "<fieldToIndex>",
21 "similarity": "euclidean | cosine | dotProduct"
22 },
23 {
24 "type": "filter",
25 "path": "<fieldToIndex>"
26 },
27 ...
28 ]
29 },
30 name="<indexName>",
31 type="vectorSearch"
32 )
33
34 second_model = SearchIndexModel(
35 definition={
36 "fields": [
37 {
38 "type": "vector",
39 "numDimensions": <numberOfDimensions>,
40 "path": "<fieldToIndex>",
41 "similarity": "euclidean | cosine | dotProduct"
42 },
43 {
44 "type": "filter",
45 "path": "<fieldToIndex>"
46 },
47 ...
48 ]
49 },
50 name="<index name>",
51 type="vectorSearch"
52 )
53
54 ...
55
56 idx_models = [first_model, second_model, ...]
57
58 # Create the search indexes
59 result = collection.create_search_indexes(models=idx_models)
60 print(result)
61
62 client.close()

자세한 내용은 create_search_indexes() 메서드.

예시

vector-index.py이라는 파일을 만듭니다.

2

<connectionString>

Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

<numberOfDimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<fieldToIndex>

인덱싱할 벡터 및 필터 필드입니다.

예시

다음을 복사하여 vector-index.py 에 붙여넣고 <connectionString> 자리 표시자 값을 바꿉니다. 다음 인덱스 정의는 Atlas Vector Search 인덱스 에서 plot_embedding 필드 vector 유형으로, genresyear 필드를 filter 유형으로 인덱싱합니다. plot_embedding 필드 에는 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536 벡터 차원을 지정하고 dotProduct 함수를 사용하여 유사성을 측정합니다.

Work with a runnable version of this example as a Python notebook.

다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드(plot_embedding)만 인덱싱합니다.

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3import time
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["sample_mflix"]
11collection = database["embedded_movies"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "path": "plot_embedding",
20 "numDimensions": 1536,
21 "similarity": "dotProduct",
22 "quantization": "scalar"
23 }
24 ]
25 },
26 name="vector_index",
27 type="vectorSearch"
28)
29
30result = collection.create_search_index(model=search_index_model)
31print("New search index named " + result + " is building.")
32
33# Wait for initial sync to complete
34print("Polling to check if the index is ready. This may take up to a minute.")
35predicate=None
36if predicate is None:
37 predicate = lambda index: index.get("queryable") is True
38
39while True:
40 indices = list(collection.list_search_indexes(result))
41 if len(indices) and predicate(indices[0]):
42 break
43 time.sleep(5)
44print(result + " is ready for querying.")
45
46client.close()

Work with a runnable version of this example as a Python notebook.

이 인덱스 정의는 다음 필드를 인덱싱합니다:

  • 데이터를 사전 필터링하기 위한 문자열 필드(genres) 및 숫자 필드(year).

  • 사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(plot_embedding)입니다.

1from pymongo.mongo_client import MongoClient
2from pymongo.operations import SearchIndexModel
3import time
4
5# Connect to your Atlas deployment
6uri = "<connectionString>"
7client = MongoClient(uri)
8
9# Access your database and collection
10database = client["sample_mflix"]
11collection = database["embedded_movies"]
12
13# Create your index model, then create the search index
14search_index_model = SearchIndexModel(
15 definition={
16 "fields": [
17 {
18 "type": "vector",
19 "path": "plot_embedding",
20 "numDimensions": 1536,
21 "similarity": "dotProduct",
22 "quantization": "scalar"
23 },
24 {
25 "type": "filter",
26 "path": "genres"
27 },
28 {
29 "type": "filter",
30 "path": "year"
31 }
32 ]
33 },
34 name="vector_index",
35 type="vectorSearch"
36)
37
38result = collection.create_search_index(model=search_index_model)
39print("New search index named " + result + " is building.")
40
41# Wait for initial sync to complete
42print("Polling to check if the index is ready. This may take up to a minute.")
43predicate=None
44if predicate is None:
45 predicate = lambda index: index.get("queryable") is True
46
47while True:
48 indices = list(collection.list_search_indexes(result))
49 if len(indices) and predicate(indices[0]):
50 break
51 time.sleep(5)
52print(result + " is ready for querying.")
53
54client.close()
3
python <file-name>.py

예시

python vector-index.py

Atlas UI, Atlas 관리 API, Atlas CLI, mongosh 또는 지원되는 MongoDB 드라이버에서 모든 컬렉션에 대한 Atlas Vector Search 인덱스를 확인할 수 있습니다.

Atlas Vector Search 검색 인덱스를 보려면 Project Search Index Editor 이상의 역할이 필요합니다.

참고

mongosh 명령 또는 운전자 헬퍼 메서드를 사용하여 모든 Atlas cluster 계층에서 Atlas Vector Search 인덱스를 조회 수 있습니다. 지원되는 운전자 버전 목록은 지원되는 클라이언트를 참조하세요.


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


Atlas 관리 API를 사용하여 컬렉션의 모든 Atlas Vector Search 인덱스를 검색하려면 데이터베이스와 컬렉션 이름을 포함하여 Atlas 검색 indexes 엔드포인트에 GET 요청을 보내세요.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}"

To learn more about the syntax and parameters for the endpoint, see Return All Atlas Search Indexes for One Collection.

Atlas 관리 API를 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스 한 개를 조회하려면 조회할 인덱스의 고유 ID 또는 이름(4 행)과 함께 Atlas Search indexes 엔드포인트에 GET 요청을 보내세요.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request GET "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}"

엔드포인트의 구문 및 매개변수에 대한 자세한 내용은 이름으로 하나씩 가져오기ID로 하나씩 가져오기를 참조하세요.

Atlas CLI를 사용하여 컬렉션의 Atlas Vector Search 인덱스를 반환하려면 다음 단계를 수행하세요.

1

clusterName

Atlas 클러스터의 이름

db

인덱싱된 컬렉션이 포함된 Atlas 클러스터의 데이터베이스 이름입니다.

collection

데이터베이스에서 인덱싱된 컬렉션의 이름입니다.

projectId

프로젝트의 고유 식별자.

2
atlas clusters search indexes list --clusterName [cluster_name] --db <db-name> --collection <collection-name>

명령에서 다음 자리 표시자 값을 바꿉니다.

  • cluster-name - 인덱싱된 컬렉션을 포함하는 Atlas 클러스터의 이름입니다.

  • db-name - 인덱스를 조회하려는 컬렉션이 포함된 데이터베이스의 이름입니다.

  • collection-name - 인덱스를 조회하려는 컬렉션 의 이름입니다.

명령 구문 및 매개변수에 대해 자세히 알아보려면 Atlas 클러스터 검색 인덱스 목록 명령에 대한 Atlas CLI 문서를 참조하세요.

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

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

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

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

2

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

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

    참고

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

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

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

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

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

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

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

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

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

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

이 페이지에는 페이지의 인덱스에 대한 다음과 같은 세부 정보가 표시됩니다.

이름

인덱스를 식별하는 레이블입니다.

인덱스 유형

Atlas Search 또는 Atlas Vector Search 인덱스를 나타내는 레이블입니다. 값에는 다음이 포함됩니다.

  • Atlas Search 인덱스의 경우 search .

  • vectorSearch Atlas Vector Search 인덱스에 대한 정보입니다.

인덱스 필드

이 인덱스가 인덱싱하는 필드가 포함된 목록입니다.

상태

클러스터 의 프라이머리 노드 에 있는 인덱스 의 현재 상태 . 유효한 값은 인덱스 상태를 참조하세요.

size

프라이머리 노드에 있는 인덱스의 크기입니다.

문서

collection의 총 문서 수 중 인덱스된 문서 수입니다.

작업

인덱스에 대해 수행할 수 있는 조치입니다. 다음을 수행할 수 있습니다.

vectorSearch 유형의 인덱스에 대해서는 Search Tester UI 에서 쿼리를 실행 수 없습니다. Query 버튼을 클릭하면 Atlas Vector Search 에 $vectorSearch Atlas UI 및 지원되는 다른 클라이언트를 사용하여 복사, 수정 및 실행 수 있는 샘플 가 표시됩니다.

mongosh를 사용하여 컬렉션의 Atlas Vector Search 인덱스를 보려면 다음 단계를 수행하세요.

1

To learn more, see Connect via mongosh.

2
3

db.collection.getSearchIndexes() 메서드의 구문은 다음과 같습니다.

1db.<collectionName>.getSearchIndexes( "<index-name>" );

C# 드라이버 3.1.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 보려면 다음 단계를 수행하세요.

1
1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5
6public class IndexService
7{
8 private const string MongoConnectionString = "<connectionString>";
9 // Other class methods here...
10 public void ViewSearchIndexes()
11 {
12 try
13 {
14 // Connect to your Atlas deployment
15 var client = new MongoClient(MongoConnectionString);
16
17 // Access your database and collection
18 var database = client.GetDatabase("<databaseName>");
19 var collection = database.GetCollection<BsonDocument>("<collectionName>");
20
21 // Get a list of the collection's search indexes and print them
22 var searchIndexView = collection.SearchIndexes;
23 var indexes = searchIndexView.List();
24
25 foreach (var index in indexes.ToEnumerable())
26 {
27 Console.WriteLine(index);
28 }
29 }
30 catch (Exception e)
31 {
32 Console.WriteLine($"Exception: {e.Message}");
33 }
34 }
35}
2

<connectionString>

Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오.

<databaseName>

컬렉션이 포함된 데이터베이스의 이름입니다.

<collectionName>

컬렉션의 이름입니다.

3
using query_quick_start;
var indexService = new IndexService();
indexService.ViewSearchIndexes();
4
dotnet run

MongoDB 고 (Go) 운전자 v2.0 이상을 사용하는 컬렉션 에 대한 Atlas Vector Search 인덱스 보려면 다음 단계를 수행하세요.

1
1package main
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log"
8
9 "go.mongodb.org/mongo-driver/v2/bson"
10 "go.mongodb.org/mongo-driver/v2/mongo"
11 "go.mongodb.org/mongo-driver/v2/mongo/options"
12)
13
14func main() {
15 ctx := context.Background()
16
17 // Replace the placeholder with your Atlas connection string
18 const uri = "<connectionString>"
19
20 // Connect to your Atlas cluster
21 clientOptions := options.Client().ApplyURI(uri)
22 client, err := mongo.Connect(clientOptions)
23 if err != nil {
24 log.Fatalf("failed to connect to the server: %v", err)
25 }
26 defer func() { _ = client.Disconnect(ctx) }()
27
28 // Set the namespace
29 coll := client.Database("<databaseName>").Collection("<collectionName>")
30
31 // Specify the options for the index to retrieve
32 indexName := "<indexName>"
33 opts := options.SearchIndexes().SetName(indexName)
34
35 // Get the index
36 cursor, err := coll.SearchIndexes().List(ctx, opts)
37 if err != nil {
38 log.Fatalf("failed to get the index: %v", err)
39 }
40
41 // Print the index details to the console as JSON
42 var results []bson.M
43 if err := cursor.All(ctx, &results); err != nil {
44 log.Fatalf("failed to unmarshal results to bson: %v", err)
45 }
46 res, err := json.Marshal(results)
47 if err != nil {
48 log.Fatalf("failed to marshal results to json: %v", err)
49 }
50 fmt.Println(string(res))
51}
2

<connectionString>

Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오.

<databaseName>

컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 검색하려는 컬렉션입니다.

<indexName>

특정 인덱스 조회 하려는 경우 인덱스 의 이름입니다. 컬렉션 의 모든 인덱스를 반환하려면 검색 인덱스 옵션을 생성할 때 이 값을 생략하고 SetName() 메서드에 대한 호출을 제거 .

3
go run get-index.go

MongoDB Java 드라이버 v5.2.0 이상을 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 보려면 다음 단계를 수행하십시오.

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class ViewVectorIndex {
8
9 public static void main(String[] args) {
10
11 // Replace the placeholder with your Atlas connection string
12 String uri = "<connectionString>";
13
14 // Connect to your Atlas cluster
15 try (MongoClient mongoClient = MongoClients.create(uri)) {
16
17 // Set the namespace
18 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
19 MongoCollection<Document> collection = database.getCollection("<collectionName>");
20
21 // Specify the options for the index to retrieve
22 String indexName = "<indexName>";
23
24 // Get the index and print details to the console as JSON
25 try {
26 Document listSearchIndex = collection.listSearchIndexes().name(indexName).first();
27 if (listSearchIndex != null) {
28 System.out.println("Index found: " + listSearchIndex.toJson());
29 } else {
30 System.out.println("Index not found.");
31 }
32 } catch (Exception e) {
33 throw new RuntimeException("Error finding index: " + e);
34 }
35
36 } catch (Exception e) {
37 throw new RuntimeException("Error connecting to MongoDB: " + e);
38 }
39 }
40}
2

<connectionString>

Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오.

<databaseName>

컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 검색하려는 컬렉션입니다.

<indexName>

특정 인덱스를 검색하려는 경우 인덱스의 이름입니다. 컬렉션의 모든 인덱스를 반환하려면 이 값을 생략합니다.

3

IDE에서 파일을 실행하여 지정된 인덱스를 조회합니다.

MongoDB Node driver v6.6.0 이상을 사용하여 컬렉션의 Atlas 벡터 검색 인덱스를 보려면 다음 단계를 수행하세요.

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // run the helper method
14 const result = await collection.listSearchIndexes("<indexName>").toArray();
15 console.log(result);
16 } finally {
17 await client.close();
18 }
19}
20run().catch(console.dir);
2

<connectionString>

Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오.

<databaseName>

컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 검색하려는 컬렉션입니다.

<indexName>

특정 인덱스를 검색하려는 경우 인덱스의 이름입니다. 컬렉션의 모든 인덱스를 반환하려면 이 값을 생략합니다.

3
node <file-name>.js

Work with a runnable version of this example as a Python notebook.

PyMongo 드라이버 v4.7 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 보려면 다음 단계를 수행하세요.

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11# Get a list of the collection's search indexes and print them
12cursor = collection.list_search_indexes()
13for index in cursor:
14 print(index)

자세한 내용은 list_search_indexes() 메서드를 참조하세요.

2

<connectionString>

Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오.

<databaseName>

컬렉션이 포함된 데이터베이스의 이름입니다.

<collectionName>

컬렉션의 이름입니다.

3
python <file-name>.py

기존 Atlas Vector Search 인덱스의 인덱스 정의는 Atlas UI, Atlas 관리 API, Atlas CLI, mongosh 또는 지원되는 MongoDB 드라이버 에서 변경할 수 있습니다. 인덱스 이름을 바꾸거나 인덱스 유형을 변경할 수 없습니다. 인덱스 이름이나 유형을 변경해야 하는 경우 새 인덱스를 만들고 이전 인덱스를 삭제해야 합니다.

중요

인덱스 편집하면 Atlas Vector Search 인덱스를 다시 작성합니다. 인덱스 다시 작성되는 동안 이전 인덱스 정의를 사용하여 벡터 검색 쿼리를 계속 실행 수 있습니다. 인덱스 재작성이 완료되면 이전 인덱스 자동으로 교체됩니다. 이 프로세스 Atlas Search 인덱스와 유사합니다. 자세히 학습 Atlas Search 인덱스 생성 및 업데이트를 참조하세요.

Atlas Vector Search 인덱스를 편집하려면 Project Search Index Editor 이상의 역할이 있어야 합니다.

참고

mongosh 명령 또는 운전자 헬퍼 메서드를 사용하여 모든 Atlas cluster 계층에서 Atlas Vector Search 인덱스를 편집할 수 있습니다. 지원되는 운전자 버전 목록은 지원되는 클라이언트를 참조하세요.


언어 선택 드롭다운 메뉴를 사용하여 인덱스 편집에 사용할 클라이언트를 선택합니다.


Atlas 관리 API를 사용하여 컬렉션의 Atlas Vector Search 인덱스를 편집하려면 편집할 인덱스의 고유 ID 또는 이름(4 행)과 함께 Atlas Search indexes 엔드포인트에 PATCH 요청을 보냅니다.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest --include \
2 --header "Accept: application/json" \
3 --header "Content-Type: application/json" \
4 --request PATCH "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}" \
5 --data'
6 {
7 "database": "<name-of-database>",
8 "collectionName": "<name-of-collection>",
9 "type": "vectorSearch",
10 "name": "<index-name>",
11 "definition": {
12 "fields":[
13 {
14 "type": "vector",
15 "path": <field-to-index>,
16 "numDimensions": <number-of-dimensions>,
17 "similarity": "euclidean | cosine | dotProduct"
18 },
19 {
20 "type": "filter",
21 "path": "<field-to-index>"
22 },
23 ...
24 }
25 ]
26 }'

엔드포인트의 구문 및 매개변수에 대한 자세한 내용은 이름으로 하나씩 업데이트ID로 하나씩 업데이트를 참조하세요.

Atlas CLI를 사용하여 컬렉션의 Atlas Vector Search 인덱스를 편집하려면 다음 단계를 수행하세요.

1

인덱스 정의는 다음 형식과 유사해야 합니다.

1{
2 "database": "<name-of-database>",
3 "collectionName": "<name-of-collection>",
4 "type": "vectorSearch",
5 "name": "<index-name>",
6 "fields":[
7 {
8 "type": "vector",
9 "path": "<field-to-index>",
10 "numDimensions": <number-of-dimensions>,
11 "similarity": "euclidean | cosine | dotProduct"
12 },
13 {
14 "type": "filter",
15 "path": "<field-to-index>"
16 },
17 ...
18 ]
19}
2

<name-of-database>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<name-of-collection>

인덱스를 생성하려는 컬렉션입니다.

<index-name>

인덱스의 이름입니다. 인덱스 이름을 생략하는 경우 Atlas Vector Search는 인덱스 이름을 vector_index로 지정합니다.

<number-of-dimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<field-to-index>

인덱싱할 벡터 및 필터 필드입니다.

3
atlas clusters search indexes update <indexId> --clusterName [cluster_name] --file [vector-_index].json

명령에서 다음 자리 표시자 값을 바꿉니다.

  • cluster_name - 인덱스를 업데이트하려는 컬렉션이 포함된 Atlas 클러스터의 이름입니다.

  • vector_index - Atlas Vector Search 인덱스에 대한 수정된 인덱스 정의가 포함된 JSON 파일의 이름입니다.

명령 구문과 매개 변수에 관한 자세한 내용은 Atlas CLI 설명서의 Atlas 클러스터 검색 인덱스 업데이트를 참조하세요.

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

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

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

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

2

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

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

    참고

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

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

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

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

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

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

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

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

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

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

3
  1. 편집할 vectorSearch 유형 인덱스를 찾습니다.

  2. 해당 인덱스의 Actions 열에서 아이콘을 클릭합니다.

  3. Edit With Visual Editor를 선택하여 안내에 따라 진행하거나 Edit With JSON Editor를 선택하여 원시 인덱스 정의를 편집합니다.

  4. 현재 구성 설정을 검토하고 필요에 따라 편집합니다.

    To learn more about the fields in an Atlas Vector Search index, see 벡터 검색을 위해 필드를 인덱싱하는 방법.

  5. Save를 클릭하여 변경 사항을 적용하세요.

인덱스의 상태가 Active에서 Building으로 변경됩니다. 이 상태에서는 업데이트된 인덱스를 사용할 준비가 될 때까지 Atlas Vector Search가 이전 인덱스를 삭제하지 않으므로, 이전 인덱스를 계속 사용할 수 있습니다. 상태가 Active로 돌아가면 수정된 인덱스를 사용할 준비가 된 것입니다.

mongosh를 사용하여 컬렉션의 Atlas Vector Search 인덱스를 편집하려면 다음 단계를 수행하세요.

1

To learn more, see Connect via mongosh.

2
3

db.collection.updateSearchIndex() 메서드의 구문은 다음과 같습니다.

1db.<collectionName>.updateSearchIndex(
2 "<index-name>",
3 {
4 fields: [
5 {
6 "type": "vector",
7 "numDimensions": <number-of-dimensions>,
8 "path": "<field-to-index>",
9 "similarity": "euclidean | cosine | dotProduct"
10 },
11 {
12 "type": "filter",
13 "path": "<field-to-index>"
14 },
15 ...
16 ]
17 }
18);

C# 드라이버 v 3.1.0 이상을 사용하여 Atlas Vector Search 컬렉션의 인덱스를 업데이트하려면 다음 단계를 수행하세요.

1
1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5
6public class IndexService
7{
8 private const string MongoConnectionString = "<connectionString>";
9 // Other class methods here...
10 public void EditVectorIndex()
11 {
12 try
13 {
14 // Connect to your Atlas deployment
15 var client = new MongoClient(MongoConnectionString);
16
17 // Access your database and collection
18 var database = client.GetDatabase("<databaseName>");
19 var collection = database.GetCollection<BsonDocument>("<collectionName>");
20
21 var definition = new BsonDocument
22 {
23 { "fields", new BsonArray
24 {
25 new BsonDocument
26 {
27 { "type", "vector" },
28 { "path", "<fieldToIndex>" },
29 { "numDimensions", <numberOfDimensions> },
30 { "similarity", "euclidean | cosine | dotProduct" }
31 }
32 }
33 }
34 };
35
36 // Update your search index
37 var searchIndexView = collection.SearchIndexes;
38 searchIndexView.Update(name, definition);
39 }
40 catch (Exception e)
41 {
42 Console.WriteLine($"Exception: {e.Message}");
43 }
44 }
45}
2

<connectionString>

Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 Bame. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

<numberOfDimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<fieldToIndex>

인덱싱할 벡터 및 필터 필드입니다.

3
using query_quick_start;
var indexService = new IndexService();
indexService.EditVectorIndex();
4
dotnet run

MongoDB 고 (Go) 운전자 v2.0 이상을 사용하여 컬렉션 에 대한 Atlas Vector Search 인덱스 업데이트 하려면 다음 단계를 수행하세요.

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/mongo"
9 "go.mongodb.org/mongo-driver/v2/mongo/options"
10)
11
12func main() {
13 ctx := context.Background()
14
15 // Replace the placeholder with your Atlas connection string
16 const uri = "<connection-string>"
17
18 // Connect to your Atlas cluster
19 clientOptions := options.Client().ApplyURI(uri)
20 client, err := mongo.Connect(clientOptions)
21 if err != nil {
22 log.Fatalf("failed to connect to the server: %v", err)
23 }
24 defer func() { _ = client.Disconnect(ctx) }()
25
26 // Set the namespace
27 coll := client.Database("<databaseName>").Collection("<collectionName>")
28 indexName := "<indexName>"
29
30 type vectorDefinitionField struct {
31 Type string `bson:"type"`
32 Path string `bson:"path"`
33 NumDimensions int `bson:"numDimensions"`
34 Similarity string `bson:"similarity"`
35 }
36
37 type vectorDefinition struct {
38 Fields []vectorDefinitionField `bson:"fields"`
39 }
40
41 definition := vectorDefinition{
42 Fields: []vectorDefinitionField{{
43 Type: "vector",
44 Path: "<fieldToIndex>",
45 NumDimensions: <numberOfDimensions>,
46 Similarity: "euclidean | cosine | dotProduct"}},
47 }
48 err = coll.SearchIndexes().UpdateOne(ctx, indexName, definition)
49
50 if err != nil {
51 log.Fatalf("failed to update the index: %v", err)
52 }
53
54 fmt.Println("Successfully updated the search index")
55}
2

<connectionString>

Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

<numberOfDimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<fieldToIndex>

인덱싱할 벡터 및 필터 필드입니다.

3
go run edit-index.go

MongoDB Java 드라이버 v5.2.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 편집하려면 다음 단계를 수행하세요.

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6import org.bson.conversions.Bson;
7
8import java.util.Collections;
9
10public class EditVectorIndex {
11
12 public static void main(String[] args) {
13
14 // Replace the placeholder with your Atlas connection string
15 String uri = "<connectionString>";
16
17 // Connect to your Atlas cluster
18 try (MongoClient mongoClient = MongoClients.create(uri)) {
19
20 // Set the namespace
21 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
22 MongoCollection<Document> collection = database.getCollection("<collectionName>");
23
24 // Define the index changes
25 String indexName = "<indexName>";
26 Bson definition = new Document(
27 "fields",
28 Collections.singletonList(
29 new Document("type", "vector")
30 .append("path", "<fieldToIndex>")
31 .append("numDimensions", "<numberOfDimensions>")
32 .append("similarity", "euclidean | cosine | dotProduct")
33 .append("quantization", "none | scalar | binary")));
34
35 // Update the index
36 collection.updateSearchIndex(indexName, definition);
37 System.out.println("Successfully updated the index");
38 }
39 }
40}
2

<connectionString>

Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

<numberOfDimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<fieldToIndex>

인덱싱할 벡터 및 필터 필드입니다.

3

IDE에서 파일을 실행하여 변경 사항으로 인덱스를 업데이트합니다.

MongoDB Node 드라이버 v6.6.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 업데이트하려면 다음 단계를 수행하세요.

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // define your Atlas Search index
14 const index = {
15 name: "<indexName>",
16 type: "vectorSearch",
17 //updated search index definition
18 definition: {
19 "fields": [
20 {
21 "type": "vector",
22 "numDimensions": <numberOfDimensions>,
23 "path": "<field-to-index>",
24 "similarity": "euclidean | cosine | dotProduct"
25 },
26 {
27 "type": "filter",
28 "path": "<fieldToIndex>"
29 },
30 ...
31 ]
32 }
33 }
34
35 // run the helper method
36 await collection.updateSearchIndex("<index-name>", index);
37 } finally {
38 await client.close();
39 }
40}
41run().catch(console.dir);
2

<connectionString>

Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

<numberOfDimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<fieldToIndex>

인덱싱할 벡터 및 필터 필드입니다.

3
node <file-name>.js

Work with a runnable version of this example as a Python notebook.

PyMongo 드라이버 v4.7 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 업데이트하려면 다음 단계를 수행하세요.

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11definition = {
12 "fields": [
13 {
14 "type": "vector",
15 "numDimensions": <numberofDimensions>,
16 "path": "<fieldToIndex>",
17 "similarity": "euclidean | cosine | dotProduct",
18 "quantization": " none | scalar | binary "
19 },
20 {
21 "type": "filter",
22 "path": "<fieldToIndex>"
23 },
24 ...
25 ]
26}
27
28# Update your search index
29collection.update_search_index("<indexName>", definition)

자세한 내용은 update_search_index() 메서드를 참조하세요.

2

<connectionString>

Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 Bame. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

<numberOfDimensions>

Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.

<fieldToIndex>

인덱싱할 벡터 및 필터 필드입니다.

3
python <file-name>.py

Atlas UI, Atlas 관리 API, Atlas CLI, mongosh 또는 지원되는 MongoDB 드라이버에서 언제든지 Atlas Vector Search 인덱스를 삭제할 수 있습니다.

Atlas Vector Search 인덱스를 삭제하려면 Project Search Index Editor 이상의 역할이 있어야 합니다.

참고

mongosh 명령 또는 운전자 헬퍼 메서드를 사용하여 모든 Atlas cluster 계층에서 Atlas Vector Search 인덱스를 삭제 수 있습니다. 지원되는 운전자 버전 목록은 지원되는 클라이언트를 참조하세요.


언어 선택 드롭다운 메뉴를 사용하여 인덱스를 삭제하는 데 사용할 클라이언트를 선택합니다.


Atlas 관리 API를 사용해 컬렉션에 대한 Atlas Vector Search 인덱스를 삭제하려면 삭제할 인덱스의 고유 ID 또는 이름으로 Atlas Search indexes 엔드포인트에 DELETE 요청을 전송하세요.

1curl --user "{PUBLIC-KEY}:{PRIVATE-KEY}" --digest \
2 --header "Accept: application/json" \
3 --include \
4 --request DELETE "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{indexId} | https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes/{databaseName}/{collectionName}/{indexName|indexId}"

엔드포인트의 구문 및 매개변수에 대해 자세히 알아보려면 이름으로 1개의 검색 인덱스 제거ID로 1개의 검색 인덱스 제거를 참조하세요.

Atlas CLI를 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행합니다.

1

<indexId>

삭제할 인덱스의 고유 식별자입니다.

<clusterName>

Atlas 클러스터의 이름

<projectId>

프로젝트의 고유 식별자.

2
atlas clusters search indexes delete <indexId> [options]

명령에서 indexId 자리 표시자 값을 삭제할 인덱스의 고유 식별자로 바꿉니다.

명령 구문 및 매개변수에 대한 자세한 내용은 Atlas CLI 문서에서 Atlas 클러스터 검색 인덱스 삭제 명령을 참조하세요.

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

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

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

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

2

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

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

    참고

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

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

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

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

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

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

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

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

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

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

3
  1. 삭제할 vectorSearch 유형 인덱스를 찾습니다.

  2. 해당 인덱스의 Actions 드롭다운에서 Delete Index를 클릭합니다.

  3. 확인 창에서 Drop Index을(를) 클릭합니다.

mongosh를 사용하여 컬렉션의 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행하세요.

1

To learn more, see Connect via mongosh.

2
3

db.collection.dropSearchIndex() 메서드의 구문은 다음과 같습니다.

1db.<collectionName>.dropSearchIndex( "<index-name>" );

C# 드라이버 3.1.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행하세요.

1
1namespace query_quick_start;
2
3using MongoDB.Bson;
4using MongoDB.Driver;
5
6public class IndexService
7{
8 private const string MongoConnectionString = "<connectionString>";
9 // Other class methods here...
10 public void DeleteVectorIndex()
11 {
12 try
13 {
14 // Connect to your Atlas deployment
15 var client = new MongoClient(MongoConnectionString);
16
17 // Access your database and collection
18 var database = client.GetDatabase("<databaseName>");
19 var collection = database.GetCollection<BsonDocument>("<collectionName>");
20
21 // Delete your search index
22 var searchIndexView = collection.SearchIndexes;
23 var name = "vector_index";
24 searchIndexView.DropOne(name);
25
26 Console.WriteLine($"Dropping search index named {name}. This may take up to a minute.");
27 }
28 catch (Exception e)
29 {
30 Console.WriteLine($"Exception: {e.Message}");
31 }
32 }
33}
2

<connectionString>

Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오.

<databaseName>

컬렉션이 포함된 데이터베이스의 이름입니다.

<collectionName>

컬렉션의 이름입니다.

<indexName>

삭제할 인덱스의 이름입니다.

3
using query_quick_start;
var indexService = new IndexService();
indexService.DeleteVectorIndex();
4
dotnet run

MongoDB 고 (Go) 운전자 v2.0 이상을 사용하여 컬렉션 의 Atlas Vector Search 인덱스 삭제 하려면 다음 단계를 수행하세요.

1
1package main
2
3import (
4 "context"
5 "fmt"
6 "log"
7
8 "go.mongodb.org/mongo-driver/v2/mongo"
9 "go.mongodb.org/mongo-driver/v2/mongo/options"
10)
11
12func main() {
13 ctx := context.Background()
14
15 // Replace the placeholder with your Atlas connection string
16 const uri = "<connectionString>"
17
18 // Connect to your Atlas cluster
19 clientOptions := options.Client().ApplyURI(uri)
20 client, err := mongo.Connect(clientOptions)
21 if err != nil {
22 log.Fatalf("failed to connect to the server: %v", err)
23 }
24 defer func() { _ = client.Disconnect(ctx) }()
25
26 // Set the namespace
27 coll := client.Database("<databaseName>").Collection("<collectionName>")
28 indexName := "<indexName>"
29
30 err = coll.SearchIndexes().DropOne(ctx, indexName)
31 if err != nil {
32 log.Fatalf("failed to delete the index: %v", err)
33 }
34
35 fmt.Println("Successfully deleted the Vector Search index")
36}
2

<connectionString>

Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

3
go run delete-index.go

MongoDB Java 드라이버 v5.2.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행하세요.

1
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import org.bson.Document;
6
7public class DeleteIndex {
8
9 public static void main(String[] args) {
10
11 // Replace the placeholder with your Atlas connection string
12 String uri = "<connectionString>";
13
14 // Connect to your Atlas cluster
15 try (MongoClient mongoClient = MongoClients.create(uri)) {
16
17 // Set the namespace
18 MongoDatabase database = mongoClient.getDatabase("<databaseName>");
19 MongoCollection<Document> collection = database.getCollection("<collectionName>");
20
21 // Specify the index to delete
22 String indexName = "<indexName>";
23
24 try {
25 collection.dropSearchIndex(indexName);
26 } catch (Exception e) {
27 throw new RuntimeException("Error deleting index: " + e);
28 }
29
30 } catch (Exception e) {
31 throw new RuntimeException("Error connecting to MongoDB: " + e);
32 }
33 }
34}
2

<connectionString>

Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

3

IDE에서 파일을 실행하여 지정된 인덱스를 삭제합니다.

MongoDB Node 드라이버 v6.6.0 이상을 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행하세요.

1
1const { MongoClient } = require("mongodb");
2
3// connect to your Atlas deployment
4const uri = "<connectionString>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("<databaseName>");
11 const collection = database.collection("<collectionName>");
12
13 // run the helper method
14 await collection.dropSearchIndex("<indexName>");
15
16 } finally {
17 await client.close();
18 }
19}
20run().catch(console.dir);
2

<connectionString>

Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오.

<databaseName>

인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다.

<collectionName>

인덱스를 생성하려는 컬렉션입니다.

<indexName>

인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 vector_index입니다.

3
node <file-name>.js

Work with a runnable version of this example as a Python notebook.

PyMongo 드라이버 v4.7 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행하세요.

1
1from pymongo.mongo_client import MongoClient
2
3# Connect to your Atlas deployment
4uri = "<connectionString>"
5client = MongoClient(uri)
6
7# Access your database and collection
8database = client["<databaseName>"]
9collection = database["<collectionName>"]
10
11# Delete your search index
12collection.drop_search_index("<indexName>")

자세한 내용은 drop_search_index() 메서드를 참조하세요.

2

<connectionString>

Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오.

<databaseName>

컬렉션이 포함된 데이터베이스의 이름입니다.

<collectionName>

컬렉션의 이름입니다.

<indexName>

삭제할 인덱스의 이름입니다.

3
python <file-name>.py

Atlas Vector Search 인덱스를 생성하면 Status 열에 클러스터의 프라이머리 노드에 있는 인덱스의 현재 상태가 표시됩니다. 상태 아래에 있는 View status details 링크를 클릭하면 클러스터의 모든 노드에 있는 인덱스 상태를 볼 수 있습니다.

Status 열이 Active로 표시되면 인덱스가 사용할 준비가 된 것입니다. 다른 상태에서는 인덱스에 대한 쿼리가 불완전한 결과를 반환할 수 있습니다.

상태
설명

시작되지 않음

Atlas가 아직 인덱스 빌드를 시작하지 않았습니다.

초기 동기화

Atlas가 인덱스를 작성하거나 편집 후 인덱스를 다시 작성하고 있습니다. 인덱스가 이 상태인 경우 다음과 같습니다:

  • 새 인덱스의 경우 Atlas Vector Search는 인덱스 빌드가 완료될 때까지 쿼리를 제공하지 않습니다.

  • 기존 인덱스의 경우 인덱스가 다시 빌드될 때까지 기존 쿼리와 새 쿼리에 대해 이전 인덱스를 계속 사용할 수 있습니다.

활성

인덱스를 사용할 준비가 되었습니다.

복구 중

복제에 오류가 발생했습니다. 이 상태 일반적으로 mongod oplog 에서 현재 복제 점 더 이상 사용할 수 없을 때 발생합니다. 기존 인덱스가 업데이트되고 상태가 Active(으)로 변경될 때까지 기존 인덱스 계속 쿼리 할 수 있습니다. View status details 모달 창 오류를 사용하여 문제를 해결하세요. 자세히 학습 문제 해결을 참조하세요.

실패하였습니다.

Atlas 인덱스 빌드 수 없습니다. View status details 모달 창 오류를 사용하여 문제를 해결하세요. 자세히 학습 문제 해결을 참조하세요.

삭제 진행 중

Atlas가 클러스터 노드에서 인덱스를 삭제하는 중입니다.

Atlas가 인덱스를 빌드하는 동안 그리고 빌드가 완료된 후 Documents 열에 인덱싱된 문서의 백분율과 개수가 표시됩니다. 이 열에는 컬렉션의 총 문서 수도 표시됩니다.