使用 Azure CLI 管理 Azure Cosmos Core (SQL) API 资源Manage Azure Cosmos Core (SQL) API resources using Azure CLI

适用于: SQL API

以下指南介绍了使用 Azure CLI 自动管理 Azure Cosmos DB 帐户、数据库和容器的常见命令。The following guide describes common commands to automate management of your Azure Cosmos DB accounts, databases and containers using Azure CLI. Azure CLI 参考中收录了所有 Azure Cosmos DB CLI 命令的参考页。Reference pages for all Azure Cosmos DB CLI commands are available in the Azure CLI Reference. 还可以在针对 Azure Cosmos DB 的 Azure CLI 示例中找到更多示例,包括如何为 MongoDB、Gremlin、Cassandra 和表 API 创建和管理 Cosmos DB 帐户、数据库和容器。You can also find more examples in Azure CLI samples for Azure Cosmos DB, including how to create and manage Cosmos DB accounts, databases and containers for MongoDB, Gremlin, Cassandra and Table API.

备注

在 Azure China 中使用 Azure CLI 2.0 之前,请首先运行 az cloud set -n AzureChinaCloud 更改云环境。Before you can use Azure CLI 2.0 in Azure China, please run az cloud set -n AzureChinaCloud first to change the cloud environment. 如果要切换回全局 Azure,请再次运行 az cloud set -n AzureCloudIf you want to switch back to Global Azure, run az cloud set -n AzureCloud again.

如果选择在本地安装并使用 CLI,本主题要求运行 Azure CLI 2.12.1 或更高版本。When you choose to install and use the CLI locally, this topic requires that you are running the Azure CLI version 2.12.1 or later. 运行 az --version 即可查找版本。Run az --version to find the version. 如果需要进行安装或升级,请参阅安装 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

有关其他 API 的 Azure CLI 示例,请参阅适用于 Cassandra 的 CLI 示例适用于 MongoDB API 的 CLI 示例适用于 Gremlin 的 CLI 示例适用于 Table 的 CLI 示例For Azure CLI samples for other APIs see CLI Samples for Cassandra, CLI Samples for MongoDB API, CLI Samples for Gremlin, CLI Samples for Table

重要

无法重命名 Azure Cosmos DB 资源,因为这违反了 Azure 资源管理器与资源 URI 的工作方式。Azure Cosmos DB resources cannot be renamed as this violates how Azure Resource Manager works with resource URIs.

Azure Cosmos 帐户Azure Cosmos Accounts

以下部分演示如何管理 Azure Cosmos 帐户,包括:The following sections demonstrate how to manage the Azure Cosmos account, including:

创建 Azure Cosmos DB 帐户Create an Azure Cosmos DB account

在“中国北部 2”和“中国东部 2”区域创建启用了 SQL API 和会话一致性的 Azure Cosmos DB 帐户:Create an Azure Cosmos DB account with SQL API, Session consistency in China North 2 and China East 2 regions:

重要

Azure Cosmos 帐户名称必须为小写且小于 44 个字符。The Azure Cosmos account name must be lowercase and less than 44 characters.

resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount' #needs to be lower case and less than 44 characters

az cosmosdb create \
    -n $accountName \
    -g $resourceGroupName \
    --default-consistency-level Session \
    --locations regionName='China North 2' failoverPriority=0 isZoneRedundant=False \
    --locations regionName='China East 2' failoverPriority=1 isZoneRedundant=False

添加或删除区域Add or remove regions

创建包含两个区域的 Azure Cosmos 帐户,添加一个区域,并删除一个区域。Create an Azure Cosmos account with two regions, add a region, and remove a region.

备注

不能同时添加或删除区域 locations 并更改 Azure Cosmos 帐户的其他属性。You cannot simultaneously add or remove regions locations and change other properties for an Azure Cosmos account. 修改区域的操作必须作为单独的操作与任何其他对帐户资源的更改操作分开执行。Modifying regions must be performed as a separate operation than any other change to the account resource.

备注

此命令可添加和删除区域,但不可修改故障转移优先级或触发手动故障转移。This command allows you to add and remove regions but does not allow you to modify failover priorities or trigger a manual failover. 请参阅设置故障转移优先级触发手动故障转移See Set failover priority and Trigger manual failover.

resourceGroupName='myResourceGroup'
accountName='mycosmosaccount'

# Create an account with 2 regions
az cosmosdb create --name $accountName --resource-group $resourceGroupName \
    --locations regionName="China North 2" failoverPriority=0 isZoneRedundant=False \
    --locations regionName="China East 2" failoverPriority=1 isZoneRedundant=False

# Add a region
az cosmosdb update --name $accountName --resource-group $resourceGroupName \
    --locations regionName="China North 2" failoverPriority=0 isZoneRedundant=False \
    --locations regionName="China East 2" failoverPriority=1 isZoneRedundant=False \
    --locations regionName="China East" failoverPriority=2 isZoneRedundant=False

# Remove a region
az cosmosdb update --name $accountName --resource-group $resourceGroupName \
    --locations regionName="China North 2" failoverPriority=0 isZoneRedundant=False \
    --locations regionName="China East 2" failoverPriority=1 isZoneRedundant=False

启用多个写入区域Enable multiple write regions

为 Cosmos 帐户启用多区域写入Enable multi-region writes for a Cosmos account

# Update an Azure Cosmos account from single write region to multiple write regions
resourceGroupName='myResourceGroup'
accountName='mycosmosaccount'

# Get the account resource id for an existing account
accountId=$(az cosmosdb show -g $resourceGroupName -n $accountName --query id -o tsv)

az cosmosdb update --ids $accountId --enable-multiple-write-locations true

设置故障转移优先级Set failover priority

为已为自动故障转移而配置的 Azure Cosmos 帐户设置故障转移优先级Set the failover priority for an Azure Cosmos account configured for automatic failover

# Assume region order is initially 'China North 2'=0 'China East 2'=1 'China East'=2 for account
resourceGroupName='myResourceGroup'
accountName='mycosmosaccount'

# Get the account resource id for an existing account
accountId=$(az cosmosdb show -g $resourceGroupName -n $accountName --query id -o tsv)

# Make China East the next region to fail over to instead of China East 2
az cosmosdb failover-priority-change --ids $accountId \
    --failover-policies 'China North 2=0' 'China East=1' 'China East 2=2'

启用自动故障转移Enable automatic failover

# Enable automatic failover on an existing account
resourceGroupName='myResourceGroup'
accountName='mycosmosaccount'

# Get the account resource id for an existing account
accountId=$(az cosmosdb show -g $resourceGroupName -n $accountName --query id -o tsv)

az cosmosdb update --ids $accountId --enable-automatic-failover true

触发手动故障转移Trigger manual failover

注意

在 priority = 0 的情况下更改区域会为 Azure Cosmos 帐户触发手动故障转移。Changing region with priority = 0 will trigger a manual failover for an Azure Cosmos account. 任何其他优先级更改都不会触发故障转移。Any other priority change will not trigger a failover.

# Assume region order is initially 'China North 2=0' 'China East 2=1' 'China East=2' for account
resourceGroupName='myResourceGroup'
accountName='mycosmosaccount'

# Get the account resource id for an existing account
accountId=$(az cosmosdb show -g $resourceGroupName -n $accountName --query id -o tsv)

# Trigger a manual failover to promote China East 2 as new write region
az cosmosdb failover-priority-change --ids $accountId \
    --failover-policies 'China East 2=0' 'China East=1' 'China North 2=2'

列出所有帐户密钥List all account keys

获取 Cosmos 帐户的所有密钥。Get all keys for a Cosmos account.

# List all account keys
resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'

az cosmosdb keys list \
   -n $accountName \
   -g $resourceGroupName

列出只读帐户密钥List read-only account keys

获取 Cosmos 帐户的只读密钥。Get read-only keys for a Cosmos account.

# List read-only account keys
resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'

az cosmosdb keys list \
    -n $accountName \
    -g $resourceGroupName \
    --type read-only-keys

列出连接字符串List connection strings

获取 Cosmos 帐户的连接字符串。Get the connection strings for a Cosmos account.

# List connection strings
resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'

az cosmosdb keys list \
    -n $accountName \
    -g $resourceGroupName \
    --type connection-strings

重新生成帐户密钥Regenerate account key

重新生成 Cosmos 帐户的新密钥。Regenerate a new key for a Cosmos account.

# Regenerate secondary account keys
# key-kind values: primary, primaryReadonly, secondary, secondaryReadonly
az cosmosdb keys regenerate \
    -n $accountName \
    -g $resourceGroupName \
    --key-kind secondary

Azure Cosmos DB 数据库Azure Cosmos DB database

以下部分演示了如何管理 Azure Cosmos DB 数据库,具体包括:The following sections demonstrate how to manage the Azure Cosmos DB database, including:

创建数据库Create a database

创建 Cosmos 数据库。Create a Cosmos database.

resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'

az cosmosdb sql database create \
    -a $accountName \
    -g $resourceGroupName \
    -n $databaseName

创建具有共享吞吐量的数据库Create a database with shared throughput

创建具有共享吞吐量的 Cosmos 数据库。Create a Cosmos database with shared throughput.

resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'
throughput=400

az cosmosdb sql database create \
    -a $accountName \
    -g $resourceGroupName \
    -n $databaseName \
    --throughput $throughput

迁移数据库以自动缩放吞吐量Migrate a database to autoscale throughput

resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'

# Migrate to autoscale throughput
az cosmosdb sql database throughput migrate \
    -a $accountName \
    -g $resourceGroupName \
    -n $databaseName \
    -t 'autoscale'

# Read the new autoscale max throughput
az cosmosdb sql database throughput show \
    -g $resourceGroupName \
    -a $accountName \
    -n $databaseName \
    --query resource.autoscaleSettings.maxThroughput \
    -o tsv

更改数据库吞吐量Change database throughput

将 Cosmos 数据库的吞吐量增加 1000 RU/s。Increase the throughput of a Cosmos database by 1000 RU/s.

resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'
newRU=1000

# Get minimum throughput to make sure newRU is not lower than minRU
minRU=$(az cosmosdb sql database throughput show \
    -g $resourceGroupName -a $accountName -n $databaseName \
    --query resource.minimumThroughput -o tsv)

if [ $minRU -gt $newRU ]; then
    newRU=$minRU
fi

az cosmosdb sql database throughput update \
    -a $accountName \
    -g $resourceGroupName \
    -n $databaseName \
    --throughput $newRU

防止数据库被删除Prevent a database from being deleted

将 Azure 资源删除锁置于数据库上,以防止删除该数据库。Put an Azure resource delete lock on a database to prevent it from being deleted. 此功能要求锁定 Cosmos 帐户,防止其被数据平面 SDK 更改。This feature requires locking the Cosmos account from being changed by data plane SDKs. 若要了解详细信息,请参阅防止被 SDK 更改To learn more see, Preventing changes from SDKs. Azure 资源锁也可以通过指定 ReadOnly 锁类型来防止更改资源。Azure resource locks can also prevent a resource from being changed by specifying a ReadOnly lock type. 对于 Cosmos 数据库,可以使用该锁来防止更改吞吐量。For a Cosmos database, it can be used to prevent throughput from being changed.

resourceGroupName='myResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'

lockType='CanNotDelete' # CanNotDelete or ReadOnly
databaseParent="databaseAccounts/$accountName"
databaseLockName="$databaseName-Lock"

# Create a delete lock on database
az lock create --name $databaseLockName \
    --resource-group $resourceGroupName \
    --resource-type Microsoft.DocumentDB/sqlDatabases \
    --lock-type $lockType \
    --parent $databaseParent \
    --resource $databaseName

# Delete lock on database
lockid=$(az lock show --name $databaseLockName \
        --resource-group $resourceGroupName \
        --resource-type Microsoft.DocumentDB/sqlDatabases \
        --resource $databaseName \
        --parent $databaseParent \
        --output tsv --query id)
az lock delete --ids $lockid

Azure Cosmos DB 容器Azure Cosmos DB container

以下部分演示了如何管理 Azure Cosmos DB 容器,具体包括:The following sections demonstrate how to manage the Azure Cosmos DB container, including:

创建容器Create a container

创建带有默认索引策略、分区键且 RU/s 为 400 的 Cosmos 容器。Create a Cosmos container with default index policy, partition key and RU/s of 400.

# Create a SQL API container
resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'
containerName='container1'
partitionKey='/myPartitionKey'
throughput=400

az cosmosdb sql container create \
    -a $accountName -g $resourceGroupName \
    -d $databaseName -n $containerName \
    -p $partitionKey --throughput $throughput

使用自动缩放创建容器Create a container with autoscale

使用默认索引策略、分区键且自动缩放 RU/s 为 4000 的 Cosmos 容器。Create a Cosmos container with default index policy, partition key and autoscale RU/s of 4000.

# Create a SQL API container
resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'
containerName='container1'
partitionKey='/myPartitionKey'
maxThroughput=4000

az cosmosdb sql container create \
    -a $accountName -g $resourceGroupName \
    -d $databaseName -n $containerName \
    -p $partitionKey --max-throughput $maxThroughput

创建带有 TTL 的容器Create a container with TTL

创建启用了 TTL 的 Cosmos 容器。Create a Cosmos container with TTL enabled.

# Create an Azure Cosmos container with TTL of one day
resourceGroupName='myResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'
containerName='container1'

az cosmosdb sql container update \
    -g $resourceGroupName \
    -a $accountName \
    -d $databaseName \
    -n $containerName \
    --ttl=86400

创建带有自定义索引策略的容器Create a container with a custom index policy

创建带有自定义索引策略、空间索引、组合索引、分区键且 RU/s 为 400 的 Cosmos 容器。Create a Cosmos container with a custom index policy, a spatial index, composite index, a partition key and RU/s of 400.

# Create a SQL API container
resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'
containerName='container1'
partitionKey='/myPartitionKey'
throughput=400

# Generate a unique 10 character alphanumeric string to ensure unique resource names
uniqueId=$(env LC_CTYPE=C tr -dc 'a-z0-9' < /dev/urandom | fold -w 10 | head -n 1)

# Define the index policy for the container, include spatial and composite indexes
idxpolicy=$(cat << EOF
{
    "indexingMode": "consistent",
    "includedPaths": [
        {"path": "/*"}
    ],
    "excludedPaths": [
        { "path": "/headquarters/employees/?"}
    ],
    "spatialIndexes": [
        {"path": "/*", "types": ["Point"]}
    ],
    "compositeIndexes":[
        [
            { "path":"/name", "order":"ascending" },
            { "path":"/age", "order":"descending" }
        ]
    ]
}
EOF
)
# Persist index policy to json file
echo "$idxpolicy" > "idxpolicy-$uniqueId.json"

az cosmosdb sql container create \
    -a $accountName -g $resourceGroupName \
    -d $databaseName -n $containerName \
    -p $partitionKey --throughput $throughput \
    --idx @idxpolicy-$uniqueId.json

# Clean up temporary index policy file
rm -f "idxpolicy-$uniqueId.json"

更改容器吞吐量Change container throughput

将 Cosmos 容器的吞吐量增加 1000 RU/s。Increase the throughput of a Cosmos container by 1000 RU/s.

resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'
containerName='container1'
newRU=1000

# Get minimum throughput to make sure newRU is not lower than minRU
minRU=$(az cosmosdb sql container throughput show \
    -g $resourceGroupName -a $accountName -d $databaseName \
    -n $containerName --query resource.minimumThroughput -o tsv)

if [ $minRU -gt $newRU ]; then
    newRU=$minRU
fi

az cosmosdb sql container throughput update \
    -a $accountName \
    -g $resourceGroupName \
    -d $databaseName \
    -n $containerName \
    --throughput $newRU

迁移容器以自动缩放吞吐量Migrate a container to autoscale throughput

resourceGroupName='MyResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'
containerName='container1'

# Migrate to autoscale throughput
az cosmosdb sql container throughput migrate \
    -a $accountName \
    -g $resourceGroupName \
    -d $databaseName \
    -n $containerName \
    -t 'autoscale'

# Read the new autoscale max throughput
az cosmosdb sql container throughput show \
    -g $resourceGroupName \
    -a $accountName \
    -d $databaseName \
    -n $containerName \
    --query resource.autoscaleSettings.maxThroughput \
    -o tsv

防止容器被删除Prevent a container from being deleted

将 Azure 资源删除锁置于容器上,以防止删除该容器。Put an Azure resource delete lock on a container to prevent it from being deleted. 此功能要求锁定 Cosmos 帐户,防止其被数据平面 SDK 更改。This feature requires locking the Cosmos account from being changed by data plane SDKs. 若要了解详细信息,请参阅防止被 SDK 更改To learn more see, Preventing changes from SDKs. Azure 资源锁也可以通过指定 ReadOnly 锁类型来防止更改资源。Azure resource locks can also prevent a resource from being changed by specifying a ReadOnly lock type. 对于 Cosmos 容器,此锁可用于防止更改吞吐量或其他任何属性。For a Cosmos container, this can be used to prevent throughput or any other property from being changed.

resourceGroupName='myResourceGroup'
accountName='mycosmosaccount'
databaseName='database1'
containerName='container1'

lockType='CanNotDelete' # CanNotDelete or ReadOnly
databaseParent="databaseAccounts/$accountName"
containerParent="databaseAccounts/$accountName/sqlDatabases/$databaseName"
containerLockName="$containerName-Lock"

# Create a delete lock on container
az lock create --name $containerLockName \
    --resource-group $resourceGroupName \
    --resource-type Microsoft.DocumentDB/containers \
    --lock-type $lockType \
    --parent $containerParent \
    --resource $containerName

# Delete lock on container
lockid=$(az lock show --name $containerLockName \
        --resource-group $resourceGroupName \
        --resource-type Microsoft.DocumentDB/containers \
        --resource-name $containerName \
        --parent $containerParent \
        --output tsv --query id)
az lock delete --ids $lockid

后续步骤Next steps

有关 Azure CLI 的详细信息,请参阅:For more information on the Azure CLI, see: