벡터 검색을 위해 필드를 인덱싱하는 방법
이 페이지의 내용
vectorSearch
유형을 사용하면 $vectorSearch
쿼리를 실행하기 위해 필드를 인덱싱할 수 있습니다. 쿼리하려는 벡터 임베딩에 대한 인덱스와 데이터를 사전 필터링하는 데 사용할 부울, 날짜, objectId, 숫자, 문자열 또는 UUID 값을 정의할 수 있습니다. 데이터 필터링은 시맨틱 검색 범위를 좁히고 멀티 테넌트 환경 등에서 특정 벡터 임베딩이 비교 대상으로 고려되지 않도록 하는 데 유용합니다.
Atlas UI, Atlas 관리 API, Atlas CLI, mongosh
또는 지원되는 MongoDB 드라이버를 사용하여 Atlas Vector Search 인덱스를 만들 수 있습니다.
참고
더 이상 사용되지 않는 knnBeta 연산자를 사용하여 vectorSearch
유형 인덱스 정의로 인덱싱된 필드를 쿼리할 수 없습니다.
고려 사항
vectorSearch
유형 인덱스 정의에서는 단일 요소로만 배열을 인덱싱할 수 있습니다. 문서 배열 내의 필드나 객체 배열 내의 필드를 인덱싱할 수 없습니다. 점 표기법을 사용하여 문서 내부의 필드를 인덱싱할 수 있습니다.
임베딩을 인덱싱 전에 Atlas cluster 에 효율적으로 저장 하려면 임베딩을 하위 유형이 float32
, int1
또는 int8
인 BSON 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 인덱스를 생성하고 관리 할 수 있습니다.
구문
다음 구문은 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 인덱스 필드
Atlas Vector Search 인덱스 정의에는 다음 필드가 사용됩니다.
옵션 | 유형 | 필요성 | 목적 |
---|---|---|---|
| 문서 배열 | 필수 사항 | 벡터 및 필터 필드를 인덱싱하려면 문서당 하나씩 지정합니다. 최소한 하나의 문서에 벡터 필드에 대한 필드 정의가 포함되어야 합니다. 선택적으로 부울, 날짜, 숫자, objectId, 문자열 및 UUID 필드를 문서당 하나씩 인덱싱하여 데이터를 사전 필터링할 수 있습니다. |
| 문자열 | 필수 사항 |
|
| 문자열 | 필수 사항 | 인덱싱할 필드의 이름입니다. 중첩된 필드의 경우 점 표기법을 사용하여 임베디드 필드의 경로를 지정합니다. 두 개의 연속된 점이나 점으로 끝나는 필드 이름은 인덱싱할 수 없습니다. 예를 들어 Atlas Vector Search는 |
| int | 필수 사항 | Atlas Vector Search 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다.
이 필드 |
| 문자열 | 필수 사항 | 상위 K-최근접 이웃을 검색하는 데 사용하는 벡터 유사성 함수입니다. 이 필드는
|
| 문자열 | 옵션 | 벡터에 대한 자동 벡터 양자화 유형입니다. 벡터에 적용 할 양자화 유형을 지정할 수 있습니다. 임베딩이
정밀도가 중요한 경우 |
vector
유형 정보
인덱스 정의의 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
- 벡터의 끝과 끝 사이의 거리를 측정합니다. 이 값을 통해 다양한 차원을 기준으로 유사성을 측정할 수 있습니다. 자세히 알아보려면 Euclidean을 참조하세요.cosine
- 벡터 사이의 각도를 기준으로 유사성을 측정합니다. 이 값을 사용하면 크기에 따라 배율이 조정되지 않는 유사성을 측정할 수 있습니다.cosine
에는 크기가 0인 벡터를 사용할 수 없습니다. 코사인 유사성을 측정하려면 벡터를 정규화하고 대신dotProduct
를 사용하는 것이 좋습니다.dotProduct
-cosine
과 같이 유사성을 측정하지만 벡터의 크기를 고려합니다. 크기를 정규화하면 유사성 측정에서cosine
과dotProduct
는 거의 동일합니다.dotProduct
를 사용하려면 인덱스 타임 및 쿼리 타임에 벡터를 단위 길이로 정규화해야 합니다.
다음 표는 다양한 유형에 대한 유사성 함수를 보여줍니다.
벡터 임베딩 유형 | euclidean | cosine | dotProduct |
---|---|---|---|
| √ | ||
| √ | √ | √ |
| √ | √ | √ |
| √ | √ | √ |
벡터 수집용입니다.
자동 스칼라 또는 이진 양자화에 사용됩니다.
최상의 성능을 위해 임베딩 모델을 확인하여 임베딩 모델의 교육 프로세스 에 맞는 유사성 함수를 확인하세요. 지침 이 없는 경우 dotProduct
(으)로 시작하세요. fields.similarity
을 dotProduct
값으로 설정하면 각도와 크기를 기준으로 유사성을 효율적으로 측정할 수 있습니다. dotProduct
은 cosine
보다 계산 리소스를 덜 소비하며 벡터의 길이가 단위일 때 효율적입니다. 그러나 벡터가 정규화되지 않은 경우 euclidean
거리 및 cosine
유사성에 대한 샘플 쿼리 결과의 유사성 점수를 평가하여 어느 것이 합리적인 결과에 해당하는지 결정합니다.
filter
유형 정보
선택적으로 부울, 날짜, 숫자, 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 Vector Search 인덱스 생성
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
요청을 보냅니다.
1 curl --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 }'
엔드포인트의 구문 및 매개변수에 대해 자세히 알아보려면 Atlas Search 인덱스 1개 생성을 참조하세요.
예시
다음 인덱스 정의는 plot_embedding
필드를 vector
유형으로 인덱싱합니다. plot_embedding
필드에는 OpenAI의 text-embedding-ada-002
임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536
벡터 차원을 지정하고 dotProduct
함수를 사용하여 유사성을 측정합니다.
다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드만 인덱싱합니다.
1 curl --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
)입니다.
1 curl --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 인덱스를 생성하려면 다음 단계를 수행하세요.
.json
파일을 만들고 해당 파일에 인덱스를 정의합니다.
인덱스 정의는 다음 형식과 유사해야 합니다.
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
이라는 파일을 만듭니다.
다음 자리 표시자 값을 바꾸고 파일을 저장합니다.
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스의 이름입니다. 인덱스 이름을 생략하는 경우 Atlas Vector Search는 인덱스 이름을 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
예시
다음 인덱스 정의를 복사하여 vector-index.json
파일 에 붙여넣습니다. 다음 인덱스 정의는 Atlas Vector Search 인덱스 에서 plot_embedding
필드 vector
유형으로, genres
및 year
필드를 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 }
다음 명령을 실행하여 인덱스를 생성합니다.
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 클러스터 검색 인덱스 생성 명령을 참조하세요.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
인덱스 구성을 시작합니다.
페이지에서 다음 항목을 선택한 후 Next를 클릭합니다.
Search Type | Vector Search 인덱스 유형을 선택합니다. |
Index Name and Data Source | 다음 정보를 지정합니다.
|
Configuration Method | For a guided experience, select Visual Editor. To edit the raw index definition, select JSON Editor. |
인덱스 정의를 지정합니다.
Atlas는 벡터 임베딩을 포함하는 필드와 해당 차원을 자동으로 감지하고 최대 세 개의 벡터 필드를 미리 채웁니다. 인덱스를 구성하려면 다음을 수행합니다.
필요한 경우 Path 드롭다운에서 인덱싱할 벡터 필드를 선택합니다.
Add Another Field를 선택하여 추가 필드를 인덱싱합니다.
Similarity Method 드롭다운 메뉴에서 인덱싱된 각 필드에 대한 유사성 메서드를 지정합니다.
(선택 사항) Advanced를 클릭하고 드롭다운 메뉴에서 Scalar 또는 Binary 양자화를 선택하여 필드의 임베딩을 자동으로 양자화합니다.
(선택 사항) Filter Field 섹션에서 데이터를 필터링할 수 있도록 컬렉션의 다른 필드를 지정합니다.
Atlas Vector Search 인덱스 설정에 대해 자세히 알아보려면 벡터 검색을 위해 필드를 인덱싱하는 방법을 참조하세요.
예시
embedded_movies
컬렉션에 대해 plot_embedding
필드가 표시됩니다.
인덱스를 구성하려면 Similarity Method 드롭다운에서 Dot Product를 선택합니다.
이 인덱스 정의는 벡터 임베딩 필드 (plot_embedding
)만 인덱싱하여 벡터 검색을 수행합니다.
embedded_movies
컬렉션에 대해 plot_embedding
필드가 표시됩니다.
인덱스를 구성하려면 다음을 수행합니다.
Similarity Method 드롭다운 메뉴에서 Dot Product을(를) 선택합니다.
Advanced를 클릭한 후 드롭다운 메뉴에서 Scalar 양자화를 선택합니다.
Filter Field 섹션에서 데이터를 필터링할
genres
및year
필드를 지정합니다.
이 인덱스 정의는 다음 필드를 인덱싱합니다:
데이터를 사전 필터링하기 위한 문자열 필드(
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 }
인덱스의 필드에 대해 자세히 알아보려면 벡터 검색을 위한 필드 인덱싱 방법을 참조하세요.
예시
다음 인덱스 정의는 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 }
mongosh
v2.1.2 이상을 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 만들려면 다음 단계를 수행하세요.
mongosh
를 사용하여 Atlas 클러스터에 연결합니다.
자세한 내용은 mongosh
를 통한 연결을 참조하세요.
db.collection.createSearchIndex()
메서드를 실행합니다.
db.collection.createSearchIndex()
메서드의 구문은 다음과 같습니다.
1 db.<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를 수행하기 위해 벡터 임베딩 필드만 인덱싱합니다.
1 db.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
)입니다.
1 db.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 인덱스를 생성하려면 다음 단계를 수행하세요.
.cs
파일을 만들고 해당 파일에 인덱스를 정의합니다.
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 using System; 4 using System.Threading; 5 6 // Connect to your Atlas deployment 7 private const string MongoConnectionString = "<connectionString>"; 8 var client = new MongoClient(MongoConnectionString); 9 10 // Access your database and collection 11 var database = client.GetDatabase("<databaseName>"); 12 var collection = database.GetCollection<BsonDocument>("<collectionName>"); 13 14 // Create your index model, then create the search index 15 var name = "<indexName>"; 16 var type = SearchIndexType.VectorSearch; 17 18 var 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 33 var model = new CreateSearchIndexModel(name, type, definition); 34 35 var searchIndexView = collection.SearchIndexes; 36 searchIndexView.CreateOne(model); 37 Console.WriteLine($"New search index named {name} is building."); 38 39 // Wait for initial sync to complete 40 Console.WriteLine("Polling to check if the index is ready. This may take up to a minute."); 41 bool queryable = false; 42 while (!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 } 57 Console.WriteLine($"{name} is ready for querying.");
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 using System; 4 using System.Threading; 5 6 // Connect to your Atlas deployment 7 private const string MongoConnectionString = "<connectionString>"; 8 var client = new MongoClient(MongoConnectionString); 9 10 // Access your database and collection 11 var database = client.GetDatabase("<databaseName>"); 12 var collection = database.GetCollection<BsonDocument>("<collectionName>"); 13 14 // Create your index models and add them to an array 15 var type = SearchIndexType.VectorSearch; 16 17 var 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 }; 31 var modelOne = new CreateSearchIndexModel("<indexName>", type, definitionOne); 32 33 var 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 }; 47 var modelTwo = new CreateSearchIndexModel("<indexName>", type, definitionTwo); 48 49 var models = new CreateSearchIndexModel[] { modelOne, modelTwo }; 50 51 // Create the search indexes 52 var searchIndexView = collection.SearchIndexes; 53 searchIndexView.CreateMany(models); 54 55 Console.WriteLine($"New search indexes are building. This may take up to a minute.");
예시
IndexService.cs
이라는 파일을 만듭니다.
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
예시
다음을 복사하여 IndexService.cs
에 붙여넣고 <connectionString>
자리 표시자 값을 바꿉니다. 다음 인덱스 정의는 Atlas Vector Search 인덱스 에서 plot_embedding
필드 vector
유형으로, genres
및 year
필드를 filter
유형으로 인덱싱합니다. plot_embedding
필드 에는 OpenAI의 text-embedding-ada-002
임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536
벡터 차원을 지정하고 dotProduct
함수를 사용하여 유사성을 측정합니다.
다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드(plot_embedding
)만 인덱싱합니다.
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 using System; 6 using System.Threading; 7 8 public 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
)입니다.
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 using System; 6 using System.Threading; 7 8 public 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 }
MongoDB Go 드라이버 v2.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 생성하려면 다음 단계를 수행하세요.
create-index.go
파일 만들고 파일에 인덱스 정의합니다.
1 package main 2 3 import ( 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 13 func 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 운전자 의 구문을 보여줍니다.
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
예시
다음을 복사하여 create-index.go
파일 에 붙여넣고 <connectionString>
자리 표시자 값을 바꿉니다. 다음 인덱스 정의는 Atlas Vector Search 인덱스 에서 plot_embedding
필드 vector
유형으로, genres
및 year
필드를 filter
유형으로 인덱싱합니다. plot_embedding
필드 에는 OpenAI의 text-embedding-ada-002
임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536
벡터 차원을 지정하고 dotProduct
함수를 사용하여 유사성을 측정합니다.
다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드(plot_embedding
)만 인덱싱합니다.
1 package main 2 3 import ( 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 14 func 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
)입니다.
1 package main 2 3 import ( 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 14 func 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 }
MongoDB Java 드라이버 v5.2.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 생성하려면 다음 단계를 수행하세요.
.java
파일을 만들고 해당 파일에 인덱스를 정의합니다.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.model.SearchIndexModel; 6 import com.mongodb.client.model.SearchIndexType; 7 import org.bson.Document; 8 import org.bson.conversions.Bson; 9 10 import java.util.Arrays; 11 import java.util.Collections; 12 import java.util.List; 13 14 public 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 }
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
다음은 인덱스 정의 예시입니다.
Atlas Vector Search 인덱스에서
plot_embedding
필드 를vector
유형으로,genres
및year
필드를filter
유형으로 인덱싱합니다.plot_embedding
필드를 OpenAI의text-embedding-ada-002
임베딩 모델을 사용하여 만든 임베딩을 포함하는 벡터 임베딩 필드로 지정합니다.1536
벡터 차원을 지정하고dotProduct
함수를 사용하여 유사성을 측정합니다.
이 인덱스 정의는 벡터 임베딩 필드 (plot_embedding
)만 인덱싱하여 벡터 검색을 수행합니다.
복사하여 만든 파일에 다음을 붙여넣고 <connectionString>
자리 표시자 값을 바꿉니다.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.model.SearchIndexModel; 6 import com.mongodb.client.model.SearchIndexType; 7 import org.bson.Document; 8 import org.bson.conversions.Bson; 9 10 import java.util.Collections; 11 import java.util.List; 12 13 public 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>
자리 표시자 값을 바꿉니다.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.model.SearchIndexModel; 6 import com.mongodb.client.model.SearchIndexType; 7 import org.bson.Document; 8 import org.bson.conversions.Bson; 9 10 import java.util.Arrays; 11 import java.util.Collections; 12 import java.util.List; 13 14 public 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 }
MongoDB Node 드라이버 v6.6.0 이상을 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 만들려면 다음 단계를 수행하세요.
.js
파일을 만들고 해당 파일에 인덱스를 정의합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 57 run().catch(console.dir);
예시
vector-index.js
이라는 파일을 만듭니다.
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
예시
다음을 복사하여 vector-index.js
파일 에 붙여넣고 <connectionString>
자리 표시자 값을 바꿉니다. 다음 인덱스 정의는 Atlas Vector Search 인덱스 에서 plot_embedding
필드 vector
유형으로, genres
및 year
필드를 filter
유형으로 인덱싱합니다. plot_embedding
필드 에는 OpenAI의 text-embedding-ada-002
임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536
벡터 차원을 지정하고 dotProduct
함수를 사용하여 유사성을 측정합니다.
다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드(plot_embedding
)만 인덱싱합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 54 run().catch(console.dir);
이 인덱스 정의는 다음 필드를 인덱싱합니다:
데이터를 사전 필터링하기 위한 문자열 필드(
genres
) 및 숫자 필드(year
).사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(
plot_embedding
)입니다.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 62 run().catch(console.dir);
이 예시의 실행 가능한 버전을 Python 노트북으로 작업하세요.
PyMongo 드라이버 v4.7 이상을 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 생성하려면 다음 단계를 수행하세요.
.py
파일을 만들고 해당 파일에 인덱스를 정의합니다.
1 import pymongo 2 from pymongo.mongo_client import MongoClient 3 from pymongo.operations import SearchIndexModel 4 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 model, then create the search index 14 search_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 34 result = collection.create_search_index(model=search_index_model) 35 print("New search index named " + result + " is building.") 36 37 # Wait for initial sync to complete 38 print("Polling to check if the index is ready. This may take up to a minute.") 39 predicate=None 40 if predicate is None: 41 predicate = lambda index: index.get("queryable") is True 42 43 while True: 44 indices = list(collection.list_search_indexes(result)) 45 if len(indices) and predicate(indices[0]): 46 break 47 time.sleep(5) 48 print(result + " is ready for querying.") 49 50 client.close()
자세한 내용은 create_search_index() 메서드.
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 def 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
이라는 파일을 만듭니다.
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
예시
다음을 복사하여 vector-index.py
에 붙여넣고 <connectionString>
자리 표시자 값을 바꿉니다. 다음 인덱스 정의는 Atlas Vector Search 인덱스 에서 plot_embedding
필드 vector
유형으로, genres
및 year
필드를 filter
유형으로 인덱싱합니다. plot_embedding
필드 에는 OpenAI의 text-embedding-ada-002
임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536
벡터 차원을 지정하고 dotProduct
함수를 사용하여 유사성을 측정합니다.
이 예시의 실행 가능한 버전을 Python 노트북으로 작업하세요.
다음 인덱스 정의는 벡터 Atlas Search를 수행하기 위해 벡터 임베딩 필드(plot_embedding
)만 인덱싱합니다.
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 import time 4 5 # Connect to your Atlas deployment 6 uri = "<connectionString>" 7 client = MongoClient(uri) 8 9 # Access your database and collection 10 database = client["sample_mflix"] 11 collection = database["embedded_movies"] 12 13 # Create your index model, then create the search index 14 search_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 30 result = collection.create_search_index(model=search_index_model) 31 print("New search index named " + result + " is building.") 32 33 # Wait for initial sync to complete 34 print("Polling to check if the index is ready. This may take up to a minute.") 35 predicate=None 36 if predicate is None: 37 predicate = lambda index: index.get("queryable") is True 38 39 while True: 40 indices = list(collection.list_search_indexes(result)) 41 if len(indices) and predicate(indices[0]): 42 break 43 time.sleep(5) 44 print(result + " is ready for querying.") 45 46 client.close()
이 예시의 실행 가능한 버전을 Python 노트북으로 작업하세요.
이 인덱스 정의는 다음 필드를 인덱싱합니다:
데이터를 사전 필터링하기 위한 문자열 필드(
genres
) 및 숫자 필드(year
).사전 필터링된 데이터에 대해 벡터 Atlas Search를 수행하기 위한 벡터 임베딩 필드(
plot_embedding
)입니다.
1 from pymongo.mongo_client import MongoClient 2 from pymongo.operations import SearchIndexModel 3 import time 4 5 # Connect to your Atlas deployment 6 uri = "<connectionString>" 7 client = MongoClient(uri) 8 9 # Access your database and collection 10 database = client["sample_mflix"] 11 collection = database["embedded_movies"] 12 13 # Create your index model, then create the search index 14 search_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 38 result = collection.create_search_index(model=search_index_model) 39 print("New search index named " + result + " is building.") 40 41 # Wait for initial sync to complete 42 print("Polling to check if the index is ready. This may take up to a minute.") 43 predicate=None 44 if predicate is None: 45 predicate = lambda index: index.get("queryable") is True 46 47 while True: 48 indices = list(collection.list_search_indexes(result)) 49 if len(indices) and predicate(indices[0]): 50 break 51 time.sleep(5) 52 print(result + " is ready for querying.") 53 54 client.close()
Atlas Vector Search 인덱스 보기
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
요청을 보내세요.
1 curl --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}"
엔드포인트의 구문과 파라미터에 대해 자세히 알아보려면 하나의 컬렉션에 대해 모든 Atlas Search 인덱스 반환을 참조하세요.
Atlas 관리 API를 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스 한 개를 조회하려면 조회할 인덱스의 고유 ID 또는 이름(4 행)과 함께 Atlas Search indexes
엔드포인트에 GET
요청을 보내세요.
1 curl --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 인덱스를 반환하려면 다음 단계를 수행하세요.
다음 명령을 실행하여 컬렉션의 인덱스를 조회합니다.
atlas clusters search indexes list --clusterName [cluster_name] --db <db-name> --collection <collection-name>
명령에서 다음 자리 표시자 값을 바꿉니다.
cluster-name
- 인덱싱된 컬렉션을 포함하는 Atlas 클러스터의 이름입니다.db-name
- 인덱스를 조회하려는 컬렉션이 포함된 데이터베이스의 이름입니다.collection-name
- 인덱스를 검색하려는 컬렉션의 이름입니다.
명령 구문 및 매개변수에 대해 자세히 알아보려면 Atlas 클러스터 검색 인덱스 목록 명령에 대한 Atlas CLI 문서를 참조하세요.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
이 페이지에는 페이지의 인덱스에 대한 다음과 같은 세부 정보가 표시됩니다.
이름 | 인덱스를 식별하는 레이블입니다. |
인덱스 유형 | Atlas Search 또는 Atlas Vector Search 인덱스를 나타내는 레이블입니다. 값에는 다음이 포함됩니다.
|
인덱스 필드 | 이 인덱스가 인덱싱하는 필드가 포함된 목록입니다. |
상태 | 클러스터 의 프라이머리 노드 에 있는 인덱스 의 현재 상태 . 유효한 값은 인덱스 상태를 참조하세요. |
size | 프라이머리 노드에 있는 인덱스의 크기입니다. |
문서 | collection의 총 문서 수 중 인덱스된 문서 수입니다. |
작업 | 인덱스에 대해 수행할 수 있는 조치입니다. 다음을 수행할 수 있습니다.
|
mongosh
를 사용하여 컬렉션의 Atlas Vector Search 인덱스를 보려면 다음 단계를 수행하세요.
mongosh
를 사용하여 Atlas 클러스터에 연결합니다.
자세한 내용은 mongosh
를 통한 연결을 참조하세요.
db.collection.getSearchIndexes()
메서드를 실행합니다.
db.collection.getSearchIndexes()
메서드의 구문은 다음과 같습니다.
1 db.<collectionName>.getSearchIndexes( "<index-name>" );
C# 드라이버 3.1.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 보려면 다음 단계를 수행하세요.
.cs
파일을 만들고 .List()
메서드를 사용하여 컬렉션의 인덱스를 조회합니다.
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 6 public 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 }
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오. |
| 컬렉션이 포함된 데이터베이스의 이름입니다. |
| 컬렉션의 이름입니다. |
MongoDB 고 (Go) 운전자 v2.0 이상을 사용하는 컬렉션 에 대한 Atlas Vector Search 인덱스 보려면 다음 단계를 수행하세요.
get-index.go
이라는 파일 만들고 SearchIndexes().List()
메서드를 사용하여 인덱스 조회 .
1 package main 2 3 import ( 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 14 func 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 }
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오. |
| 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 검색하려는 컬렉션입니다. |
| 특정 인덱스 조회 하려는 경우 인덱스 의 이름입니다. 컬렉션 의 모든 인덱스를 반환하려면 검색 인덱스 옵션을 생성할 때 이 값을 생략하고 |
MongoDB Java 드라이버 v5.2.0 이상을 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 보려면 다음 단계를 수행하십시오.
.java
파일을 만들고 listSearchIndexes()
메서드를 사용하여 인덱스를 조회합니다.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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 }
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오. |
| 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 검색하려는 컬렉션입니다. |
| 특정 인덱스를 검색하려는 경우 인덱스의 이름입니다. 컬렉션의 모든 인덱스를 반환하려면 이 값을 생략합니다. |
MongoDB Node driver v6.6.0 이상을 사용하여 컬렉션의 Atlas 벡터 검색 인덱스를 보려면 다음 단계를 수행하세요.
.js
파일을 만들고 listSearchIndexes()
메서드를 사용하여 인덱스를 조회합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 20 run().catch(console.dir);
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오. |
| 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 검색하려는 컬렉션입니다. |
| 특정 인덱스를 검색하려는 경우 인덱스의 이름입니다. 컬렉션의 모든 인덱스를 반환하려면 이 값을 생략합니다. |
이 예시의 실행 가능한 버전을 Python 노트북으로 작업하세요.
PyMongo 드라이버 v4.7 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 보려면 다음 단계를 수행하세요.
.py
파일을 만들고 list_search_indexes()
메서드를 사용하여 컬렉션의 인덱스를 조회합니다.
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 # Get a list of the collection's search indexes and print them 12 cursor = collection.list_search_indexes() 13 for index in cursor: 14 print(index)
자세한 내용은 list_search_indexes() 메서드를 참조하세요.
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오. |
| 컬렉션이 포함된 데이터베이스의 이름입니다. |
| 컬렉션의 이름입니다. |
Atlas Vector Search 인덱스 편집
기존 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
요청을 보냅니다.
1 curl --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 인덱스를 편집하려면 다음 단계를 수행하세요.
.json
파일을 만들고 해당 파일의 인덱스에 대한 변경 사항을 정의합니다.
인덱스 정의는 다음 형식과 유사해야 합니다.
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 }
다음 자리 표시자 값을 바꾸고 파일을 저장합니다.
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스의 이름입니다. 인덱스 이름을 생략하는 경우 Atlas Vector Search는 인덱스 이름을 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
다음 명령을 실행하여 인덱스를 업데이트합니다.
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 클러스터 검색 인덱스 업데이트를 참조하세요.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
인덱스를 편집합니다.
편집할
vectorSearch
유형 인덱스를 찾습니다.해당 인덱스의 Actions 열에서 아이콘을 클릭합니다.
Edit With Visual Editor를 선택하여 안내에 따라 진행하거나 Edit With JSON Editor를 선택하여 원시 인덱스 정의를 편집합니다.
현재 구성 설정을 검토하고 필요에 따라 편집합니다.
Atlas Vector Search 인덱스의 필드에 대해 자세히 알아보려면 벡터 검색을 위한 필드 인덱싱 방법을 참조하세요.
Save를 클릭하여 변경 사항을 적용하세요.
인덱스의 상태가 Active에서 Building으로 변경됩니다. 이 상태에서는 업데이트된 인덱스를 사용할 준비가 될 때까지 Atlas Vector Search가 이전 인덱스를 삭제하지 않으므로, 이전 인덱스를 계속 사용할 수 있습니다. 상태가 Active로 돌아가면 수정된 인덱스를 사용할 준비가 된 것입니다.
mongosh
를 사용하여 컬렉션의 Atlas Vector Search 인덱스를 편집하려면 다음 단계를 수행하세요.
mongosh
를 사용하여 Atlas 클러스터에 연결합니다.
자세한 내용은 mongosh
를 통한 연결을 참조하세요.
db.collection.updateSearchIndex()
메서드를 실행합니다.
db.collection.updateSearchIndex()
메서드의 구문은 다음과 같습니다.
1 db.<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 컬렉션의 인덱스를 업데이트하려면 다음 단계를 수행하세요.
.cs
파일을 만들고 해당 파일의 인덱스 변경 사항을 정의합니다.
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 6 public 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 }
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 Bame. 인덱스 이름을 생략하면 기본값은 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
MongoDB 고 (Go) 운전자 v2.0 이상을 사용하여 컬렉션 에 대한 Atlas Vector Search 인덱스 업데이트 하려면 다음 단계를 수행하세요.
edit-index.go
파일 만들고 파일 에서 인덱스 변경 사항을 정의합니다.
1 package main 2 3 import ( 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 12 func 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 }
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
MongoDB Java 드라이버 v5.2.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 편집하려면 다음 단계를 수행하세요.
.java
파일을 만들고 해당 파일의 인덱스 변경 사항을 정의합니다.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 import org.bson.conversions.Bson; 7 8 import java.util.Collections; 9 10 public 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 }
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
MongoDB Node 드라이버 v6.6.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 업데이트하려면 다음 단계를 수행하세요.
.js
파일을 만들고 해당 파일의 인덱스 변경 사항을 정의합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 41 run().catch(console.dir);
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
이 예시의 실행 가능한 버전을 Python 노트북으로 작업하세요.
PyMongo 드라이버 v4.7 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 업데이트하려면 다음 단계를 수행하세요.
.py
파일을 만들고 해당 파일의 인덱스 변경 사항을 정의합니다.
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 definition = { 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 29 collection.update_search_index("<indexName>", definition)
자세한 내용은 update_search_index() 메서드를 참조하세요.
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 string. 자세한 내용은 드라이버를 통한 연결을 참조하세요. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 Bame. 인덱스 이름을 생략하면 기본값은 |
| Atlas Vector Search가 인덱스 타임 및 쿼리 타임에 시행하는 벡터 차원의 수입니다. |
| 인덱싱할 벡터 및 필터 필드입니다. |
Atlas Vector Search 인덱스 삭제
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
요청을 전송하세요.
1 curl --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 인덱스를 삭제하려면 다음 단계를 수행합니다.
명령을 실행하여 인덱스를 삭제 합니다.
atlas clusters search indexes delete <indexId> [options]
명령에서 indexId
자리 표시자 값을 삭제할 인덱스의 고유 식별자로 바꿉니다.
명령 구문 및 매개변수에 대한 자세한 내용은 Atlas CLI 문서에서 Atlas 클러스터 검색 인덱스 삭제 명령을 참조하세요.
AtlasGo Atlas 에서 프로젝트 의 Clusters 페이지로 고 (Go) 합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.
아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.
아직 표시되지 않은 경우 사이드바에서 Clusters를 클릭합니다.
Clusters(클러스터) 페이지가 표시됩니다.
mongosh
를 사용하여 컬렉션의 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행하세요.
mongosh
를 사용하여 Atlas 클러스터에 연결합니다.
자세한 내용은 mongosh
를 통한 연결을 참조하세요.
db.collection.dropSearchIndex()
메서드를 실행합니다.
db.collection.dropSearchIndex()
메서드의 구문은 다음과 같습니다.
1 db.<collectionName>.dropSearchIndex( "<index-name>" );
C# 드라이버 3.1.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행하세요.
.cs
파일을 만들고 DropOne()
메서드를 사용하여 인덱스를 삭제합니다.
1 namespace query_quick_start; 2 3 using MongoDB.Bson; 4 using MongoDB.Driver; 5 6 public 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 }
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오. |
| 컬렉션이 포함된 데이터베이스의 이름입니다. |
| 컬렉션의 이름입니다. |
| 삭제할 인덱스의 이름입니다. |
MongoDB 고 (Go) 운전자 v2.0 이상을 사용하여 컬렉션 의 Atlas Vector Search 인덱스 삭제 하려면 다음 단계를 수행하세요.
delete-index.go
파일 만들고 SearchIndexes().DropOne()
메서드를 사용하여 인덱스 삭제.
1 package main 2 3 import ( 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 12 func 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 }
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
MongoDB Java 드라이버 v5.2.0 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행하세요.
.java
파일을 만들고 collection.dropSearchIndex()
메서드를 사용하여 인덱스를 삭제합니다.
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import org.bson.Document; 6 7 public 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 }
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
MongoDB Node 드라이버 v6.6.0 이상을 사용하여 컬렉션에 대한 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행하세요.
.js
파일을 만들고 dropSearchIndex()
메서드를 사용하여 인덱스를 삭제합니다.
1 const { MongoClient } = require("mongodb"); 2 3 // connect to your Atlas deployment 4 const uri = "<connectionString>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 20 run().catch(console.dir);
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오. |
| 인덱스를 생성하려는 컬렉션이 포함된 데이터베이스입니다. |
| 인덱스를 생성하려는 컬렉션입니다. |
| 인덱스 의 이름입니다. 인덱스 이름을 생략하면 기본값은 |
이 예시의 실행 가능한 버전을 Python 노트북으로 작업하세요.
PyMongo 드라이버 v4.7 이상을 사용하여 컬렉션의 Atlas Vector Search 인덱스를 삭제하려면 다음 단계를 수행하세요.
.py
파일을 만들고 drop_search_index()
메서드를 사용하여 인덱스를 삭제합니다.
1 from pymongo.mongo_client import MongoClient 2 3 # Connect to your Atlas deployment 4 uri = "<connectionString>" 5 client = MongoClient(uri) 6 7 # Access your database and collection 8 database = client["<databaseName>"] 9 collection = database["<collectionName>"] 10 11 # Delete your search index 12 collection.drop_search_index("<indexName>")
자세한 내용은 drop_search_index() 메서드를 참조하세요.
다음 값을 바꾸고 파일을 저장합니다.
| Atlas 연결 문자열입니다. 자세한 사항은 드라이버를 통해 연결을 참조하십시오. |
| 컬렉션이 포함된 데이터베이스의 이름입니다. |
| 컬렉션의 이름입니다. |
| 삭제할 인덱스의 이름입니다. |
인덱스 상태
Atlas Vector Search 인덱스를 생성하면 Status 열에 클러스터의 프라이머리 노드에 있는 인덱스의 현재 상태가 표시됩니다. 상태 아래에 있는 View status details 링크를 클릭하면 클러스터의 모든 노드에 있는 인덱스 상태를 볼 수 있습니다.
Status 열이 Active로 표시되면 인덱스가 사용할 준비가 된 것입니다. 다른 상태에서는 인덱스에 대한 쿼리가 불완전한 결과를 반환할 수 있습니다.
상태 | 설명 |
---|---|
시작되지 않음 | Atlas가 아직 인덱스 빌드를 시작하지 않았습니다. |
초기 동기화 | Atlas가 인덱스를 작성하거나 편집 후 인덱스를 다시 작성하고 있습니다. 인덱스가 이 상태인 경우 다음과 같습니다:
|
활성 | 인덱스를 사용할 준비가 되었습니다. |
복구 중 | 복제에 오류가 발생했습니다. 이 상태 일반적으로 |
실패하였습니다. | Atlas 인덱스 빌드 수 없습니다. View status details 모달 창 오류를 사용하여 문제를 해결하세요. 자세히 학습 문제 해결을 참조하세요. |
삭제 진행 중 | Atlas가 클러스터 노드에서 인덱스를 삭제하는 중입니다. |
Atlas가 인덱스를 빌드하는 동안 그리고 빌드가 완료된 후 Documents 열에 인덱싱된 문서의 백분율과 개수가 표시됩니다. 이 열에는 컬렉션의 총 문서 수도 표시됩니다.