对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

使用MongoDB Search 和 Vector Search

如果成功安装了 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客户端工具。在集群内运行 Pod 可简化与MongoDB的连接,而无需向外部公开数据库。

以下命令部署一个名为 mongodb-tools-pod 且运行MongoDB Community Server 映像的 Pod。使用 sleep infinity 命令让 Pod 保持运行,以便您使用 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 - 包含使用 Voyage AI 的 voyage-3-large 嵌入模型从 plot 字段创建,并转换为 binData 以实现高效存储和检索的 2048 维嵌入向量。

  • plot_embedding - 包含使用 OpenAI 的 text-embedding-ada-002 嵌入模型从 plot 字段创建的 1536d 嵌入,并转换为 binData 以便高效存储和检索。

movies

包含电影信息,其中包括发行年份、导演和评价。

sessions

theaters

包含电影院的位置。

users

包含用户信息。

以下命令下载示例数据集,并使用 mongorestore 将数据加载到MongoDB 部署中的 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搜索索引。动态映射会自动对所有可动态索引的字段类型进行索引。

    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>

要学习;了解有关创建索引和运行搜索查询的更多信息,请参阅:

给本页内容打分