-
Notifications
You must be signed in to change notification settings - Fork 374
Expand file tree
/
Copy pathcosmosdb_example.py
More file actions
75 lines (58 loc) · 2.4 KB
/
Copy pathcosmosdb_example.py
File metadata and controls
75 lines (58 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import json
from azure.cosmos import CosmosClient, PartitionKey
from testcontainers.community.cosmosdb import CosmosDbContainer
def basic_example():
with CosmosDbContainer() as cosmos:
# Get connection parameters
endpoint = cosmos.get_connection_url()
key = cosmos.get_primary_key()
# Create CosmosDB client
client = CosmosClient(endpoint, key)
# Create a database
database_name = "test_database"
database = client.create_database_if_not_exists(id=database_name)
print(f"Created database: {database_name}")
# Create a container
container_name = "test_container"
container = database.create_container_if_not_exists(
id=container_name, partition_key=PartitionKey(path="/category")
)
print(f"Created container: {container_name}")
# Insert test items
test_items = [
{"id": "1", "category": "test1", "name": "Item 1", "value": 100},
{"id": "2", "category": "test2", "name": "Item 2", "value": 200},
{"id": "3", "category": "test1", "name": "Item 3", "value": 300},
]
for item in test_items:
container.create_item(body=item)
print("Inserted test items")
# Query items
query = "SELECT * FROM c WHERE c.category = 'test1'"
items = list(container.query_items(query=query, enable_cross_partition_query=True))
print("\nQuery results:")
for item in items:
print(json.dumps(item, indent=2))
# Execute a more complex query
query = """
SELECT
c.category,
COUNT(1) as count,
AVG(c.value) as avg_value,
MIN(c.value) as min_value,
MAX(c.value) as max_value
FROM c
GROUP BY c.category
"""
results = list(container.query_items(query=query, enable_cross_partition_query=True))
print("\nAggregation results:")
for result in results:
print(json.dumps(result, indent=2))
# Get container info
container_properties = container.read()
print("\nContainer properties:")
print(f"ID: {container_properties['id']}")
print(f"Partition Key: {container_properties['partitionKey']}")
print(f"Indexing Policy: {json.dumps(container_properties['indexingPolicy'], indent=2)}")
if __name__ == "__main__":
basic_example()