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

MongoDB 검색 및 벡터 검색 사용

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

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

1

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

1# The env vars here are all commented out because this snippets module
2# is reusable across different MongoDB deployments and all the necessary variables
3# should be already defined there.
4
5# set it to the context name of the k8s cluster
6#export K8S_CTX="<local cluster context>"
7# the following namespace will be used to deploy mongodb tools pod
8#export MDB_NS="mongodb"
9
10# regular user performing restore and search queries on sample mflix database
11# the user should be able to restore database using mongorestore
12#export MDB_USER_PASSWORD="mdb-user-password-CHANGE-ME"
13
14# name of MongoDB or MongoDBCommunity resource in case it's deployed in the same cluster
15# user only for the connection string in MDB_CONNECTION_STRING env var below
16#export MDB_RESOURCE_NAME="mdbc-rs"
17
18# default connection string if MongoDB database is deployed using the operator
19#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}"
2

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

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

1kubectl apply -n "${MDB_NS}" --context "${K8S_CTX}" -f - <<EOF
2apiVersion: v1
3kind: Pod
4metadata:
5 name: mongodb-tools-pod
6 labels:
7 app: mongodb-tools
8spec:
9 containers:
10 - name: mongodb-tools
11 image: mongodb/mongodb-community-server:${MDB_VERSION%-ent}-ubi8
12 command: ["/bin/bash", "-c"]
13 args: ["sleep infinity"]
14 restartPolicy: Never
15EOF
16
17echo "Waiting for the mongodb-tools to be ready..."
18kubectl --context "${K8S_CTX}" -n "${MDB_NS}" wait \
19 --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(으)로 연결합니다.

1kubectl exec -n "${MDB_NS}" --context "${K8S_CTX}" \
2 mongodb-tools-pod -- /bin/bash -eu -c "$(cat <<EOF
3echo "Downloading sample database archive..."
4curl https://atlas-education.s3.amazonaws.com/sample_mflix.archive \
5 -o /tmp/sample_mflix.archive
6echo "Restoring sample database"
7mongorestore \
8 --archive=/tmp/sample_mflix.archive \
9 --verbose=1 \
10 --drop \
11 --nsInclude 'sample_mflix.*' \
12 --uri="${MDB_CONNECTION_STRING}"
13EOF
14)"
4

You can create a MongoDB Search or a Vector Search index. You must create a MongoDB Search index to run $search and $searchMeta queries and Vector Search index to run $vectorSearch queries.

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

  • Vector Search provides simple index definition that supports querying vector embeddings in your data based on semantic similarity by using ANN and ENN search algorithm. To learn more, see Define Vector Search Index.

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

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

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

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

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

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

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

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

After the index creation is successful, you can run MongoDB Search or Vector Search queries using the index. You can also combine MongoDB Search with Vector Search. To learn more about running MongoDB Search queries, see Define Your Query. To learn more about Vector Search queries, see Run Vector Search ANN and ENN Queries.

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

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

1mdb_script=$(cat <<'EOF'
2use sample_mflix;
3db.movies.aggregate([
4 {
5 $search: {
6 "compound": {
7 "must": [ {
8 "text": {
9 "query": "baseball",
10 "path": "plot"
11 }
12 }],
13 "mustNot": [ {
14 "text": {
15 "query": ["Comedy", "Romance"],
16 "path": "genres"
17 }
18 } ]
19 },
20 "sort": {
21 "released": -1
22 }
23 }
24 },
25 {
26 $limit: 3
27 },
28 {
29 $project: {
30 "_id": 0,
31 "title": 1,
32 "plot": 1,
33 "genres": 1,
34 "released": 1
35 }
36 }
37]);
38EOF
39)
40
41kubectl exec --context "${K8S_CTX}" -n "${MDB_NS}" \
42 mongodb-tools-pod -- /bin/bash -eu -c "$(cat <<EOF
43echo '${mdb_script}' > /tmp/mdb_script.js
44mongosh --quiet "${MDB_CONNECTION_STRING}" < /tmp/mdb_script.js
45EOF
46)"
1mdbc-rs [primary] test> switched to db sample_mflix
2mdbc-rs [primary] sample_mflix> ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... [
3 {
4 plot: 'A sports agent stages an unconventional recruitment strategy to get talented Indian cricket players to play Major League Baseball.',
5 genres: [ 'Biography', 'Drama', 'Sport' ],
6 title: 'Million Dollar Arm',
7 released: ISODate('2014-05-16T00:00:00.000Z')
8 },
9 {
10 plot: 'A Taiwanese high school baseball team travels to Japan in 1931 to compete in a national tournament.',
11 genres: [ 'Biography', 'Drama', 'History' ],
12 title: 'Kano',
13 released: ISODate('2014-02-27T00:00:00.000Z')
14 },
15 {
16 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 ...",
17 genres: [ 'Drama' ],
18 title: 'Calloused Hands',
19 released: ISODate('2013-03-03T00:00:00.000Z')
20 }
21]
22mdbc-rs [primary] sample_mflix>

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

이 페이지 평가하기

이 페이지의 내용