Using the Azure Cosmos DB Python SDK
This tutorial guides you through the process of connecting to and interacting with Azure Cosmos DB using the official Python SDK. Learn how to perform basic CRUD operations, query data, and manage resources.
Prerequisites: Ensure you have an Azure subscription and an Azure Cosmos DB account set up. You'll also need Python installed on your development machine.
Step 1: Install the Azure Cosmos DB SDK
First, install the Azure Cosmos DB Python SDK using pip:
pip install azure-cosmos
Step 2: Connect to Your Cosmos DB Account
You'll need your Cosmos DB endpoint and primary key to connect. You can find these in the Azure portal under your Cosmos DB account's 'Keys' section.
Create a Python script (e.g., cosmos_tutorial.py
) and add the following code:
from azure.cosmos import CosmosClient
# Replace with your actual endpoint and key
endpoint = "YOUR_COSMOS_DB_ENDPOINT"
key = "YOUR_COSMOS_DB_PRIMARY_KEY"
try:
client = CosmosClient(endpoint, key)
print("Successfully connected to Azure Cosmos DB.")
except Exception as e:
print(f"Failed to connect: {e}")
Replace YOUR_COSMOS_DB_ENDPOINT
and YOUR_COSMOS_DB_PRIMARY_KEY
with your credentials.
Step 3: Create a Database and Container
Databases in Cosmos DB are logical containers for your data. Containers (formerly collections) hold your items (documents).
# Create a database (if it doesn't exist)
database_name = "mySampleDatabase"
database = client.create_database_if_not_exists(database_name)
print(f"Database '{database.id}' created or already exists.")
# Create a container (if it doesn't exist)
container_name = "mySampleContainer"
container = database.create_container_if_not_exists(
id=container_name,
partition_key="/categoryId" # Define your partition key path
)
print(f"Container '{container.id}' created or already exists.")
Here, /categoryId
is used as the partition key. Choose a partition key that distributes your data evenly for optimal performance.
Step 4: Create an Item (Document)
Items are JSON documents stored within containers.
# Define an item
item_body = {
"id": "item1",
"name": "Example Item",
"categoryId": "A",
"description": "This is a sample item for demonstration.",
"tags": ["sample", "tutorial"]
}
# Create the item
created_item = container.create_item(body=item_body)
print(f"Created item with id: {created_created_item['id']}")
Step 5: Read an Item
You can retrieve an item using its ID and partition key.
# Read the item by its ID
read_item = container.read_item(item="item1", partition_key="A")
print(f"Read item: {read_item}")
Step 6: Query Items
Cosmos DB supports SQL-like queries to retrieve data.
# Query items with a specific categoryId
query = "SELECT * FROM c WHERE c.categoryId = 'A'"
items = list(container.query_items(
query=query,
enable_cross_partition_query=False # Set to True for cross-partition queries if needed
))
print(f"Found {len(items)} items matching the query:")
for item in items:
print(f"- {item['id']}")
Step 7: Update an Item
You can replace an existing item or upsert (update or insert) it.
# Update an item
item_body.update({
"description": "This item has been updated.",
"quantity": 100
})
updated_item = container.upsert_item(body=item_body)
print(f"Updated item with id: {updated_item['id']}")
Step 8: Delete an Item
Remove an item from the container.
# Delete the item
container.delete_item(item="item1", partition_key="A")
print(f"Deleted item with id: item1")
Further Exploration: This tutorial covers basic operations. The Azure Cosmos DB Python SDK supports more advanced features like conflict resolution, stored procedures, user-defined functions, and change feed. Refer to the official SDK reference for more details.