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

安装和使用 MongoDB Community Edition

您可以使用Kubernetes 操作符 并部署mongot进程资源,以在Kubernetes集群上与MongoDB Community Edition v8.2.0 或更高版本一起运行。mongot进程支持MongoDB Search 和 向量搜索。或者,您可以启用和配置向量搜索,使用支持的 Voyage AI嵌入模型为集合和查询中的文本数据自动生成向量嵌入。

重要

自动嵌入处于预览状态。在预览期间,该功能和相应的文档可能随时更改。要学习;了解更多信息,请参阅预览功能。

以下过程演示了如何在 Kubernetes 集群中部署和配置 MongoDB Search 和 向量搜索,以与新的或现有的副本集一起运行。该部署使用 TLS 证书来确保 MongoDB 节点与 mongot 搜索进程之间的安全通信。

要部署MongoDB Search 和 Vector Search,您必须具备以下条件:

  • 正在运行的 Kubernetes 集群。

  • Kubernetes命令行工具 kubectl,配置为与集群通信。

  • Helm( Kubernetes的包管理器),用于安装Kubernetes Operator。

  • cert-manager 或用于 TLS 证书预配的替代证书管理解决方案。

  • Bash v5.1 或更高版本,用于运行本教程中的命令。

或者,要将向量搜索配置为自动为集合和查询中的文本数据生成向量嵌入,您必须为嵌入服务创建API密钥。我们建议创建两个键,一个用于在索引时为集合中的文本数据生成嵌入,另一个用于在查询时为查询文本生成嵌入。如果您没有密钥,可以从Atlas用户界面创建密钥。

1

设置环境变量以供本过程中的后续步骤使用。复制以下命令,更新环境的值,然后运行这些命令以加载变量:

# set it to the context name of the k8s clusterexport K8S_CTX="<local cluster context>" # the following namespace will be created if not existsexport MDB_NS="mongodb" # MongoDBCommunity resource name referenced throughout the guideexport MDB_RESOURCE_NAME="mdbc-rs"# Number of replica set members deployed in the sample MongoDBCommunityexport MDB_MEMBERS=3 # TLS-related secret names used for MongoDBCommunity and MongoDBSearchexport MDB_TLS_CA_SECRET_NAME="${MDB_RESOURCE_NAME}-ca"export MDB_TLS_SERVER_CERT_SECRET_NAME="${MDB_RESOURCE_NAME}-tls"export MDB_SEARCH_TLS_SECRET_NAME="${MDB_RESOURCE_NAME}-search-tls" export MDB_TLS_CA_CONFIGMAP="${MDB_RESOURCE_NAME}-ca-configmap"export MDB_TLS_SELF_SIGNED_ISSUER="${MDB_RESOURCE_NAME}-selfsigned-cluster-issuer"export MDB_TLS_CA_CERT_NAME="${MDB_RESOURCE_NAME}-selfsigned-ca"export MDB_TLS_CA_ISSUER="${MDB_RESOURCE_NAME}-cluster-issuer" # minimum required MongoDB version for running MongoDB Search is 8.2.0export MDB_VERSION="8.2.0" # root admin user for convenience, not used here at all in this guideexport MDB_ADMIN_USER_PASSWORD="admin-user-password-CHANGE-ME"# regular user performing restore and search queries on sample mflix databaseexport MDB_USER_PASSWORD="mdb-user-password-CHANGE-ME"# user for MongoDB Search to connect to the replica set to synchronise data fromexport MDB_SEARCH_SYNC_USER_PASSWORD="search-sync-user-password-CHANGE-ME" export OPERATOR_HELM_CHART="mongodb/mongodb-kubernetes"# comma-separated key=value pairs for additional parameters passed to the helm-chart installing the operatorexport OPERATOR_ADDITIONAL_HELM_VALUES="" # TLS is mandatory; connection string must include tls=trueexport 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" export CERT_MANAGER_NAMESPACE="cert-manager" # Vector Search auto embedding related configurationsexport AUTO_EMBEDDING_API_KEY_SECRET_NAME="voyage-api-keys"export AUTO_EMBEDDING_API_QUERY_KEY="<embedding-model-query-key>"export AUTO_EMBEDDING_API_INDEXING_KEY="<embedding-model-indexing-key>"export PROVIDER_ENDPOINT="https://ai.mongodb.com/v1/embeddings"export EMBEDDING_MODEL="voyage-4"

注意

如果您有API密钥来启用向量搜索自动生成嵌入,请替换环境变量中的以下占位符值:

AUTO_EMBEDDING_API_QUERY_KEY

用于为查询文本生成嵌入的API密钥。

AUTO_EMBEDDING_API_INDEXING_KEY

在索引时为集合中的文本数据生成嵌入的API密钥。

PROVIDER_ENDPOINT

嵌入模型提供商的终结点。从Atlas用户界面创建的密钥的默认值为 https://ai.mongodb.com/v1/embeddings。如果您直接从 Voyage AI创建API密钥,请替换为 https://api.voyageai.com/v1/embeddings。

2

Helm 自动部署和管理 Kubernetes 上的 MongoDB 实例。如果您已经拥有包含用于安装 Kubernetes 操作符的 Helm 图表的 Helm 存储库,请跳过此步骤。否则,请添加 Helm存储库。

要添加 Helm存储库,请复制、粘贴并运行以下命令:

helm repo add mongodb https://mongodb.github.io/helm-chartshelm repo update mongodbhelm search repo mongodb/mongodb-kubernetes
3

Kubernetes Operator 监视 MongoDBCommunity 和 MongoDBSearch 自定义资源,并管理MongoDB部署的生命周期。如果您已经安装了MongoDB Controllers for Kubernetes 操作符,请跳过此步骤。否则,请从您在上一步中添加的 Helm存储库安装MongoDB Controllers for Kubernetes Operator。

要在 mongodb 命名空间中安装 MongoDB Controllers for Kubernetes 操作符,请复制、粘贴并运行以下命令:

helm upgrade --install --debug --kube-context "${K8S_CTX}" \ --create-namespace \ --namespace="${MDB_NS}" \ mongodb-kubernetes \ ${OPERATOR_ADDITIONAL_HELM_VALUES:+--set ${OPERATOR_ADDITIONAL_HELM_VALUES}} \ "${OPERATOR_HELM_CHART}"
4

在继续MongoDB Search 和 向量搜索部署之前,确保Kubernetes Operator 完全运行。运行以下命令,验证所有操作符组件都在运行且可用。

kubectl --context "${K8S_CTX}" -n "${MDB_NS}" rollout status --timeout=2m deployment/mongodb-kubernetes-operatorecho "Operator deployment in ${MDB_NS} namespace"kubectl --context "${K8S_CTX}" -n "${MDB_NS}" get deploymentsecho; echo "Operator pod in ${MDB_NS} namespace"kubectl --context "${K8S_CTX}" -n "${MDB_NS}" get pods
5

MongoDB需要身份验证才能安全访问权限。在此步骤中,您将创建三个Kubernetes密钥:

  • mdb-admin-user-password: MongoDB管理员的档案。

  • mdb-user-password:授权执行搜索查询的用户的档案。

  • mdbc-rs-search-sync-source-password:专用搜索用户的档案,由 mongot进程在内部用于同步数据和管理索引。

Kubernetes 操作符使用这些密钥中的密码在 MongoDB 数据库中自动创建用户。

要创建密钥,请复制、粘贴并运行以下命令:

# Create admin user secretkubectl create secret generic mdb-admin-user-password \ --from-literal=password="${MDB_ADMIN_USER_PASSWORD}" \ --dry-run=client -o yaml | kubectl apply --context "${K8S_CTX}" --namespace "${MDB_NS}" -f - # Create search sync source user secretkubectl create secret generic "${MDB_RESOURCE_NAME}-search-sync-source-password" \ --from-literal=password="${MDB_SEARCH_SYNC_USER_PASSWORD}" \ --dry-run=client -o yaml | kubectl apply --context "${K8S_CTX}" --namespace "${MDB_NS}" -f - # Create regular user secretkubectl create secret generic mdb-user-password \ --from-literal=password="${MDB_USER_PASSWORD}" \ --dry-run=client -o yaml | kubectl apply --context "${K8S_CTX}" --namespace "${MDB_NS}" -f - echo "User secrets created."
6

管理TLS证书需要 cert-manager。如果您已在集群中安装 cert-manager,请跳过此步骤。否则,请使用Helm 安装 cert-manager。

要在 cert-manager命名空间中安装 cert-manager,请在终端中运行以下命令:

helm upgrade --install \ cert-manager \ oci://quay.io/jetstack/charts/cert-manager \ --kube-context "${K8S_CTX}" \ --namespace "${CERT_MANAGER_NAMESPACE}" \ --create-namespace \ --set crds.enabled=true for deployment in cert-manager cert-manager-cainjector cert-manager-webhook; do kubectl --context "${K8S_CTX}" \ -n "${CERT_MANAGER_NAMESPACE}" \ wait --for=condition=Available "deployment/${deployment}" --timeout=300sdone echo "cert-manager is ready in namespace ${CERT_MANAGER_NAMESPACE}."
7

创建证书授权机构基础设施,用于针对 MongoDB 和 MongoDBSearch 资源颁发 TLS 证书。这些命令会执行以下操作:

  • 创建自签名 ClusterIssuer。

  • 生成 CA 证书。

  • 发布所有命名空间都可以使用的集群范围的 CA 颁发者。

  • 通过 ConfigMap 公开 CA 捆绑包,以便MongoDB资源可以使用它。

# Bootstrap a self-signed ClusterIssuer that will mint the CA material consumed by# the MongoDBCommunity deployment.kubectl apply --context "${K8S_CTX}" -f - <<EOF_MANIFESTapiVersion: cert-manager.io/v1kind: ClusterIssuermetadata: name: ${MDB_TLS_SELF_SIGNED_ISSUER}spec: selfSigned: {}EOF_MANIFEST kubectl --context "${K8S_CTX}" wait --for=condition=Ready clusterissuer "${MDB_TLS_SELF_SIGNED_ISSUER}" # Create the CA certificate and secret in the cert-manager namespace.kubectl apply --context "${K8S_CTX}" -f - <<EOF_MANIFESTapiVersion: cert-manager.io/v1kind: Certificatemetadata: name: ${MDB_TLS_CA_CERT_NAME} namespace: ${CERT_MANAGER_NAMESPACE}spec: isCA: true commonName: ${MDB_TLS_CA_CERT_NAME} secretName: ${MDB_TLS_CA_SECRET_NAME} privateKey: algorithm: ECDSA size: 256 issuerRef: name: ${MDB_TLS_SELF_SIGNED_ISSUER} kind: ClusterIssuerEOF_MANIFEST kubectl --context "${K8S_CTX}" wait --for=condition=Ready -n "${CERT_MANAGER_NAMESPACE}" certificate "${MDB_TLS_CA_CERT_NAME}" # Publish a cluster-scoped issuer that fronts the generated CA secret so all namespaces can reuse it.kubectl apply --context "${K8S_CTX}" -f - <<EOF_MANIFESTapiVersion: cert-manager.io/v1kind: ClusterIssuermetadata: name: ${MDB_TLS_CA_ISSUER}spec: ca: secretName: ${MDB_TLS_CA_SECRET_NAME}EOF_MANIFEST kubectl --context "${K8S_CTX}" wait --for=condition=Ready clusterissuer "${MDB_TLS_CA_ISSUER}" TMP_CA_CERT="$(mktemp)" kubectl --context "${K8S_CTX}" \ get secret "${MDB_TLS_CA_SECRET_NAME}" -n "${CERT_MANAGER_NAMESPACE}" \ -o jsonpath="{.data['ca\\.crt']}" | base64 --decode > "${TMP_CA_CERT}" # Expose the CA bundle through a ConfigMap for workloads and the MongoDBCommunity resource.kubectl --context "${K8S_CTX}" create configmap "${MDB_TLS_CA_CONFIGMAP}" -n "${MDB_NS}" \ --from-file=ca-pem="${TMP_CA_CERT}" --from-file=mms-ca.crt="${TMP_CA_CERT}" \ --from-file=ca.crt="${TMP_CA_CERT}" \ --dry-run=client -o yaml | kubectl --context "${K8S_CTX}" apply -f - echo "Cluster-wide CA issuer ${MDB_TLS_CA_ISSUER} is ready."
8

为 MongoDB 服务器和 MongoDBSearch 服务颁发 TLS 证书。MongoDB 服务器证书包含了用于 pod 和服务通信的所有必要 DNS 名称。这两种证书都支持服务器和客户端身份验证。

server_certificate="${MDB_RESOURCE_NAME}-server-tls"search_certificate="${MDB_RESOURCE_NAME}-search-tls" mongo_dns_names=()for ((member = 0; member < MDB_MEMBERS; member++)); do mongo_dns_names+=("${MDB_RESOURCE_NAME}-${member}") mongo_dns_names+=("${MDB_RESOURCE_NAME}-${member}.${MDB_RESOURCE_NAME}-svc.${MDB_NS}.svc.cluster.local")donemongo_dns_names+=( "${MDB_RESOURCE_NAME}-svc.${MDB_NS}.svc.cluster.local" "*.${MDB_RESOURCE_NAME}-svc.${MDB_NS}.svc.cluster.local") search_dns_names=( "${MDB_RESOURCE_NAME}-search-svc.${MDB_NS}.svc.cluster.local") render_dns_list() { local dns_list=("$@") for dns in "${dns_list[@]}"; do printf " - \"%s\"\n" "${dns}" done} kubectl apply --context "${K8S_CTX}" -n "${MDB_NS}" -f - <<EOF_MANIFESTapiVersion: cert-manager.io/v1kind: Certificatemetadata: name: ${server_certificate} namespace: ${MDB_NS}spec: secretName: ${MDB_TLS_SERVER_CERT_SECRET_NAME} issuerRef: name: ${MDB_TLS_CA_ISSUER} kind: ClusterIssuer duration: 240h0m0s renewBefore: 120h0m0s usages: - digital signature - key encipherment - server auth - client auth dnsNames:$(render_dns_list "${mongo_dns_names[@]}")---apiVersion: cert-manager.io/v1kind: Certificatemetadata: name: ${search_certificate} namespace: ${MDB_NS}spec: secretName: ${MDB_SEARCH_TLS_SECRET_NAME} issuerRef: name: ${MDB_TLS_CA_ISSUER} kind: ClusterIssuer duration: 240h0m0s renewBefore: 120h0m0s usages: - digital signature - key encipherment - server auth - client auth dnsNames:$(render_dns_list "${search_dns_names[@]}")EOF_MANIFEST kubectl --context "${K8S_CTX}" -n "${MDB_NS}" wait --for=condition=Ready certificate "${server_certificate}" --timeout=300skubectl --context "${K8S_CTX}" -n "${MDB_NS}" wait --for=condition=Ready certificate "${search_certificate}" --timeout=300s echo "MongoDB TLS certificates have been issued."
9

如果您已经部署了MongoDB Community Edition,请跳过此步骤。否则,部署MongoDB Community Edition。

要部署MongoDB Community Edition,请完成以下步骤:

  1. 创建名为 mdb-rs 的 MongoDBCommunity 自定义资源。

    该资源定义了 mongod 和 mongodb-agent 容器的 CPU 和内存资源,并设置了以下三个用户:

    mdb-user

    可以恢复数据库和运行搜索查询的用户。该用户使用 mdb-user-password 密钥来执行这些操作。

    search-sync-source

    MongoDB 搜索用于连接到 MongoDB 数据库以管理和构建索引的用户。此用户使用Kubernetes 操作符创建的 searchCoordinator角色。这会使用 mdbc-rs-search-sync-source-password 密钥将 mongot 连接到 mongod。

    admin-user

    数据库管理员用户。

    Kubernetes 操作符使用此资源配置具有 3 个成员的 MongoDB 副本集。

    要创建密钥,请复制、粘贴并运行以下命令:

    kubectl apply --context "${K8S_CTX}" -n "${MDB_NS}" -f - <<EOFapiVersion: mongodbcommunity.mongodb.com/v1kind: MongoDBCommunitymetadata: name: ${MDB_RESOURCE_NAME}spec: version: ${MDB_VERSION} type: ReplicaSet members: ${MDB_MEMBERS} security: tls: enabled: true certificateKeySecretRef: name: ${MDB_TLS_SERVER_CERT_SECRET_NAME} caConfigMapRef: name: ${MDB_TLS_CA_CONFIGMAP} authentication: ignoreUnknownUsers: true modes: - SCRAM agent: logLevel: DEBUG statefulSet: spec: template: spec: containers: - name: mongod resources: limits: cpu: "2" memory: 2Gi requests: cpu: "1" memory: 1Gi - name: mongodb-agent resources: limits: cpu: "1" memory: 2Gi requests: cpu: "0.5" memory: 1Gi users: # admin user with root role - name: mdb-admin db: admin # a reference to the secret containing user password passwordSecretRef: name: mdb-admin-user-password scramCredentialsSecretName: mdb-admin-user roles: - name: root db: admin # user performing search queries - name: mdb-user db: admin # a reference to the secret containing user password passwordSecretRef: name: mdb-user-password scramCredentialsSecretName: mdb-user-scram roles: - name: restore db: sample_mflix - name: readWrite db: sample_mflix # user used by MongoDB Search to connect to MongoDB database to # synchronize data from. # For MongoDB <8.2, the operator will be creating the # searchCoordinator custom role automatically. # From MongoDB 8.2, searchCoordinator role will be a # built-in role. - name: search-sync-source db: admin # a reference to the secret that will be used to generate the user's password passwordSecretRef: name: ${MDB_RESOURCE_NAME}-search-sync-source-password scramCredentialsSecretName: ${MDB_RESOURCE_NAME}-search-sync-source roles: - name: searchCoordinator db: adminEOF
  2. 等待 MongoDBCommunity资源部署完成。

    当您应用MongoDBCommunity 自定义资源时, Kubernetes 操作符开始部署MongoDB节点 (Pod)。此步骤会暂停执行,直到 mdbc-rs 资源的状态阶段为 Running,这表示MongoDB Community副本集可操作。

    echo "Waiting for MongoDBCommunity resource to reach Running phase..."kubectl --context "${K8S_CTX}" -n "${MDB_NS}" wait \ --for=jsonpath='{.status.phase}'=Running mdbc/mdbc-rs --timeout=400secho; echo "MongoDBCommunity resource"kubectl --context "${K8S_CTX}" -n "${MDB_NS}" get mdbc/mdbc-rsecho; echo "Pods running in cluster ${K8S_CTX}"kubectl --context "${K8S_CTX}" -n "${MDB_NS}" get pods
10

您可以部署一个搜索节点实例,而无需任何负载均衡。

要部署,请完成以下步骤:

  1. 创建名为 mdbc-rs 的 MongoDBSearch 自定义资源。

    此资源指定搜索节点的 CPU 和内存资源要求。要学习;了解有关此自定义资源中设置的更多信息,请参阅MongoDB搜索和向量搜索设置。

    # create a Kubernetes secret that would have embedding model's API Keyskubectl create secret generic "${AUTO_EMBEDDING_API_KEY_SECRET_NAME}" \ --from-literal=query-key="${AUTO_EMBEDDING_API_QUERY_KEY}" \ --from-literal=indexing-key="${AUTO_EMBEDDING_API_INDEXING_KEY}" --context "${K8S_CTX}" -n "${MDB_NS}" # create MongoDBSearch resource, enabling the auto embedding using the API Keys provided abovekubectl apply --context "${K8S_CTX}" -n "${MDB_NS}" -f - <<EOFapiVersion: mongodb.com/v1kind: MongoDBSearchmetadata: name: ${MDB_RESOURCE_NAME}spec: security: tls: certificateKeySecretRef: name: ${MDB_SEARCH_TLS_SECRET_NAME} resourceRequirements: limits: cpu: "3" memory: 5Gi requests: cpu: "2" memory: 3Gi autoEmbedding: providerEndpoint: ${PROVIDER_ENDPOINT} embeddingModelAPIKeySecret: name: ${AUTO_EMBEDDING_API_KEY_SECRET_NAME}EOF

    注意

    由于Kubernetes Operator 仅部署MongoDB Search 的单个实例,因此该实例会自动配置为嵌入式物化视图编写器。

  2. 等待 MongoDBSearch资源部署完成。

    当您应用MongoDBSearch 自定义资源时, Kubernetes 操作符开始部署搜索节点 (pod)。此步骤会暂停执行,直到 mdbc-rs MongoDB搜索 资源的状态阶段为 Running(表示MongoDB搜索 正在运行)。

    echo "Waiting for MongoDBSearch resource to reach Running phase..."kubectl --context "${K8S_CTX}" -n "${MDB_NS}" wait \ --for=jsonpath='{.status.phase}'=Running mdbs/"${MDB_RESOURCE_NAME}" --timeout=300s
11

确保使用 MongoDBSearch 的 MongoDBCommunity资源部署成功。

echo "Waiting for MongoDBCommunity resource to reach Running phase..."kubectl --context "${K8S_CTX}" -n "${MDB_NS}" wait \ --for=jsonpath='{.status.phase}'=Running mdbc/mdbc-rs --timeout=400secho; echo "MongoDBCommunity resource"kubectl --context "${K8S_CTX}" -n "${MDB_NS}" get mdbc/mdbc-rsecho; echo "Pods running in cluster ${K8S_CTX}"kubectl --context "${K8S_CTX}" -n "${MDB_NS}" get pods
12

查看MongoDB副本集成员、 Kubernetes Operator 的MongoDB控制器以及搜索节点的命名空间Pod 中运行的所有 Pod。

echo; echo "MongoDBCommunity resource"kubectl --context "${K8S_CTX}" -n "${MDB_NS}" get mdbc/mdbc-rsecho; echo "MongoDBSearch resource"kubectl --context "${K8S_CTX}" -n "${MDB_NS}" get mdbs/mdbc-rsecho; echo "Pods running in cluster ${K8S_CTX}"kubectl --context "${K8S_CTX}" -n "${MDB_NS}" get pods

现在您已成功部署MongoDB 搜索和向量搜索以便与MongoDB Community Edition一起使用,接下来将数据添加到您的MongoDB 集群,创建MongoDB 搜索和向量搜索搜索索引,并根据您的数据运行查询。要学习;了解更多信息,请参阅使用MongoDB Search 和 Vector Search。

给本页内容打分