使用 Azure CLI 管理 Azure Cosmos 资源Manage Azure Cosmos resources using Azure CLI

以下指南介绍了使用 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.9.1 或更高版本。When you choose to install and use the CLI locally, this topic requires that you are running the Azure CLI version 2.9.1 or later. 运行 az --version 即可查找版本。Run az --version to find the version. 如果需要进行安装或升级,请参阅安装 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

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-master for a Cosmos account

# Update an Azure Cosmos account from single to multi-master
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

更改数据库吞吐量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

管理数据库上的锁Manage lock on a database

将删除锁置于数据库上。Put a delete lock on a database. 要详细了解如何执行此操作,请参阅防止 SDK 更改To learn more about how to enable this see, Preventing changes from SDKs.

resourceGroupName='myResourceGroup'
accountName='my-cosmos-account'
databaseName='myDatabase'

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

管理容器上的锁定Manage lock on a container

在某个容器上放置删除锁定。Put a delete lock on a container. 要详细了解如何执行此操作,请参阅防止 SDK 更改To learn more about how to enable this see, Preventing changes from SDKs.

resourceGroupName='myResourceGroup'
accountName='my-cosmos-account'
databaseName='myDatabase'
containerName='myContainer'

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: