azure-cosmos-py
microsoft/skills
Führen Sie mit dem Python-SDK CRUD-Operationen durch, führen Sie Abfragen aus und verwalten Sie Container über die Azure Cosmos DB NoSQL-API.
...Alle erweiternAzure Cosmos DB SDK für Python
Client-Bibliothek für die Azure Cosmos DB NoSQL-API – eine global verteilte Datenbank mit mehreren Modellen.
Installation
pip install azure-cosmos azure-identity
Umgebungsvariablen
COSMOS_ENDPOINT=https://.documents.azure.com:443/ # Erforderlich für alle Authentifizierungsmethoden
COSMOS_DATABASE=mydb # Erforderlich für alle Authentifizierungsmethoden
COSMOS_CONTAINER=mycontainer # Erforderlich für alle Authentifizierungsmethoden
AZURE_TOKEN_CREDENTIALS=prod # Nur erforderlich, wenn „DefaultAzureCredential“ in der Produktion verwendet wird
Authentifizierung und Lebenszyklus
🔑 Für alle folgenden Code-Beispiele gelten zwei Regeln:
- Verwenden Sie vorzugsweise
„DefaultAzureCredential“. Es funktioniert lokal (Azure-CLI / VS Code / Entwickler-CLI) und in Azure (verwaltete Identität, Workload-Identität) ohne Codeänderungen. Vermeiden Sie Verbindungszeichenfolgen, Konto- und API-Schlüssel – diese umgehen die Entra-Prüfung und -Rotation.
- Lokale Entwicklung:
„DefaultAzureCredential“funktioniert ohne weitere Anpassungen.- Produktion: Setzen Sie
AZURE_TOKEN_CREDENTIALS=prod(oderAZURE_TOKEN_CREDENTIALS=), um die Anmeldeinformationskette auf produktionssichere Anmeldeinformationen zu beschränken.- Hüllen Sie jeden Client in einen Kontextmanager, damit HTTP-Transporte, Sockets und Token-Caches deterministisch freigegeben werden:
- Synchron:
mit `(...)` als Client: - Asynchron:
async mitund(...) als Client: async mit DefaultAzureCredential() als Anmeldeinformationen:(ausazure.identity.aio)Code-Schnipsel können diese Konfiguration zwar verkürzen, aber Produktionscode sollte stets beide Regeln befolgen.
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.cosmos import CosmosClient
# Lokale Entwicklung: DefaultAzureCredential. Produktion: Setze AZURE_TOKEN_CREDENTIALS=prod oder AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# Oder verwenden Sie in der Produktion direkt spezifische Anmeldedaten:
# Siehe https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
endpoint = "https://.documents.azure.com:443/"
with CosmosClient(url=endpoint, credential=credential) as client:
# Verwenden Sie den Client hier (Operationen siehe folgende Abschnitte)
...
Client-Hierarchie
| Client | Zweck | Beziehen aus |
|---|---|---|
CosmosClient |
Vorgänge auf Kontoebene | Direkte Instanziierung |
DatabaseProxy |
Datenbankoperationen | client.get_database_client() |
ContainerProxy |
Container-/Elementoperationen | database.get_container_client() |
Kern-Workflow
Datenbank und Container einrichten
# Datenbank abrufen oder erstellen
database = client.create_database_if_not_exists(id="mydb")
# Container mit Partitionsschlüssel abrufen oder erstellen
container = database.create_container_if_not_exists(
id="mycontainer",
partition_key=PartitionKey(path="/category")
)
# Vorhandene abrufen
database = client.get_database_client("mydb")
container = database.get_container_client("mycontainer")
Element anlegen
item = {
"id": "item-001", # Erforderlich: innerhalb der Partition eindeutig
"category": "electronics", # Wert des Partitionsschlüssels
"name": "Laptop",
"price": 999,99,
"tags": ["Computer", "tragbar"]
}
created = container.create_item(body=item)
print(f"Erstellt: {created['id']}")
Element lesen
# Zum Lesen sind die ID UND der Partitionsschlüssel erforderlich
item = container.read_item(
item="item-001",
partition_key="electronics"
)
print(f"Name: {item['name']}")
Element aktualisieren (ersetzen)
item = container.read_item(item="item-001", partition_key="electronics")
item["price"] = 899,99
item["on_sale"] = True
updated = container.replace_item(item=item["id"], body=item)
Element einfügen oder aktualisieren
# Anlegen, falls nicht vorhanden; ersetzen, falls vorhanden
item = {
"id": "item-002",
"category": "electronics",
"name": "Tablet",
"price": 499.99
}
result = container.upsert_item(body=item)
Element löschen
container.delete_item(
item="item-001",
partition_key="electronics"
)
Abfragen
Einfache Abfrage
# Abfrage innerhalb einer Partition (effizient)
query = "SELECT * FROM c WHERE c.price < @max_price"
items = container.query_items(
query=query,
parameters=[{"name": "@max_price", "value": 500}],
partition_key="electronics"
)
for item in items:
print(f"{item['name']}: ${item['price']}")
</code></pre>
<h3>Partitionsübergreifende Abfrage</h3>
<pre><code class="language-python"># Partitionsübergreifend (aufwändiger, sparsam einsetzen)
query = "SELECT * FROM c WHERE c.price < @max_price"
items = container.query_items(
query=query,
parameters=[{"name": "@max_price", "value": 500}],
enable_cross_partition_query=True
)
for item in items:
print(item)
</code></pre>
<h3>Abfrage mit Projektion</h3>
<pre><code class="language-python">query = "SELECT c.id, c.name, c.price FROM c WHERE c.category = @category"
items = container.query_items(
query=query,
parameters=[{"name": "@category", "value": "electronics"}],
partition_key="electronics"
)
</code></pre>
<h3>Alle Elemente lesen</h3>
<pre><code class="language-python"># Alle Elemente in einer Partition lesen
items = container.read_all_items() # Partitionsübergreifend
# Oder mit Partitionsschlüssel
items = container.query_items(
query="SELECT * FROM c",
partition_key="electronics"
)
</code></pre>
<h2>Partitionsschlüssel</h2>
<p><strong>Wichtig</strong>: Geben Sie für effiziente Operationen immer den Partitionsschlüssel an.</p>
<pre><code class="language-python">from azure.cosmos import PartitionKey
# Einzelner Partitionsschlüssel
container = database.create_container_if_not_exists(
id="orders",
partition_key=PartitionKey(path="/customer_id")
)
# Hierarchischer Partitionsschlüssel (Vorschau)
container = database.create_container_if_not_exists(
id="events",
partition_key=PartitionKey(path=["/tenant_id", "/user_id"])
)
</code></pre>
<h2>Durchsatz</h2>
<pre><code class="language-python"># Container mit bereitgestelltem Durchsatz erstellen
container = database.create_container_if_not_exists(
id="mycontainer",
partition_key=PartitionKey(path="/pk"),
offer_throughput=400 # RU/s
)
# Aktuellen Durchsatz auslesen
offer = container.read_offer()
print(f"Durchsatz: {offer.offer_throughput} RU/s")
# Durchsatz aktualisieren
container.replace_throughput(throughput=1000)
</code></pre>
<h2>Asynchroner Client</h2>
<pre><code class="language-python">from azure.cosmos.aio import CosmosClient
from azure.identity.aio import DefaultAzureCredential
async def cosmos_operations():
async with DefaultAzureCredential() as credential:
async with CosmosClient(endpoint, credential=credential) as client:
database = client.get_database_client("mydb")
container = database.get_container_client("mycontainer")
# Erstellen
await container.create_item(body={"id": "1", "pk": "test"})
# Lesen
item = await container.read_item(item="1", partition_key="test")
# Abfrage
async for item in container.query_items(
query="SELECT * FROM c",
partition_key="test"
):
print(item)
import asyncio
asyncio.run(cosmos_operations())
</code></pre>
<h2>Fehlerbehandlung</h2>
<pre><code class="language-python">from azure.cosmos.exceptions import CosmosHttpResponseError
try:
item = container.read_item(item="nonexistent", partition_key="pk")
except CosmosHttpResponseError as e:
if e.status_code == 404:
print("Element nicht gefunden")
elif e.status_code == 429:
print(f"Ratenbegrenzung. Wiederholung nach: {e.headers.get('x-ms-retry-after-ms')} ms")
else:
raise
</code></pre>
<h2>Bewährte Verfahren</h2>
<ol>
<li><strong>Entscheiden Sie sich für „sync“ ODER „async“ und bleiben Sie dabei.</strong> Mischen Sie keine <code>azure.cosmos</code>-Sync-Clients mit <code>azure.cosmos.aio</code>-Async-Clients im selben Aufrufpfad. Wählen Sie pro Modul einen Modus.</li>
<li><strong>Verwenden Sie für Clients und asynchrone Anmeldeinformationen stets Kontextmanager.</strong> Umschließen Sie jeden Client mit <code>with CosmosClient(...) as client:</code> (synchron) oder <code>async with CosmosClient(...) as client:</code> (asynchron). Für asynchrone <code>DefaultAzureCredential</code> aus <code>azure.identity.aio</code> verwenden Sie ebenfalls <code>async with credential:</code>, damit Tokens und Transporte bereinigt werden.</li>
<li><strong>Verwenden Sie <code>DefaultAzureCredential</code></strong> für eine portable Authentifizierung zwischen lokaler Entwicklung und Azure (vermeiden Sie nach Möglichkeit Verbindungszeichenfolgen / API-Schlüssel).</li>
<li><strong>Geben Sie für Punkt-Lesevorgänge und Abfragen immer den Partitionsschlüssel</strong> an.</li>
<li><strong>Verwenden Sie parametrisierte Abfragen</strong>, um Injektionen zu verhindern und das Caching zu verbessern</li>
<li><strong>Vermeiden Sie nach Möglichkeit partitionenübergreifende Abfragen</strong></li>
<li><strong>Verwenden Sie <code>upsert_item</code></strong> für idempotente Schreibvorgänge</li>
<li><strong>Verwenden Sie den asynchronen Client </strong> für Szenarien mit hohem Durchsatz </li>
<li><strong>Entwerfen Sie den Partitionsschlüssel </strong> für eine gleichmäßige Datenverteilung </li>
<li><strong>Verwenden Sie <code>read_item</code></strong> anstelle einer Abfrage zum Abrufen einzelner Dokumente </li>
</ol>
<h2>Referenzdateien</h2>
<table>
<thead>
<tr>
<th>Datei</th>
<th>Inhalt</th>
</tr>
</thead>
<tbody><tr>
<td>references/partitioning.md</td>
<td>Strategien für Partitionsschlüssel, hierarchische Schlüssel, Erkennung und Abmilderung von „Hot Partitions“</td>
</tr>
<tr>
<td>references/query-patterns.md</td>
<td>Abfrageoptimierung, Aggregationen, Paginierung, Transaktionen, Change Feed</td>
</tr>
<tr>
<td>scripts/setup_cosmos_container.py</td>
<td>CLI-Tool zum Erstellen von Containern mit Partitionierung, Durchsatz und Indizierung</td>
</tr>
</tbody></table> ---
name: azure-cosmos-py
description: Perform CRUD operations, run queries, and manage containers on Azure Cosmos DB NoSQL API using the Python SDK.
license: MIT
---
# Azure Cosmos DB SDK for Python
Client library for Azure Cosmos DB NoSQL API — globally distributed, multi-model database.
## Installation
```bash
pip install azure-cosmos azure-identity
```
## Environment Variables
```bash
COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/ # Required for all auth methods
COSMOS_DATABASE=mydb # Required for all auth methods
COSMOS_CONTAINER=mycontainer # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication & Lifecycle
> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
> - Local dev: `DefaultAzureCredential` works as-is.
> - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
> - Sync: `with <Client>(...) as client:`
> - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.
```python
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.cosmos import CosmosClient
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
endpoint = "https://<account>.documents.azure.com:443/"
with CosmosClient(url=endpoint, credential=credential) as client:
# Use client here (see following sections for operations)
...
```
## Client Hierarchy
| Client | Purpose | Get From |
|--------|---------|----------|
| `CosmosClient` | Account-level operations | Direct instantiation |
| `DatabaseProxy` | Database operations | `client.get_database_client()` |
| `ContainerProxy` | Container/item operations | `database.get_container_client()` |
## Core Workflow
### Setup Database and Container
```python
# Get or create database
database = client.create_database_if_not_exists(id="mydb")
# Get or create container with partition key
container = database.create_container_if_not_exists(
id="mycontainer",
partition_key=PartitionKey(path="/category")
)
# Get existing
database = client.get_database_client("mydb")
container = database.get_container_client("mycontainer")
```
### Create Item
```python
item = {
"id": "item-001", # Required: unique within partition
"category": "electronics", # Partition key value
"name": "Laptop",
"price": 999.99,
"tags": ["computer", "portable"]
}
created = container.create_item(body=item)
print(f"Created: {created['id']}")
```
### Read Item
```python
# Read requires id AND partition key
item = container.read_item(
item="item-001",
partition_key="electronics"
)
print(f"Name: {item['name']}")
```
### Update Item (Replace)
```python
item = container.read_item(item="item-001", partition_key="electronics")
item["price"] = 899.99
item["on_sale"] = True
updated = container.replace_item(item=item["id"], body=item)
```
### Upsert Item
```python
# Create if not exists, replace if exists
item = {
"id": "item-002",
"category": "electronics",
"name": "Tablet",
"price": 499.99
}
result = container.upsert_item(body=item)
```
### Delete Item
```python
container.delete_item(
item="item-001",
partition_key="electronics"
)
```
## Queries
### Basic Query
```python
# Query within a partition (efficient)
query = "SELECT * FROM c WHERE c.price < @max_price"
items = container.query_items(
query=query,
parameters=[{"name": "@max_price", "value": 500}],
partition_key="electronics"
)
for item in items:
print(f"{item['name']}: ${item['price']}")
```
### Cross-Partition Query
```python
# Cross-partition (more expensive, use sparingly)
query = "SELECT * FROM c WHERE c.price < @max_price"
items = container.query_items(
query=query,
parameters=[{"name": "@max_price", "value": 500}],
enable_cross_partition_query=True
)
for item in items:
print(item)
```
### Query with Projection
```python
query = "SELECT c.id, c.name, c.price FROM c WHERE c.category = @category"
items = container.query_items(
query=query,
parameters=[{"name": "@category", "value": "electronics"}],
partition_key="electronics"
)
```
### Read All Items
```python
# Read all in a partition
items = container.read_all_items() # Cross-partition
# Or with partition key
items = container.query_items(
query="SELECT * FROM c",
partition_key="electronics"
)
```
## Partition Keys
**Critical**: Always include partition key for efficient operations.
```python
from azure.cosmos import PartitionKey
# Single partition key
container = database.create_container_if_not_exists(
id="orders",
partition_key=PartitionKey(path="/customer_id")
)
# Hierarchical partition key (preview)
container = database.create_container_if_not_exists(
id="events",
partition_key=PartitionKey(path=["/tenant_id", "/user_id"])
)
```
## Throughput
```python
# Create container with provisioned throughput
container = database.create_container_if_not_exists(
id="mycontainer",
partition_key=PartitionKey(path="/pk"),
offer_throughput=400 # RU/s
)
# Read current throughput
offer = container.read_offer()
print(f"Throughput: {offer.offer_throughput} RU/s")
# Update throughput
container.replace_throughput(throughput=1000)
```
## Async Client
```python
from azure.cosmos.aio import CosmosClient
from azure.identity.aio import DefaultAzureCredential
async def cosmos_operations():
async with DefaultAzureCredential() as credential:
async with CosmosClient(endpoint, credential=credential) as client:
database = client.get_database_client("mydb")
container = database.get_container_client("mycontainer")
# Create
await container.create_item(body={"id": "1", "pk": "test"})
# Read
item = await container.read_item(item="1", partition_key="test")
# Query
async for item in container.query_items(
query="SELECT * FROM c",
partition_key="test"
):
print(item)
import asyncio
asyncio.run(cosmos_operations())
```
## Error Handling
```python
from azure.cosmos.exceptions import CosmosHttpResponseError
try:
item = container.read_item(item="nonexistent", partition_key="pk")
except CosmosHttpResponseError as e:
if e.status_code == 404:
print("Item not found")
elif e.status_code == 429:
print(f"Rate limited. Retry after: {e.headers.get('x-ms-retry-after-ms')}ms")
else:
raise
```
## Best Practices
1. **Pick sync OR async and stay consistent.** Do not mix `azure.cosmos` sync clients with `azure.cosmos.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with CosmosClient(...) as client:` (sync) or `async with CosmosClient(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use `DefaultAzureCredential`** for portable auth across local dev and Azure (avoid connection strings / API keys when possible).
4. **Always specify partition key** for point reads and queries
5. **Use parameterized queries** to prevent injection and improve caching
6. **Avoid cross-partition queries** when possible
7. **Use `upsert_item`** for idempotent writes
8. **Use async client** for high-throughput scenarios
9. **Design partition key** for even data distribution
10. **Use `read_item`** instead of query for single document retrieval
## Reference Files
| File | Contents |
|------|----------|
| [references/partitioning.md](references/partitioning.md) | Partition key strategies, hierarchical keys, hot partition detection and mitigation |
| [references/query-patterns.md](references/query-patterns.md) | Query optimization, aggregations, pagination, transactions, change feed |
| [scripts/setup_cosmos_container.py](scripts/setup_cosmos_container.py) | CLI tool for creating containers with partitioning, throughput, and indexing |
Alle Dateien
0 Dateienazure-cosmos-py installieren
Laden Sie die Skill-Dateien herunter und entpacken Sie sie in Ihr Verzeichnis „.claude/skills/“.
ZIP herunterladenKlonen Sie das Repository und kopieren Sie die Skill-Dateien in Ihr Projekt.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-cosmos-py # Copy SKILL.md to your .claude/skills/ directory
Kopieren





Heim
