Gestire Azure Cosmos DB risorse API Core (SQL) con PowerShellManage Azure Cosmos DB Core (SQL) API resources using PowerShell

SI APPLICA A: API SQL

La guida seguente illustra come usare PowerShell per creare script e automatizzare la gestione di risorse API Azure Cosmos DB Core (SQL), tra cui l'account Cosmos, il database, il contenitore e la velocità effettiva.The following guide describes how to use PowerShell to script and automate management of Azure Cosmos DB Core (SQL) API resources, including the Cosmos account, database, container, and throughput. Per i cmdlet di PowerShell relativi ad altre API, vedere Esempi di PowerShell per Cassandra, Esempi di PowerShell per l'API MongoDB, Esempi di PowerShell per Gremlin, Esempi di PowerShell per TabellaFor PowerShell cmdlets for other APIs see PowerShell Samples for Cassandra, PowerShell Samples for MongoDB API, PowerShell Samples for Gremlin, PowerShell Samples for Table

Nota

Negli esempi di questo articolo vengono usati i cmdlet di gestione di Az.CosmosDB.Samples in this article use Az.CosmosDB management cmdlets. Per informazioni sulle ultime modifiche, vedere la pagina di informazioni di riferimento dell'API Az.CosmosDB.See the Az.CosmosDB API reference page for the latest changes.

Per la gestione multipiattaforma dell'account Azure Cosmos DB, è possibile usare i cmdlet Az e Az.CosmosDB con PowerShell multipiattaforma, l'interfaccia della riga di comando di Azure, l'API REST o il portale di Azure.For cross-platform management of Azure Cosmos DB, you can use the Az and Az.CosmosDB cmdlets with cross-platform PowerShell, as well as the Azure CLI, the REST API, or the Azure portal.

Nota

Questo articolo è stato aggiornato per usare il nuovo modulo Az di Azure PowerShell.This article has been updated to use the new Azure PowerShell Az module. È comunque possibile usare il modulo AzureRM, che continuerà a ricevere correzioni di bug almeno fino a dicembre 2020.You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. Per altre informazioni sul nuovo modulo Az e sulla compatibilità di AzureRM, vedere Introduzione del nuovo modulo Az di Azure PowerShell.To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. Per istruzioni sull'installazione del modulo Az, vedere Installare Azure PowerShell.For Az module installation instructions, see Install Azure PowerShell.

IntroduzioneGetting Started

Seguire le istruzioni indicate in Come installare e configurare Azure PowerShell per installare e accedere all'account Azure in PowerShell.Follow the instructions in How to install and configure Azure PowerShell to install and sign in to your Azure account in PowerShell.

Importante

Non è possibile rinominare Azure Cosmos DB risorse perché questo viola il modo in cui Azure Resource Manager funziona con gli URI delle risorse.Azure Cosmos DB resources cannot be renamed as this violates how Azure Resource Manager works with resource URIs.

Account Azure CosmosAzure Cosmos accounts

Le sezioni seguenti illustrano come gestire l'account Azure Cosmos:The following sections demonstrate how to manage the Azure Cosmos account, including:

Creare un account Azure CosmosCreate an Azure Cosmos account

Questo comando crea un account del database Azure Cosmos DB con più aree e failover automatico e il criterio di coerenza con decadimento ristretto.This command creates an Azure Cosmos DB database account with multiple regions, automatic failover and bounded-staleness consistency policy.

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$apiKind = "Sql"
$consistencyLevel = "BoundedStaleness"
$maxStalenessInterval = 300
$maxStalenessPrefix = 100000
$locations = @()
$locations += New-AzCosmosDBLocationObject -LocationName "East US" -FailoverPriority 0 -IsZoneRedundant 0
$locations += New-AzCosmosDBLocationObject -LocationName "West US" -FailoverPriority 1 -IsZoneRedundant 0

New-AzCosmosDBAccount `
    -ResourceGroupName $resourceGroupName `
    -LocationObject $locations `
    -Name $accountName `
    -ApiKind $apiKind `
    -EnableAutomaticFailover:$true `
    -DefaultConsistencyLevel $consistencyLevel `
    -MaxStalenessIntervalInSeconds $maxStalenessInterval `
    -MaxStalenessPrefix $maxStalenessPrefix
  • $resourceGroupName: gruppo di risorse di Azure in cui distribuire l'account Cosmos.$resourceGroupName The Azure resource group into which to deploy the Cosmos account. Deve essere già esistente.It must already exist.
  • $locations Le aree per l'account del database, l'area con FailoverPriority 0 è l'area di scrittura.$locations The regions for the database account, the region with FailoverPriority 0 is the write region.
  • $accountName Il nome dell'account Azure Cosmos.$accountName The name for the Azure Cosmos account. Deve essere univoco, includere solo caratteri alfanumerici minuscoli e '-' e avere una lunghezza compresa tra 3 e 31 caratteri.Must be unique, lowercase, include only alphanumeric and '-' characters, and between 3 and 31 characters in length.
  • $apiKind: tipo di account Cosmos da creare.$apiKind The type of Cosmos account to create. Per altre informazioni, vedere API in Cosmos DB.For more information, see APIs in Cosmos DB.
  • $consistencyPolicy,$maxStalenessInterval e$maxStalenessPrefix: livello di coerenza predefinito e impostazioni dell'account Azure Cosmos.$consistencyPolicy, $maxStalenessInterval, and $maxStalenessPrefix The default consistency level and settings of the Azure Cosmos account. Per altre informazioni, vedere Livelli di coerenza in Azure Cosmos DB.For more information, see Consistency Levels in Azure Cosmos DB.

Gli account Azure Cosmos possono essere configurati con firewall IP, endpoint servizio di rete virtuale ed endpoint privati.Azure Cosmos accounts can be configured with IP Firewall, Virtual Network service endpoints, and private endpoints. Per informazioni su come configurare il firewall IP per Azure Cosmos DB, vedere Configurare il firewall IP.For information on how to configure the IP Firewall for Azure Cosmos DB, see Configure IP Firewall. Per informazioni su come abilitare gli endpoint servizio per Azure Cosmos DB, vedere Configurare l'accesso da reti virtuali.For information on how to enable service endpoints for Azure Cosmos DB, see Configure access from virtual Networks. Per informazioni su come abilitare gli endpoint privati per Azure Cosmos DB, vedere Configurare l'accesso da endpoint privati.For information on how to enable private endpoints for Azure Cosmos DB, see Configure access from private endpoints.

Elencare tutti gli account Azure Cosmos in un gruppo di risorseList all Azure Cosmos accounts in a Resource Group

Questo comando elenca tutti gli account Azure Cosmos in un gruppo di risorse.This command lists all Azure Cosmos accounts in a Resource Group.

$resourceGroupName = "myResourceGroup"

Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName

Ottenere le proprietà di un account Azure CosmosGet the properties of an Azure Cosmos account

Questo comando consente di ottenere le proprietà di un account Azure Cosmos esistente.This command allows you to get the properties of an existing Azure Cosmos account.

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"

Get-AzCosmosDBAccount -ResourceGroupName $resourceGroupName -Name $accountName

Aggiornare un account Azure CosmosUpdate an Azure Cosmos account

Questo comando consente di aggiornare le proprietà di un account del database Azure Cosmos DB.This command allows you to update your Azure Cosmos DB database account properties. Le proprietà che possono essere aggiornate includono:Properties that can be updated include the following:

  • Aggiunta o rimozione di areeAdding or removing regions
  • Modifica dei criteri di coerenza predefinitiChanging default consistency policy
  • Modifica del filtro dell'intervallo IPChanging IP Range Filter
  • Modifica delle configurazioni di reti virtualiChanging Virtual Network configurations
  • Abilitazione di scritture in più areeEnabling multi-region writes

Nota

Non è possibile aggiungere o rimuovere simultaneamente aree (locations) e cambiare l'ordine delle proprietà per un account Azure Cosmos.You cannot simultaneously add or remove regions (locations) and change other properties for an Azure Cosmos account. La modifica delle aree deve essere eseguita come operazione distinta rispetto a qualsiasi altra modifica apportata all'account.Modifying regions must be performed as a separate operation from any other change to the account.

Nota

Questo comando consente di aggiungere e rimuovere aree, ma non di modificare le priorità di failover o attivare un failover manuale.This command allows you to add and remove regions but does not allow you to modify failover priorities or trigger a manual failover. Vedere Modificare la priorità di failover e Attivare un failover manuale.See Modify failover priority and Trigger manual failover.

# Create account with two regions
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$apiKind = "Sql"
$consistencyLevel = "Session"
$enableAutomaticFailover = $true
$locations = @()
$locations += New-AzCosmosDBLocationObject -LocationName "East US" -FailoverPriority 0 -IsZoneRedundant 0
$locations += New-AzCosmosDBLocationObject -LocationName "West US" -FailoverPriority 1 -IsZoneRedundant 0

# Create the Cosmos DB account
New-AzCosmosDBAccount `
    -ResourceGroupName $resourceGroupName `
    -LocationObject $locations `
    -Name $accountName `
    -ApiKind $apiKind `
    -EnableAutomaticFailover:$enableAutomaticFailover `
    -DefaultConsistencyLevel $consistencyLevel

# Add a region to the account
$locationObject2 = @()
$locationObject2 += New-AzCosmosDBLocationObject -LocationName "East US" -FailoverPriority 0 -IsZoneRedundant 0
$locationObject2 += New-AzCosmosDBLocationObject -LocationName "West US" -FailoverPriority 1 -IsZoneRedundant 0
$locationObject2 += New-AzCosmosDBLocationObject -LocationName "South Central US" -FailoverPriority 2 -IsZoneRedundant 0

Update-AzCosmosDBAccountRegion `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -LocationObject $locationObject2

Write-Host "Update-AzCosmosDBAccountRegion returns before the region update is complete."
Write-Host "Check account in Azure portal or using Get-AzCosmosDBAccount for region status."
Write-Host "When region was added, press any key to continue."
$HOST.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | OUT-NULL
$HOST.UI.RawUI.Flushinputbuffer()

# Remove West US region from the account
$locationObject3 = @()
$locationObject3 += New-AzCosmosDBLocationObject -LocationName "East US" -FailoverPriority 0 -IsZoneRedundant 0
$locationObject3 += New-AzCosmosDBLocationObject -LocationName "South Central US" -FailoverPriority 1 -IsZoneRedundant 0

Update-AzCosmosDBAccountRegion `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -LocationObject $locationObject3

Write-Host "Update-AzCosmosDBAccountRegion returns before the region update is complete."
Write-Host "Check account in Azure portal or using Get-AzCosmosDBAccount for region status."

Abilitare più aree di scrittura per un account Azure CosmosEnable multiple write regions for an Azure Cosmos account

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$enableAutomaticFailover = $false
$enableMultiMaster = $true

# First disable automatic failover - cannot have both automatic
# failover and multi-region writes on an account
Update-AzCosmosDBAccount `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -EnableAutomaticFailover:$enableAutomaticFailover

# Now enable multi-region writes
Update-AzCosmosDBAccount `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -EnableMultipleWriteLocations:$enableMultiMaster

Eliminare un account Azure CosmosDelete an Azure Cosmos account

Questo comando elimina un account Azure Cosmos esistente.This command deletes an existing Azure Cosmos account.

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"

Remove-AzCosmosDBAccount `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -PassThru:$true

Aggiornare i tag per un account Azure CosmosUpdate Tags of an Azure Cosmos account

Questo comando imposta i tag delle risorse di Azure per un account Azure Cosmos.This command sets the Azure resource tags for an Azure Cosmos account. I tag possono essere impostati sia durante la creazione dell'account con New-AzCosmosDBAccount, sia durante l'aggiornamento dell'account usando Update-AzCosmosDBAccount.Tags can be set both at account creation using New-AzCosmosDBAccount as well as on account update using Update-AzCosmosDBAccount.

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$tags = @{dept = "Finance"; environment = "Production";}

Update-AzCosmosDBAccount `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -Tag $tags

Elencare le chiavi dell'accountList Account Keys

Quando si crea un account Azure Cosmos, il servizio genera due chiavi di accesso primarie che possono essere usate per l'autenticazione quando si accede all'account Azure Cosmos.When you create an Azure Cosmos account, the service generates two primary access keys that can be used for authentication when the Azure Cosmos account is accessed. Vengono generate anche chiavi di sola lettura per l'autenticazione delle operazioni di sola lettura.Read-only keys for authenticating read-only operations are also generated. Generando due chiavi di accesso, Azure Cosmos DB consente di rigenerare e ruotare una chiave alla volta senza interruzioni dell'account Azure Cosmos.By providing two access keys, Azure Cosmos DB enables you to regenerate and rotate one key at a time with no interruption to your Azure Cosmos account. Gli account Cosmos DB hanno due chiavi di lettura/scrittura (primaria e secondaria) e due chiavi di sola lettura (primaria e secondaria).Cosmos DB accounts have two read-write keys (primary and secondary) and two read-only keys (primary and secondary).

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"

Get-AzCosmosDBAccountKey `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -Type "Keys"

Elencare le stringhe di connessioneList Connection Strings

Il comando seguente recupera le stringhe di connessione per connettere le app all'account Cosmos DB.The following command retrieves connection strings to connect apps to the Cosmos DB account.

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"

Get-AzCosmosDBAccountKey `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -Type "ConnectionStrings"

Rigenerare le chiavi dell'accountRegenerate Account Keys

Le chiavi di accesso a un account Azure Cosmos devono essere rigenerate periodicamente per garantire la sicurezza delle connessioni.Access keys to an Azure Cosmos account should be periodically regenerated to help keep connections secure. All'account sono assegnate una chiave di accesso primaria e una secondaria.A primary and secondary access keys are assigned to the account. In questo modo i client possono mantenere l'accesso quando una delle chiavi viene rigenerata.This allows clients to maintain access while one key at a time is regenerated. Esistono quattro tipi di chiavi per un account Azure Cosmos: Primary, Secondary, PrimaryReadonly e SecondaryReadonlyThere are four types of keys for an Azure Cosmos account (Primary, Secondary, PrimaryReadonly, and SecondaryReadonly)

$resourceGroupName = "myResourceGroup" # Resource Group must already exist
$accountName = "mycosmosaccount" # Must be all lower case
$keyKind = "primary" # Other key kinds: secondary, primaryReadOnly, secondaryReadOnly

New-AzCosmosDBAccountKey `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -KeyKind $keyKind

Abilitare il failover automaticoEnable automatic failover

Il comando seguente imposta il failover automatico di un account Cosmos DB nell'area secondaria se l'area primaria diventa non disponibile.The following command sets a Cosmos DB account to fail over automatically to its secondary region should the primary region become unavailable.

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$enableAutomaticFailover = $true
$enableMultiMaster = $false

# First disable multi-region writes - cannot have both automatic
# failover and multi-region writes on an account
Update-AzCosmosDBAccount `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -EnableMultipleWriteLocations:$enableMultiMaster

# Now enable automatic failover
Update-AzCosmosDBAccount `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -EnableAutomaticFailover:$enableAutomaticFailover

Modificare la priorità di failoverModify Failover Priority

Per gli account configurati con failover automatico, è possibile cambiare l'ordine in cui Cosmos alzerà di livello le repliche secondarie a primarie nel caso quelle primarie diventassero indisponibili.For accounts configured with Automatic Failover, you can change the order in which Cosmos will promote secondary replicas to primary should the primary become unavailable.

Per l'esempio seguente, si supponga che la priorità di failover corrente sia West US 2 = 0, East US 2 = 1, South Central US = 2.For the example below, assume the current failover priority is West US 2 = 0, East US 2 = 1, South Central US = 2. Il comando la modificherà impostandola su West US 2 = 0, South Central US = 1, East US 2 = 2.The command will change this to West US 2 = 0, South Central US = 1, East US 2 = 2.

Attenzione

La modifica della località per failoverPriority=0 attiverà un failover manuale per un account Azure Cosmos.Changing the location for failoverPriority=0 will trigger a manual failover for an Azure Cosmos account. Qualsiasi altra modifica della priorità non attiverà un failover.Any other priority changes will not trigger a failover.

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$locations = @("West US 2", "South Central US", "East US 2") # Regions ordered by UPDATED failover priority

Update-AzCosmosDBAccountFailoverPriority `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -FailoverPolicy $locations

Attivare un failover manualeTrigger Manual Failover

Per gli account configurati con failover manuale, è possibile eseguire il failover e alzare di livello qualsiasi replica secondaria a primaria modificando failoverPriority=0.For accounts configured with Manual Failover, you can fail over and promote any secondary replica to primary by modifying to failoverPriority=0. Questa operazione può essere usata per avviare un'esercitazione sul ripristino di emergenza per testarne la pianificazione.This operation can be used to initiate a disaster recovery drill to test disaster recovery planning.

Per l'esempio seguente, si presuppone che l'account abbia la priorità di failover corrente impostata su West US 2 = 0 e East US 2 = 1 e che le aree vengano invertite.For the example below, assume the account has a current failover priority of West US 2 = 0 and East US 2 = 1 and flip the regions.

Attenzione

Se si cambia locationName per failoverPriority=0, verrà attivato un failover manuale per un account Azure Cosmos.Changing locationName for failoverPriority=0 will trigger a manual failover for an Azure Cosmos account. Qualsiasi altra modifica della priorità non attiverà un failover.Any other priority change will not trigger a failover.

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$locations = @("East US 2", "West US 2") # Regions ordered by UPDATED failover priority

Update-AzCosmosDBAccountFailoverPriority `
    -ResourceGroupName $resourceGroupName `
    -Name $accountName `
    -FailoverPolicy $locations

Elencare i blocchi delle risorse in un account Azure Cosmos DBList resource locks on an Azure Cosmos DB account

È possibile inserire blocchi delle risorse per le risorse di Azure Cosmos DB, inclusi database e raccolte.Resource locks can be placed on Azure Cosmos DB resources including databases and collections. L'esempio seguente mostra come elencare tutti i blocchi delle risorse di Azure in un account Azure Cosmos DB.The example below shows how to list all Azure resource locks on an Azure Cosmos DB account.

$resourceGroupName = "myResourceGroup"
$resourceTypeAccount = "Microsoft.DocumentDB/databaseAccounts"
$accountName = "mycosmosaccount"

Get-AzResourceLock `
    -ResourceGroupName $resourceGroupName `
    -ResourceType $resourceTypeAccount `
    -ResourceName $accountName

Database Azure Cosmos DBAzure Cosmos DB Database

Le sezioni seguenti illustrano come gestire il database Azure Cosmos DB:The following sections demonstrate how to manage the Azure Cosmos DB database, including:

Creare un database Azure Cosmos DBCreate an Azure Cosmos DB database

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"

New-AzCosmosDBSqlDatabase `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -Name $databaseName

Creare un database Azure Cosmos DB con unità elaborate condiviseCreate an Azure Cosmos DB database with shared throughput

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$databaseRUs = 400

New-AzCosmosDBSqlDatabase `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -Name $databaseName `
    -Throughput $databaseRUs

Ottenere le unità elaborate di un database Azure Cosmos DBGet the throughput of an Azure Cosmos DB database

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"

Get-AzCosmosDBSqlDatabaseThroughput `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -Name $databaseName

Eseguire la migrazione della velocità effettiva del database alla scalabilità automaticaMigrate database throughput to autoscale

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"

Invoke-AzCosmosDBSqlDatabaseThroughputMigration `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -Name $databaseName `
    -ThroughputType Autoscale

Ottenere tutti i database Azure Cosmos DB in un accountGet all Azure Cosmos DB databases in an account

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"

Get-AzCosmosDBSqlDatabase `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName

Ottenere un singolo database Azure Cosmos DBGet a single Azure Cosmos DB database

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"

Get-AzCosmosDBSqlDatabase `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -Name $databaseName

Eliminare un database Azure Cosmos DBDelete an Azure Cosmos DB database

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"

Remove-AzCosmosDBSqlDatabase `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -Name $databaseName

Creare un blocco delle risorsa per un database Azure Cosmos DB per evitare l'eliminazioneCreate a resource lock on an Azure Cosmos DB database to prevent delete

$resourceGroupName = "myResourceGroup"
$resourceType = "Microsoft.DocumentDB/databaseAccounts/sqlDatabases"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$resourceName = "$accountName/$databaseName"
$lockName = "myResourceLock"
$lockLevel = "CanNotDelete"

New-AzResourceLock `
    -ResourceGroupName $resourceGroupName `
    -ResourceType $resourceType `
    -ResourceName $resourceName `
    -LockName $lockName `
    -LockLevel $lockLevel

Rimuovere un blocco delle risorse per un database Azure Cosmos DBRemove a resource lock on an Azure Cosmos DB database

$resourceGroupName = "myResourceGroup"
$resourceType = "Microsoft.DocumentDB/databaseAccounts/sqlDatabases"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$resourceName = "$accountName/$databaseName"
$lockName = "myResourceLock"

Remove-AzResourceLock `
    -ResourceGroupName $resourceGroupName `
    -ResourceType $resourceType `
    -ResourceName $resourceName `
    -LockName $lockName

Contenitore Azure Cosmos DBAzure Cosmos DB Container

Le sezioni seguenti illustrano come gestire il contenitore Azure Cosmos DB:The following sections demonstrate how to manage the Azure Cosmos DB container, including:

Creare un contenitore Azure Cosmos DBCreate an Azure Cosmos DB container

# Create an Azure Cosmos DB container with default indexes and throughput at 400 RU
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"
$partitionKeyPath = "/myPartitionKey"
$throughput = 400 #minimum = 400

New-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName `
    -PartitionKeyKind Hash `
    -PartitionKeyPath $partitionKeyPath `
    -Throughput $throughput

Creare un contenitore Azure Cosmos DB con scalabilità automaticaCreate an Azure Cosmos DB container with autoscale

# Create an Azure Cosmos DB container with default indexes and autoscale throughput at 4000 RU
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"
$partitionKeyPath = "/myPartitionKey"
$autoscaleMaxThroughput = 4000 #minimum = 4000

New-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName `
    -PartitionKeyKind Hash `
    -PartitionKeyPath $partitionKeyPath `
    -AutoscaleMaxThroughput $autoscaleMaxThroughput

Creare un contenitore Azure Cosmos DB con una chiave di partizione di grandi dimensioniCreate an Azure Cosmos DB container with a large partition key size

# Create an Azure Cosmos DB container with a large partition key value (version = 2)
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"
$partitionKeyPath = "/myPartitionKey"

New-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName `
    -PartitionKeyKind Hash `
    -PartitionKeyPath $partitionKeyPath `
    -PartitionKeyVersion 2

Ottenere le unità elaborate di un contenitore Azure Cosmos DBGet the throughput of an Azure Cosmos DB container

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"

Get-AzCosmosDBSqlContainerThroughput `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName

Eseguire la migrazione della velocità effettiva del contenitore alla scalabilità automaticaMigrate container throughput to autoscale

$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"

Invoke-AzCosmosDBSqlContainerThroughputMigration `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName `
    -ThroughputType Autoscale

Creare un contenitore Azure Cosmos DB con un criterio di indicizzazione personalizzatoCreate an Azure Cosmos DB container with custom index policy

# Create a container with a custom indexing policy
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"
$partitionKeyPath = "/myPartitionKey"
$indexPathIncluded = "/*"
$indexPathExcluded = "/myExcludedPath/*"

$includedPathIndex = New-AzCosmosDBSqlIncludedPathIndex -DataType String -Kind Range
$includedPath = New-AzCosmosDBSqlIncludedPath -Path $indexPathIncluded -Index $includedPathIndex

$indexingPolicy = New-AzCosmosDBSqlIndexingPolicy `
    -IncludedPath $includedPath `
    -ExcludedPath $indexPathExcluded `
    -IndexingMode Consistent `
    -Automatic $true

New-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName `
    -PartitionKeyKind Hash `
    -PartitionKeyPath $partitionKeyPath `
    -IndexingPolicy $indexingPolicy

Creare un contenitore Azure Cosmos DB con indicizzazione disattivataCreate an Azure Cosmos DB container with indexing turned off

# Create an Azure Cosmos DB container with no indexing
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"
$partitionKeyPath = "/myPartitionKey"

$indexingPolicy = New-AzCosmosDBSqlIndexingPolicy `
    -IndexingMode None

New-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName `
    -PartitionKeyKind Hash `
    -PartitionKeyPath $partitionKeyPath `
    -IndexingPolicy $indexingPolicy

Creare un contenitore Azure Cosmos DB con chiave univoca e TTLCreate an Azure Cosmos DB container with unique key policy and TTL

# Create a container with a unique key policy and TTL of one day
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"
$partitionKeyPath = "/myPartitionKey"
$uniqueKeyPath = "/myUniqueKeyPath"
$ttlInSeconds = 86400 # Set this to -1 (or don't use it at all) to never expire

$uniqueKey = New-AzCosmosDBSqlUniqueKey `
    -Path $uniqueKeyPath

$uniqueKeyPolicy = New-AzCosmosDBSqlUniqueKeyPolicy `
    -UniqueKey $uniqueKey

New-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName `
    -PartitionKeyKind Hash `
    -PartitionKeyPath $partitionKeyPath `
    -UniqueKeyPolicy $uniqueKeyPolicy `
    -TtlInSeconds $ttlInSeconds

Creare un contenitore Azure Cosmos DB con risoluzione dei conflittiCreate an Azure Cosmos DB container with conflict resolution

Per scrivere tutti i conflitti in ConflictsFeed e gestirli separatamente, passare -Type "Custom" -Path "".To write all conflicts to the ConflictsFeed and handle separately, pass -Type "Custom" -Path "".

# Create container with last-writer-wins conflict resolution policy
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"
$partitionKeyPath = "/myPartitionKey"
$conflictResolutionPath = "/myResolutionPath"

$conflictResolutionPolicy = New-AzCosmosDBSqlConflictResolutionPolicy `
    -Type LastWriterWins `
    -Path $conflictResolutionPath

New-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName `
    -PartitionKeyKind Hash `
    -PartitionKeyPath $partitionKeyPath `
    -ConflictResolutionPolicy $conflictResolutionPolicy

Per creare un criterio di risoluzione dei conflitti per l'uso di una stored procedure, chiamare New-AzCosmosDBSqlConflictResolutionPolicy e passare i parametri -Type e -ConflictResolutionProcedure.To create a conflict resolution policy to use a stored procedure, call New-AzCosmosDBSqlConflictResolutionPolicy and pass parameters -Type and -ConflictResolutionProcedure.

# Create container with custom conflict resolution policy using a stored procedure
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"
$partitionKeyPath = "/myPartitionKey"
$conflictResolutionSprocName = "mysproc"

$conflictResolutionSproc = "/dbs/$databaseName/colls/$containerName/sprocs/$conflictResolutionSprocName"

$conflictResolutionPolicy = New-AzCosmosDBSqlConflictResolutionPolicy `
    -Type Custom `
    -ConflictResolutionProcedure $conflictResolutionSproc

New-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName `
    -PartitionKeyKind Hash `
    -PartitionKeyPath $partitionKeyPath `
    -ConflictResolutionPolicy $conflictResolutionPolicy

Elencare tutti i contenitori Azure Cosmos DB in un databaseList all Azure Cosmos DB containers in a database

# List all Azure Cosmos DB containers in a database
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"

Get-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName

Ottenere un singolo contenitore Azure Cosmos DB in un databaseGet a single Azure Cosmos DB container in a database

# Get a single Azure Cosmos DB container in a database
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"

Get-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName

Eliminare un contenitore Azure Cosmos DBDelete an Azure Cosmos DB container

# Delete an Azure Cosmos DB container
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"

Remove-AzCosmosDBSqlContainer `
    -ResourceGroupName $resourceGroupName `
    -AccountName $accountName `
    -DatabaseName $databaseName `
    -Name $containerName

Creare un blocco delle risorse per un contenitore Azure Cosmos DB per impedire l'eliminazioneCreate a resource lock on an Azure Cosmos DB container to prevent delete

$resourceGroupName = "myResourceGroup"
$resourceType = "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"
$resourceName = "$accountName/$databaseName/$containerName"
$lockName = "myResourceLock"
$lockLevel = "CanNotDelete"

New-AzResourceLock `
    -ResourceGroupName $resourceGroupName `
    -ResourceType $resourceType `
    -ResourceName $resourceName `
    -LockName $lockName `
    -LockLevel $lockLevel

Rimuovere un blocco delle risorse per un contenitore Azure Cosmos DBRemove a resource lock on an Azure Cosmos DB container

$resourceGroupName = "myResourceGroup"
$resourceType = "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers"
$accountName = "mycosmosaccount"
$databaseName = "myDatabase"
$containerName = "myContainer"
$resourceName = "$accountName/$databaseName/$containerName"
$lockName = "myResourceLock"

Remove-AzResourceLock `
    -ResourceGroupName $resourceGroupName `
    -ResourceType $resourceType `
    -ResourceName $resourceName `
    -LockName $lockName

Passaggi successiviNext steps