AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.

MongoDB 검색 및 벡터 검색 사용

MongoDBSearch 리소스를 성공적으로 설치한 경우, MongoDB 검색 및 Vector 검색 검색 인덱스를 mdb-user (으)로 생성하고 인덱스를 사용하여 MongoDB 검색 및 Vector 검색 검색 쿼리를 실행할 수 있습니다. 이 페이지에서는 샘플 데이터를 로드하고, 데이터에 대한 MongoDB 검색 인덱스 및 Vector 검색 인덱스를 만들고, 데이터에 대해 MongoDB 검색 쿼리 및 Vector 검색 쿼리를 실행하는 방법을 설명합니다.

MongoDB Search 및 Vector Search를 사용하려면 다음이 필요합니다.

1
  1. 이 절차의 후속 단계에서 사용할 환경 변수를 설정하다 하려면 다음을 복사하고 환경 변수의 값을 설정하다 다음 환경 변수를 로드합니다.

    # The env vars here are all commented out because this snippets module# is reusable across different MongoDB deployments and all the necessary variables# should be already defined there. # set it to the context name of the k8s cluster#export K8S_CTX="<local cluster context>"# the following namespace will be used to deploy mongodb tools pod#export MDB_NS="mongodb" # regular user performing restore and search queries on sample mflix database# the user should be able to restore database using mongorestore#export MDB_USER_PASSWORD="mdb-user-password-CHANGE-ME" # name of MongoDB or MongoDBCommunity resource in case it's deployed in the same cluster# user only for the connection string in MDB_CONNECTION_STRING env var below#export MDB_RESOURCE_NAME="mdbc-rs" # TLS-related resources used by the snippets in this module#export MDB_TLS_CA_SECRET_NAME="${MDB_RESOURCE_NAME}-ca"#export MDB_TLS_CA_CONFIGMAP="${MDB_RESOURCE_NAME}-ca-configmap"#export MDB_TLS_SERVER_CERT_SECRET_NAME="${MDB_RESOURCE_NAME}-tls"#export MDB_SEARCH_TLS_SECRET_NAME="${MDB_RESOURCE_NAME}-search-tls" # default connection string if MongoDB database is deployed using the operator#export MDB_CONNECTION_STRING="mongodb://mdb-user:${MDB_USER_PASSWORD}@${MDB_RESOURCE_NAME}-0.${MDB_RESOURCE_NAME}-svc.${MDB_NS}.svc.cluster.local:27017/?replicaSet=${MDB_RESOURCE_NAME}"# To enable TLS for the shared snippets, append driver options directly to the connection string, for example:#export MDB_CONNECTION_STRING="mongodb://mdb-user:${MDB_USER_PASSWORD}@${MDB_RESOURCE_NAME}-0.${MDB_RESOURCE_NAME}-svc.${MDB_NS}.svc.cluster.local:27017/?replicaSet=${MDB_RESOURCE_NAME}&tls=true&tlsCAFile=/tls/ca.crt"
  2. env_variables.sh 파일 에 표시된 (27 줄)에 표시된 대로 TLS 활성화 연결 문자열 사용하여 연결하려면 mongosh 클라이언트 참조할 수 있도록 MongoDBSearch 서비스에 대한 공용 CA 인증서를 다운로드 .

2

mongodb-tools-pod 이라는 이름의 Pod를 배포하여 Kubernetes 클러스터 내에서 mongosh 및 mongorestore 와 같은 MongoDB 클라이언트 도구를 실행 . 클러스터 내부에서 파드를 실행하면 데이터베이스 외부에 노출할 필요 없이 MongoDB 에 대한 연결이 간소화됩니다.

다음 명령은 MongoDB Community 서버 이미지를 실행하는 mongodb-tools-pod 이라는 포드를 배포합니다. 포드는 sleep infinity 명령으로 계속 실행 되어 kubectl exec 를 사용하여 MongoDB 클라이언트 도구를 실행 수 있습니다.

kubectl apply -n "${MDB_NS}" --context "${K8S_CTX}" -f - <<EOFapiVersion: v1kind: Podmetadata: name: mongodb-tools-pod labels: app: mongodb-toolsspec: containers: - name: mongodb-tools image: mongodb/mongodb-community-server:${MDB_VERSION%-ent}-ubi8 command: ["/bin/bash", "-c"] args: ["sleep infinity"] volumeMounts: - name: mongo-ca mountPath: /tls readOnly: true restartPolicy: Never volumes: - name: mongo-ca configMap: name: ${MDB_TLS_CA_CONFIGMAP:-"${MDB_RESOURCE_NAME}-ca-configmap"} optional: true items: - key: ca.crt path: ca.crtEOF echo "Waiting for the mongodb-tools to be ready..."kubectl --context "${K8S_CTX}" -n "${MDB_NS}" wait --for=condition=Ready pod/mongodb-tools-pod --timeout=60s
3

다음 컬렉션이 포함된 sample_mflix 데이터베이스 가져옵니다.

컬렉션 이름
설명

comments

특정 영화와 관련된 댓글을 포함합니다.

embedded_movies

다음 추가 필드와 함께 movies 컬렉션 의 Western, Action 및 Fantasy 장르의 영화에 대한 세부 정보가 포함되어 있습니다.

  • plot_embedding_voyage_3_large - plot 필드에서 Voyage AI의 voyage-3-large 임베딩 모델을 사용하여 생성하고, 효율적인 저장 및 검색을 위해 binData 로 변환된 2048d 임베딩을 포함합니다.

  • plot_embedding - plot 필드에서 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성하고, 효율적인 저장 및 검색을 위해 binData로 변환된 1536d 임베딩을 포함합니다.

movies

개봉 연도, 감독, 리뷰 등의 영화 정보가 포함되어 있습니다.

sessions

theaters

영화관 위치를 포함합니다.

users

사용자 정보를 포함합니다.

다음 명령은 샘플 데이터 세트를 다운로드하고 mongorestore 을(를) 사용하여 MongoDB deployment 의 sample_mflix 데이터베이스 에 데이터를 로드하고, mdb-user(으)로 연결합니다.

# Restore sample_mflix database. Provide any TLS parameters directly within MDB_CONNECTION_STRING.kubectl exec -n "${MDB_NS}" --context "${K8S_CTX}" \ mongodb-tools-pod -- env MDB_CONNECTION_STRING="${MDB_CONNECTION_STRING}" /bin/bash -eu -c "$(cat <<'EOF'echo "Downloading sample database archive..."curl -fSL https://atlas-education.s3.amazonaws.com/sample_mflix.archive -o /tmp/sample_mflix.archive echo "Restoring sample database"mongorestore \ --archive=/tmp/sample_mflix.archive \ --verbose=1 \ --drop \ --nsInclude 'sample_mflix.*' \ --uri="${MDB_CONNECTION_STRING}"EOF)"
4

MongoDB Search 또는 Vector Search 인덱스 만들 수 있습니다. $search 및 $searchMeta 쿼리를 실행 하려면 MongoDB Search 인덱스 생성하고 $vectorSearch 쿼리를 실행 하려면 Vector Search 인덱스 생성해야 합니다.

  • MongoDB Search는 동적 및 정적 필드 매핑, 다양한 분석기(표준, 언어별, 사용자 지정)는 물론 동의어 및 패싯 검색 과 같은 기능을 지원 유연한 인덱스 정의를 제공합니다. 자세한 학습 은 인덱스 정의를 참조하세요.

  • 벡터 검색은 ANN 및 ENN 검색 알고리즘 사용하여 시맨틱 유사성을 기반으로 데이터의 벡터 임베딩을 쿼리할 수 있도록 지원하는 간단한 인덱스 정의를 제공합니다. 자세한 학습 은 벡터 검색 인덱스 정의를 참조하세요.

  1. 터미널에서 다음 명령을 복사하여 붙여넣은 후 실행 MongoDB Search 또는 Vector Search 인덱스 생성합니다.

    이 명령은 kubectl exec 를 사용하여 mongodb-tools-pod에서 mongosh 를 실행 . sample_mflix db.<collection>.createSearchIndex() 메서드에 연결하여 인덱스 생성합니다.

    다음 명령은 movies 컬렉션 에 동적 매핑을 사용하여 이름이 default 인 MongoDB Search 인덱스 생성합니다. 동적 매핑은 동적으로 인덱싱할 수 있는 모든 필드 유형을 자동으로 인덱싱합니다.

    kubectl exec --context "${K8S_CTX}" -n "${MDB_NS}" mongodb-tools-pod -- \ mongosh --quiet "${MDB_CONNECTION_STRING}" \ --eval "use sample_mflix" \ --eval 'db.movies.createSearchIndex("default", { mappings: { dynamic: true } });'
  2. 인덱스 생성이 완료될 때까지 기다립니다.

    인덱스 생성은 비동기식 프로세스 입니다. 다음 스크립트 실행하여 인덱스 생성이 완료될 때까지 60 초 동안 기다립니다.

    # Currently it's not possible to check the status of search indexes, we need to just waitecho "Sleeping to wait for search indexes to be created"sleep 60

    또는 다음 명령을 실행 컬렉션 의 인덱스 목록을 조회 .

    kubectl exec --context "${K8S_CTX}" -n "${MDB_NS}" mongodb-tools-pod -- \ mongosh --quiet "${MDB_CONNECTION_STRING}" \ --eval "use sample_mflix" \ --eval 'db.runCommand({"listSearchIndexes": "movies"});'
5

인덱스 생성이 성공적으로 완료되면 인덱스를 사용하여 MongoDB Search 또는 Vector Search 쿼리를 실행할 수 있습니다. MongoDB Search와 Vector Search를 결합할 수도 있습니다. MongoDB Search 쿼리 실행에 대해 자세히 알아보려면 쿼리 정의를 참조하세요. Vector Search 쿼리에 대해 자세히 알아보려면 Vector Search 근사 최근접 이웃 및 등가 최근접 이웃 쿼리를 실행하세요.

다음 스크립트 집계 파이프라인 쿼리 기준을 정의하고 kubectl exec 명령을 사용하여 mongosh 를 로드하여 쿼리 실행합니다.

다음 쿼리 plot 필드 에서 baseball이라는 텀 포함된 영화 줄거리를 검색합니다. comedy 및 romance 장르의 영화는 제외됩니다.

mdb_script=$(cat <<'EOF'use sample_mflix;db.movies.aggregate([ { $search: { "compound": { "must": [ { "text": { "query": "baseball", "path": "plot" } }], "mustNot": [ { "text": { "query": ["Comedy", "Romance"], "path": "genres" } } ] }, "sort": { "released": -1 } } }, { $limit: 3 }, { $project: { "_id": 0, "title": 1, "plot": 1, "genres": 1, "released": 1 } }]);EOF) kubectl exec --context "${K8S_CTX}" -n "${MDB_NS}" \ mongodb-tools-pod -- /bin/bash -eu -c "$(cat <<EOFecho '${mdb_script}' > /tmp/mdb_script.jsmongosh --quiet "${MDB_CONNECTION_STRING}" < /tmp/mdb_script.jsEOF)"
mdbc-rs [primary] test> switched to db sample_mflixmdbc-rs [primary] sample_mflix> ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... [ { plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.', genres: [ 'Biography', 'Drama', 'Sport' ], title: 'Million Dollar Arm', released: ISODate('2014-05-16T00:00:00.000Z') }, { plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.', genres: [ 'Biography', 'Drama', 'History' ], title: 'Kano', released: ISODate('2014-02-27T00:00:00.000Z') }, { plot: "12-year-old Josh is a mixed race boy and a promising baseball player. He is abused by his mother's boyfriend Byrd, and neglected by his mother Debbie. He forges his own path in life when ...", genres: [ 'Drama' ], title: 'Calloused Hands', released: ISODate('2013-03-03T00:00:00.000Z') }]mdbc-rs [primary] sample_mflix>

인덱스 생성 및 검색 쿼리 실행 에 대해 자세히 학습 다음을 참조하세요.

이 페이지 평가하기

이 페이지의 내용