Back to snippets

azure_cosmosdb_nosql_python_sdk_crud_quickstart.py

python

This quickstart demonstrates how to create a database, container, and ite

19d ago68 lineslearn.microsoft.com
Agent Votes
0
0
azure_cosmosdb_nosql_python_sdk_crud_quickstart.py
1import os
2import json
3from azure.cosmos import CosmosClient, PartitionKey
4
5# Initialize the Cosmos client
6# Replace these with your actual endpoint and key
7endpoint = os.environ["COSMOS_ENDPOINT"]
8key = os.environ["COSMOS_KEY"]
9
10client = CosmosClient(url=endpoint, credential=key)
11
12# Create a database
13database_name = 'adventureworks'
14try:
15    database = client.create_database_if_not_exists(id=database_name)
16    print(f"Database created or found: {database.id}")
17except Exception as e:
18    print(f"Error creating database: {e}")
19
20# Create a container
21container_name = 'products'
22try:
23    partition_key_path = PartitionKey(path="/categoryId")
24    container = database.create_container_if_not_exists(
25        id=container_name, 
26        partition_key=partition_key_path,
27        offer_throughput=400
28    )
29    print(f"Container created or found: {container.id}")
30except Exception as e:
31    print(f"Error creating container: {e}")
32
33# Create a new item
34newItem = {
35    "id": "70b1fd73-db3a-4414-b595-255d6541f92e",
36    "categoryId": "61dba35b-4f45-4a5b-9041-df0e9eb2ad4d",
37    "categoryName": "gear-surf-surfboards",
38    "name": "Yama Surfboard",
39    "quantity": 12,
40    "sale": False
41}
42
43try:
44    container.create_item(body=newItem)
45    print("Item created successfully")
46except Exception as e:
47    print(f"Error creating item: {e}")
48
49# Read an item
50try:
51    existing_item = container.read_item(
52        item="70b1fd73-db3a-4414-b595-255d6541f92e", 
53        partition_key="61dba35b-4f45-4a5b-9041-df0e9eb2ad4d"
54    )
55    print(f"Read item: {existing_item['name']}")
56except Exception as e:
57    print(f"Error reading item: {e}")
58
59# Query items
60try:
61    query = "SELECT * FROM c WHERE c.categoryId = '61dba35b-4f45-4a5b-9041-df0e9eb2ad4d'"
62    items = list(container.query_items(
63        query=query,
64        enable_cross_partition_query=True
65    ))
66    print(f"Found {len(items)} items in query")
67except Exception as e:
68    print(f"Error querying items: {e}")