Python Program to create Container if not exist with partition key and unique Key

Question:

I want to write python script to create container only if it not exist with partition key and unique key.

Steps for  Creating Alert Container
 1. Create Container With Container ID: alerts
 2. Add Partition Key as /user_tenant
 3. Add Unique Key as /alert_id

reference link: https://github.com/Azure/azure-cosmos-python#create-a-container

plz suggest the api that will create container if it not present.

Asked By: Mohit Singh

||

Answers:

@Gaurav Mantri
Below is the working code as suggested by you.
for uniqueKeys we need to add it inside uniqueKeyPolicy as shown in below code.

import azure.cosmos.documents as documents
from azure.cosmos import cosmos_client, http_constants, errors
import os

url = os.environ['COSMOS_DB_END_POINT']
key = os.environ['COSMOS_DB_MASTER_KEY']
database_name = os.environ["COSMOS_DB_DATABASE_ID"]
client = cosmos_client.CosmosClient(url, {'masterKey': key})

container_definition = {'id': 'alerts_test',
                        'partitionKey':
                            {
                                'paths': ['/user_tenant'],
                                'kind': documents.PartitionKind.Hash
                            },
                        'uniqueKeyPolicy': {
                            'uniqueKeys':
                                [
                                    {'paths': ['/alert_id']}
                                ]
                        }
                        }

try:
    container = client.CreateContainer("dbs/" + database_name, container_definition, {'offerThroughput': 400})
    print("New Container Created:")
    print(container)
except errors.HTTPFailure as e:
    if e.status_code == http_constants.StatusCodes.CONFLICT:
        container = client.ReadContainer("dbs/" + database_name + "/colls/" + container_definition['id'])
        print(container)
    else:
        raise e
Answered By: Mohit Singh

Here is my answer.

Create Connection

import azure.cosmos.cosmos_client as cosmos_client

COMOS_MASTER_KEY = "*****" 
COMOS_ENDPOINT = "https://account.documents.azure.com:port/" 

client = cosmos_client.CosmosClient(url=COMOS_ENDPOINT, credential={"masterKey":COMOS_MASTER_KEY})

Create Database If Not Exist

database = client.create_database_if_not_exists({'id': database_name,'offer_throughput':20000})

Create Collection If it does Not Exist

database.create_container_if_not_exists(id="collection_name",partition_key=PartitionKey(path="/partition_key_path"),offer_throughput=1000)
Answered By: Abhishek Tomar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.