快速入门:使用 ARM 模板创建 Azure Cosmos DB 和容器Quickstart: Create an Azure Cosmos DB and a container by using an ARM template

Azure Cosmos DB 是世纪互联提供的多区域分布式多模型数据库服务。Azure Cosmos DB is 21Vianet's multiple-regionally distributed multi-model database service. 使用 Azure Cosmos DB,可以快速创建和查询键/值数据库、文档数据库和图形数据库。You can use Azure Cosmos DB to quickly create and query key/value databases, document databases, and graph databases. 本快速入门重点介绍部署用以创建 Azure Cosmos 数据库的 Azure 资源管理器模板(ARM 模板)以及在该数据库内创建容器的过程。This quickstart focuses on the process of deploying an Azure Resource Manager template (ARM template) to create an Azure Cosmos database and a container within that database. 稍后你可以在该容器中存储数据。You can later store data in this container.

ARM 模板是定义项目基础结构和配置的 JavaScript 对象表示法 (JSON) 文件。An ARM template is a JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for your project. 该模板使用声明性语法,使你可以声明要部署的内容,而不需要编写一系列编程命令来进行创建。The template uses declarative syntax, which lets you state what you intend to deploy without having to write the sequence of programming commands to create it.

如果你的环境满足先决条件,并且你熟悉如何使用 ARM 模板,请选择“部署到 Azure”按钮。If your environment meets the prerequisites and you're familiar with using ARM templates, select the Deploy to Azure button. Azure 门户中会打开模板。The template will open in the Azure portal.

部署到 Azure Deploy to Azure

先决条件Prerequisites

Azure 订阅,或免费的 Azure Cosmos DB 试用帐户An Azure subscription or free Azure Cosmos DB trial account

查看模板Review the template

本快速入门中使用的模板来自 Azure 快速启动模板The template used in this quickstart is from Azure Quickstart Templates.

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "accountName": {
            "type": "string",
            "defaultValue": "[concat('sql-', 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",
            "allowedValues": [ "Eventual", "ConsistentPrefix", "Session", "BoundedStaleness", "Strong" ],
            "metadata": {
                "description": "The default consistency level of the Cosmos DB account."
            }
        },
        "maxStalenessPrefix": {
            "type": "int",
            "minValue": 10,
            "defaultValue": 100000,
            "maxValue": 2147483647,
            "metadata": {
                "description": "Max stale requests. Required for BoundedStaleness. Valid ranges, Single Region: 10 to 1000000. Multi Region: 100000 to 1000000."
            }
        },
        "maxIntervalInSeconds": {
            "type": "int",
            "minValue": 5,
            "defaultValue": 300,
            "maxValue": 86400,
            "metadata": {
                "description": "Max lag time (minutes). Required for BoundedStaleness. Valid ranges, Single Region: 5 to 84600. Multi Region: 300 to 86400."
            }
        },  
        "automaticFailover": {
            "type": "bool",
            "defaultValue": true,
            "allowedValues": [ true, false ],
            "metadata": {
                "description": "Enable automatic failover for regions"
            }
        },
        "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,
            "minValue": 400,
            "maxValue": 1000000,
            "metadata": {
                "description": "The throughput for the container"
            }           
        }
    },
    "variables": {
        "accountName": "[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",
            "name": "[variables('accountName')]",
            "apiVersion": "2020-03-01",
            "kind": "GlobalDocumentDB",
            "location": "[parameters('location')]",
            "properties": {
                "consistencyPolicy": "[variables('consistencyPolicy')[parameters('defaultConsistencyLevel')]]",
                "locations": "[variables('locations')]",
                "databaseAccountOfferType": "Standard",
                "enableAutomaticFailover": "[parameters('automaticFailover')]"
            }
        },
        {
            "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases",
            "name": "[concat(variables('accountName'), '/', parameters('databaseName'))]",
            "apiVersion": "2020-03-01",
            "dependsOn": [ "[resourceId('Microsoft.DocumentDB/databaseAccounts', variables('accountName'))]" ],
            "properties":{
                "resource":{
                    "id": "[parameters('databaseName')]"
                }
            }
        },
        {
            "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers",
            "name": "[concat(variables('accountName'), '/', parameters('databaseName'), '/', parameters('containerName'))]",
            "apiVersion": "2020-03-01",
            "dependsOn": [ "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlDatabases', variables('accountName'), parameters('databaseName'))]" ],
            "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": "/path/to/geojson/property/?",
                                "types": [
                                    "Point",
                                    "Polygon",
                                    "MultiPolygon",
                                    "LineString"
                                ]
                            }
                        ]
                    },
                    "defaultTtl": 86400,
                    "uniqueKeyPolicy": {
                        "uniqueKeys": [
                        {
                            "paths": [
                            "/phoneNumber"
                            ]
                        }
                        ]
                    }
                },
                "options": { "throughput": "[parameters('throughput')]" }
            }
        }
    ]
}

该模板中定义了三个 Azure 资源:Three Azure resources are defined in the template:

  • Microsoft.DocumentDB/databaseAccounts:创建 Azure Cosmos 帐户。Microsoft.DocumentDB/databaseAccounts: Create an Azure Cosmos account.

  • Microsoft.DocumentDB/databaseAccounts/sqlDatabases:创建 Azure Cosmos 数据库。Microsoft.DocumentDB/databaseAccounts/sqlDatabases: Create an Azure Cosmos database.

  • Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers:创建 Azure Cosmos 容器。Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers: Create an Azure Cosmos container.

可以在快速入门模板库中找到更多 Azure Cosmos DB 模板示例。More Azure Cosmos DB template samples can be found in the quickstart template gallery.

部署模板Deploy the template

  1. 选择下图登录到 Azure 并打开一个模板。Select the following image to sign in to Azure and open a template. 该模板将创建 Azure Cosmos 帐户、数据库和容器。The template creates an Azure Cosmos account, a database, and a container.

    部署到 Azure Deploy to Azure

  2. 选择或输入以下值。Select or enter the following values.

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

    除非另有指定,否则请使用默认值创建 Azure Cosmos 资源。Unless it is specified, use the default values to create the Azure Cosmos resources.

    • 订阅:选择一个 Azure 订阅。Subscription: select an Azure subscription.

    • 资源组:选择“新建”,输入资源组的唯一名称,然后单击“确定”。 Resource group: select Create new, enter a unique name for the resource group, and then click OK.

    • 位置:选择一个位置。Location: select a location. 例如,中国北部For example, China North.

    • 帐户名称:输入 Azure Cosmos 帐户的名称。Account Name: enter a name for the Azure Cosmos account. 它必须全局唯一。It must be globally unique.

    • 位置:输入要在其中创建 Azure Cosmos 帐户的位置。Location: enter a location where you want to create your Azure Cosmos account. Azure Cosmos 帐户必须与资源组处于同一位置。The Azure Cosmos account can be in the same location as the resource group.

    • 主要区域:Azure Cosmos 帐户的主要副本区域。Primary Region: The primary replica region for the Azure Cosmos account.

    • 次要区域:Azure Cosmos 帐户的次要副本区域。Secondary region: The secondary replica region for the Azure Cosmos account.

    • 默认一致性级别:Azure Cosmos 帐户的默认一致性级别。Default Consistency Level: The default consistency level for the Azure Cosmos account.

    • 最大过期前缀:最大过时请求数。Max Staleness Prefix: Max stale requests. 对于 BoundedStaleness 是必需的。Required for BoundedStaleness.

    • 以秒为单位的最大间隔:最大延迟时间。Max Interval in Seconds: Max lag time. 对于 BoundedStaleness 是必需的。Required for BoundedStaleness.

    • 数据库名称:Azure Cosmos 数据库的名称。Database Name: The name of the Azure Cosmos database.

    • 容器名称:Azure Cosmos 容器的名称。Container Name: The name of the Azure Cosmos container.

    • 吞吐量:容器的吞吐量,最小吞吐量值为 400 RU/秒。Throughput: The throughput for the container, minimum throughput value is 400 RU/s.

    • 我同意上述条款和条件:选中。I agree to the terms and conditions state above: Select.

  3. 选择“购买”。Select Purchase. 成功部署 Azure Cosmos 帐户后,你会收到通知:After the Azure Cosmos account has been deployed successfully, you get a notification:

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

使用 Azure 门户部署模板。The Azure portal is used to deploy the template. 除了 Azure 门户,还可以使用 Azure PowerShell、Azure CLI 和 REST API。In addition to the Azure portal, you can also use the Azure PowerShell, Azure CLI, and REST API. 若要了解其他部署方法,请参阅部署模板To learn other deployment methods, see Deploy templates.

验证部署Validate the deployment

可以使用 Azure 门户检查 Azure Cosmos 帐户、数据库和容器,或者使用以下 Azure CLI 或 Azure PowerShell 脚本列出创建的机密。You can either use the Azure portal to check the Azure Cosmos account, the database, and the container or use the following Azure CLI or Azure PowerShell script to list the secret created.

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

清理资源Clean up resources

如果打算继续使用后续的快速入门和教程,则可能需要保留这些资源。If you plan to continue working with subsequent quickstarts and tutorials, you might want to leave these resources in place. 如果不再需要资源组,可以将其删除,这将删除 Azure Cosmos 帐户和相关的资源。When no longer needed, delete the resource group, which deletes the Azure Cosmos account and the related resources. 使用 Azure CLI 或 Azure PowerShell 删除资源组:To delete the resource group by using Azure CLI or Azure PowerShell:

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

后续步骤Next steps

在本快速入门中,你已使用 ARM 模板创建了 Azure Cosmos 帐户、数据库和容器,并验证了部署。In this quickstart, you created an Azure Cosmos account, a database and a container by using an ARM template and validated the deployment. 若要详细了解 Azure Cosmos DB 和 Azure 资源管理器,请继续阅读以下文章。To learn more about Azure Cosmos DB and Azure Resource Manager, continue on to the articles below.