Create a database and container for Azure Cosmos DB - API for NoSQL

APPLIES TO: NoSQL

Note

We recommend that you use the Azure Az PowerShell module to interact with Azure. See Install Azure PowerShell to get started. To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.

This sample requires Azure PowerShell Az 5.4.0 or later. Run Get-Module -ListAvailable Az to see which versions are installed. If you need to install, see Install Azure PowerShell module.

Run Connect-AzAccount to sign in to Azure.

Sample script

This script creates an Azure Cosmos DB account for API for NoSQL in two regions with session level consistency, a database, and a container with a partition key, custom indexing policy, unique key policy, TTL, dedicated throughput, and last writer wins conflict resolution policy with a custom conflict resolution path that will be used when multipleWriteLocations=true.

# Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb
# --------------------------------------------------
# Purpose
# Create Cosmos SQL API account, database, and container with dedicated throughput,
# indexing policy with include, exclude, and composite paths, unique key, and conflict resolution
# --------------------------------------------------
Function New-RandomString{Param ([Int]$Length = 10) return $(-join ((97..122) + (48..57) | Get-Random -Count $Length | ForEach-Object {[char]$_}))}
# --------------------------------------------------
$uniqueId = New-RandomString -Length 7 # Random alphanumeric string for unique resource names
$apiKind = "Sql"
# --------------------------------------------------
# Variables - ***** SUBSTITUTE YOUR VALUES *****
$locations = @()
$locations += New-AzCosmosDBLocationObject -LocationName "East Us" -FailoverPriority 0 -IsZoneRedundant 0
$locations += New-AzCosmosDBLocationObject -LocationName "West Us" -FailoverPriority 1 -IsZoneRedundant 0

$resourceGroupName = "myResourceGroup" # Resource Group must already exist
$accountName = "cosmos-$uniqueId" # Must be all lower case
$consistencyLevel = "Session"
$tags = @{Tag1 = "MyTag1"; Tag2 = "MyTag2"; Tag3 = "MyTag3"}
$databaseName = "myDatabase"
$containerName = "myContainer"
$containerRUs = 400
$partitionKeyPath = "/myPartitionKey"
$indexPathIncluded = "/*"
$compositeIndexPaths1 = @(
    @{ Path = "/myCompositePath1"; Order = "ascending" };
    @{ Path = "/myCompositePath2"; Order = "descending" }
)
$compositeIndexPaths2 = @(
    @{ Path = "/myCompositePath3"; Order = "ascending" };
    @{ Path = "/myCompositePath4"; Order = "descending" }
)
$indexPathExcluded = "/myExcludedPath/*"
$uniqueKeyPath = "/myUniqueKeyPath"
$conflictResolutionPath = "/myResolutionPath"
$ttlInSeconds = 120 # Set this to -1 (or don't use it at all) to never expire
# --------------------------------------------------
Write-Host "Creating account $accountName"

$account = New-AzCosmosDBAccount -ResourceGroupName $resourceGroupName `
    -LocationObject $locations -Name $accountName -ApiKind $apiKind -Tag $tags `
    -DefaultConsistencyLevel $consistencyLevel `
    -EnableAutomaticFailover:$true

Write-Host "Creating database $databaseName"
$database = New-AzCosmosDBSqlDatabase -ParentObject $account -Name $databaseName

$uniqueKey = New-AzCosmosDBSqlUniqueKey -Path $uniqueKeyPath
$uniqueKeyPolicy = New-AzCosmosDBSqlUniqueKeyPolicy -UniqueKey $uniqueKey

$compositePath1 = @()
ForEach ($compositeIndexPath in $compositeIndexPaths1) {
    $compositePath1 += New-AzCosmosDBSqlCompositePath `
        -Path $compositeIndexPath.Path `
        -Order $compositeIndexPath.Order
}

$compositePath2 = @()
ForEach ($compositeIndexPath in $compositeIndexPaths2) {
    $compositePath2 += New-AzCosmosDBSqlCompositePath `
        -Path $compositeIndexPath.Path `
        -Order $compositeIndexPath.Order
}

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

$indexingPolicy = New-AzCosmosDBSqlIndexingPolicy `
    -IncludedPath $includedPath `
    -CompositePath @($compositePath1, $compositePath2) `
    -ExcludedPath $indexPathExcluded `
    -IndexingMode Consistent -Automatic $true

# Conflict resolution policies only apply in multi-master accounts.
# Included here to show custom resolution path.
$conflictResolutionPolicy = New-AzCosmosDBSqlConflictResolutionPolicy `
    -Type LastWriterWins -Path $conflictResolutionPath

Write-Host "Creating container $containerName"
$container = New-AzCosmosDBSqlContainer `
    -ParentObject $database -Name $containerName `
    -Throughput $containerRUs -IndexingPolicy $indexingPolicy `
    -PartitionKeyKind Hash -PartitionKeyPath $partitionKeyPath `
    -UniqueKeyPolicy $uniqueKeyPolicy `
    -ConflictResolutionPolicy $conflictResolutionPolicy `
    -TtlInSeconds $ttlInSeconds

Clean up deployment

After the script sample has been run, the following command can be used to remove the resource group and all resources associated with it.

Remove-AzResourceGroup -ResourceGroupName "myResourceGroup"

Script explanation

This script uses the following commands. Each command in the table links to command specific documentation.

Command Notes
Azure Cosmos DB
New-AzCosmosDBAccount Creates an Azure Cosmos DB Account.
New-AzCosmosDBSqlDatabase Creates an Azure Cosmos DB SQL Database.
New-AzCosmosDBSqlUniqueKey Creates a PSSqlUniqueKey object used as a parameter for New-AzCosmosDBSqlUniqueKeyPolicy.
New-AzCosmosDBSqlUniqueKeyPolicy Creates a PSSqlUniqueKeyPolicy object used as a parameter for New-AzCosmosDBSqlContainer.
New-AzCosmosDBSqlCompositePath Creates a PSCompositePath object used as a parameter for New-AzCosmosDBSqlIndexingPolicy.
New-AzCosmosDBSqlIncludedPathIndex Creates a PSIndexes object used as a parameter for New-AzCosmosDBSqlIncludedPath.
New-AzCosmosDBSqlIncludedPath Creates a PSIncludedPath object used as a parameter for New-AzCosmosDBSqlIndexingPolicy.
New-AzCosmosDBSqlIndexingPolicy Creates a PSSqlIndexingPolicy object used as a parameter for New-AzCosmosDBSqlContainer.
New-AzCosmosDBSqlConflictResolutionPolicy Creates a PSSqlConflictResolutionPolicy object used as a parameter for New-AzCosmosDBSqlContainer.
New-AzCosmosDBSqlContainer Creates a new Azure Cosmos DB SQL Container.
Azure Resource Groups
Remove-AzResourceGroup Deletes a resource group including all nested resources.

Next steps

For more information on the Azure PowerShell, see Azure PowerShell documentation.