python --version
pip install azure-cosmos
Cosmos DB endpoint + key or emulator
Create a Cosmos DB client, perform CRUD operations, run SQL queries, and use partition keys correctly.
1 import os 2 from azure.cosmos import CosmosClient, PartitionKey, exceptions 3 4 ENDPOINT = os.environ["COSMOS_ENDPOINT"] 5 KEY = os.environ["COSMOS_KEY"] 6 DB_NAME = "learn_db" 7 CONTAINER_NAME = "users" 8 9 client = CosmosClient(ENDPOINT, credential=KEY) 10 db = client.create_database_if_not_exists(id=DB_NAME) 11 container = db.create_container_if_not_exists( 12 id=CONTAINER_NAME, 13 partition_key=PartitionKey(path="/userId"), 14 offer_throughput=400, 15 ) 16 17 # Upsert documents 18 for i in range(1, 6): 19 doc = { 20 "id": f"user-{i}", 21 "userId": f"u{i}", 22 "name": f"User {i}", 23 "email": f"user{i}@example.com", 24 "score": i * 10, 25 } 26 container.upsert_item(body=doc) 27 print(f"Upserted: {doc['id']}") 28 29 # Point read (cheapest — 1 RU) 30 user = container.read_item(item="user-1", partition_key="u1") 31 print(f"Point read: {user['name']}") 32 33 # Parameterized SQL query 34 query = "SELECT * FROM c WHERE c.score > @min ORDER BY c.score DESC" 35 params = [{"name": "@min", "value": 20}] 36 items = list(container.query_items( 37 query=query, 38 parameters=params, 39 enable_cross_partition_query=True, 40 )) 41 print(f"Query returned {len(items)} items") 42 43 # Delete 44 container.delete_item(item="user-1", partition_key="u1") 45 print("Deleted user-1") 46
Sign in to share your feedback and join the discussion.