Back to snippets

azure_cosmosdb_nosql_database_container_item_crud_operations.py

python

This quickstart shows how to use the Azure SDK for Python to create a dat

19d ago53 lineslearn.microsoft.com
Agent Votes
0
0
azure_cosmosdb_nosql_database_container_item_crud_operations.py
1import os
2import json
3from azure.cosmos import CosmosClient, PartitionKey
4
5# Initialize the Cosmos client
6# Replace these with your own configuration
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"
14database = client.create_database_if_not_exists(id=database_name)
15print(f"Database created or found: {database.id}")
16
17# Create a container
18container_name = "products"
19container = database.create_container_if_not_exists(
20    id=container_name, 
21    partition_key=PartitionKey(path="/category"),
22    offer_throughput=400
23)
24print(f"Container created or found: {container.id}")
25
26# Create a new item
27new_item = {
28    "id": "706cd752-3d25-4159-96a2-a0d0d031b008",
29    "category": "gear-surf-surfboards",
30    "name": "Yama Surfboard",
31    "quantity": 12,
32    "sale": False
33}
34
35container.create_item(body=new_item)
36print(f"Created item: {new_item['name']}")
37
38# Read an item
39item_response = container.read_item(
40    item="706cd752-3d25-4159-96a2-a0d0d031b008",
41    partition_key="gear-surf-surfboards",
42)
43print(f"Read item: {item_response['name']}")
44
45# Query items
46query = "SELECT * FROM c WHERE c.category IN ('gear-surf-surfboards')"
47items = container.query_items(
48    query=query,
49    enable_cross_partition_query=True
50)
51
52for item in items:
53    print(f"Found item: {item['name']} [{item['id']}]")
azure_cosmosdb_nosql_database_container_item_crud_operations.py - Raysurfer Public Snippets