快速入门:使用 ARM 模板创建 Azure Cosmos DB 和容器

适用范围: NoSQL

Azure Cosmos DB 是世纪互联的快速 NoSQL 数据库,具有适合任何规模的开放式 API。 使用 Azure Cosmos DB,可以快速创建和查询键/值数据库、文档数据库和图形数据库。 本快速入门重点介绍部署用以创建 Azure Cosmos 数据库的 Azure 资源管理器模板(ARM 模板)以及在该数据库内创建容器的过程。 稍后你可以在该容器中存储数据。

资源管理器模板是定义项目基础结构和配置的 JavaScript 对象表示法 (JSON) 文件。 模板使用声明性语法。 在声明性语法中,你可以在不编写创建部署的编程命令序列的情况下,描述预期部署。

如果你的环境满足先决条件,并且你熟悉如何使用 ARM 模板,请选择“部署到 Azure”按钮。 Azure 门户中会打开模板。

部署到 Azure

先决条件

Azure 订阅,或免费的 Azure Cosmos DB 试用帐户

查看模板

本快速入门中使用的模板来自 Azure 快速启动模板

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.3.255.40792",
      "templateHash": "18246509320363749893"
    }
  },
  "parameters": {
    "accountName": {
      "type": "string",
      "defaultValue": "[format('sql-{0}', uniqueString(resourceGroup().id))]",
      "metadata": {
        "description": "Cosmos DB account name, max length 44 characters"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for the Cosmos DB account."
      }
    },
    "primaryRegion": {
      "type": "string",
      "metadata": {
        "description": "The primary replica region for the Cosmos DB account."
      }
    },
    "secondaryRegion": {
      "type": "string",
      "metadata": {
        "description": "The secondary replica region for the Cosmos DB account."
      }
    },
    "defaultConsistencyLevel": {
      "type": "string",
      "defaultValue": "Session",
      "metadata": {
        "description": "The default consistency level of the Cosmos DB account."
      },
      "allowedValues": [
        "Eventual",
        "ConsistentPrefix",
        "Session",
        "BoundedStaleness",
        "Strong"
      ]
    },
    "maxStalenessPrefix": {
      "type": "int",
      "defaultValue": 100000,
      "metadata": {
        "description": "Max stale requests. Required for BoundedStaleness. Valid ranges, Single Region: 10 to 1000000. Multi Region: 100000 to 1000000."
      },
      "maxValue": 2147483647,
      "minValue": 10
    },
    "maxIntervalInSeconds": {
      "type": "int",
      "defaultValue": 300,
      "metadata": {
        "description": "Max lag time (minutes). Required for BoundedStaleness. Valid ranges, Single Region: 5 to 84600. Multi Region: 300 to 86400."
      },
      "maxValue": 86400,
      "minValue": 5
    },
    "automaticFailover": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Enable automatic failover for regions"
      },
      "allowedValues": [
        true,
        false
      ]
    },
    "databaseName": {
      "type": "string",
      "defaultValue": "myDatabase",
      "metadata": {
        "description": "The name for the database"
      }
    },
    "containerName": {
      "type": "string",
      "defaultValue": "myContainer",
      "metadata": {
        "description": "The name for the container"
      }
    },
    "throughput": {
      "type": "int",
      "defaultValue": 400,
      "metadata": {
        "description": "The throughput for the container"
      },
      "maxValue": 1000000,
      "minValue": 400
    }
  },
  "functions": [],
  "variables": {
    "accountName_var": "[toLower(parameters('accountName'))]",
    "consistencyPolicy": {
      "Eventual": {
        "defaultConsistencyLevel": "Eventual"
      },
      "ConsistentPrefix": {
        "defaultConsistencyLevel": "ConsistentPrefix"
      },
      "Session": {
        "defaultConsistencyLevel": "Session"
      },
      "BoundedStaleness": {
        "defaultConsistencyLevel": "BoundedStaleness",
        "maxStalenessPrefix": "[parameters('maxStalenessPrefix')]",
        "maxIntervalInSeconds": "[parameters('maxIntervalInSeconds')]"
      },
      "Strong": {
        "defaultConsistencyLevel": "Strong"
      }
    },
    "locations": [
      {
        "locationName": "[parameters('primaryRegion')]",
        "failoverPriority": 0,
        "isZoneRedundant": false
      },
      {
        "locationName": "[parameters('secondaryRegion')]",
        "failoverPriority": 1,
        "isZoneRedundant": false
      }
    ]
  },
  "resources": [
    {
      "type": "Microsoft.DocumentDB/databaseAccounts",
      "apiVersion": "2021-04-15",
      "name": "[variables('accountName_var')]",
      "location": "[parameters('location')]",
      "kind": "GlobalDocumentDB",
      "properties": {
        "consistencyPolicy": "[variables('consistencyPolicy')[parameters('defaultConsistencyLevel')]]",
        "locations": "[variables('locations')]",
        "databaseAccountOfferType": "Standard",
        "enableAutomaticFailover": "[parameters('automaticFailover')]"
      }
    },
    {
      "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases",
      "apiVersion": "2021-04-15",
      "name": "[format('{0}/{1}', variables('accountName_var'), parameters('databaseName'))]",
      "properties": {
        "resource": {
          "id": "[parameters('databaseName')]"
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.DocumentDB/databaseAccounts', variables('accountName_var'))]"
      ]
    },
    {
      "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers",
      "apiVersion": "2021-04-15",
      "name": "[format('{0}/{1}', format('{0}/{1}', variables('accountName_var'), parameters('databaseName')), parameters('containerName'))]",
      "properties": {
        "resource": {
          "id": "[parameters('containerName')]",
          "partitionKey": {
            "paths": [
              "/myPartitionKey"
            ],
            "kind": "Hash"
          },
          "indexingPolicy": {
            "indexingMode": "consistent",
            "includedPaths": [
              {
                "path": "/*"
              }
            ],
            "excludedPaths": [
              {
                "path": "/myPathToNotIndex/*"
              }
            ],
            "compositeIndexes": [
              [
                {
                  "path": "/name",
                  "order": "ascending"
                },
                {
                  "path": "/age",
                  "order": "descending"
                }
              ]
            ],
            "spatialIndexes": [
              {
                "path": "/location/*",
                "types": [
                  "Point",
                  "Polygon",
                  "MultiPolygon",
                  "LineString"
                ]
              }
            ]
          },
          "defaultTtl": 86400,
          "uniqueKeyPolicy": {
            "uniqueKeys": [
              {
                "paths": [
                  "/phoneNumber"
                ]
              }
            ]
          }
        },
        "options": {
          "throughput": "[parameters('throughput')]"
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlDatabases', split(format('{0}/{1}', variables('accountName_var'), parameters('databaseName')), '/')[0], split(format('{0}/{1}', variables('accountName_var'), parameters('databaseName')), '/')[1])]"
      ]
    }
  ]
}

该模板中定义了三个 Azure 资源:

可以在快速入门模板库中找到更多 Azure Cosmos DB 模板示例。

部署模板

  1. 选择下图登录到 Azure 并打开一个模板。 该模板将创建 Azure Cosmos DB 帐户、数据库和容器。

    部署到 Azure

  2. 选择或输入以下值。

    ARM 模板, Azure Cosmos DB 集成, 部署门户

    除非另有指定,否则请使用默认值创建 Azure Cosmos DB 资源。

    • 订阅:选择一个 Azure 订阅。

    • 资源组:选择“新建”,输入资源组的唯一名称,然后单击“确定”。

    • 位置:选择一个位置。 例如,中国北部

    • 帐户名称:输入 Azure Cosmos DB 帐户的名称。 它必须多区域唯一。

    • 位置:输入要在其中创建 Azure Cosmos DB 帐户的位置。 Azure Cosmos DB 帐户必须与资源组处于同一位置。

    • 主要区域:Azure Cosmos DB 帐户的主要副本区域。

    • 次要区域:Azure Cosmos DB 帐户的次要副本区域。

    • 默认一致性级别:Azure Cosmos DB 帐户的默认一致性级别。

    • 最大过期前缀:最大过时请求数。 对于 BoundedStaleness 是必需的。

    • 以秒为单位的最大间隔:最大延迟时间。 对于 BoundedStaleness 是必需的。

    • 数据库名称:Azure Cosmos DB 数据库的名称。

    • 容器名称:Azure Cosmos DB 容器的名称。

    • 吞吐量:容器的吞吐量,最小吞吐量值为 400 RU/秒。

    • 我同意上述条款和条件:选中。

  3. 选择“购买”。 成功部署 Azure Cosmos DB 帐户后,你会收到通知:

    ARM 模板, Azure Cosmos DB 集成, 部署门户通知

使用 Azure 门户部署模板。 除了 Azure 门户,还可以使用 Azure PowerShell、Azure CLI 和 REST API。 若要了解其他部署方法,请参阅部署模板

验证部署

可以使用 Azure 门户检查 Azure Cosmos DB 帐户、数据库和容器,或者使用以下 Azure CLI 或 Azure PowerShell 脚本列出创建的机密。

echo "Enter your Azure Cosmos DB account name:" &&
read cosmosAccountName &&
echo "Enter the resource group where the Azure Cosmos DB account exists:" &&
read resourcegroupName &&
az cosmosdb show -g $resourcegroupName -n $cosmosAccountName

清理资源

如果打算继续使用后续的快速入门和教程,则可能需要保留这些资源。 如果不再需要资源组,可以将其删除,这将删除 Azure Cosmos DB 帐户和相关的资源。 使用 Azure CLI 或 Azure PowerShell 删除资源组:

echo "Enter the Resource Group name:" &&
read resourceGroupName &&
az group delete --name $resourceGroupName &&
echo "Press [ENTER] to continue ..."

后续步骤

在本快速入门中,你已使用 ARM 模板创建了 Azure Cosmos DB 帐户、数据库和容器,并验证了部署。 若要详细了解 Azure Cosmos DB 和 Azure 资源管理器,请继续阅读以下文章。