Option
HeimHeim Skill Entwicklertools azure-cosmos-rust

azure-cosmos-rust

microsoft/skills microsoft/skills

Bietet CRUD-Operationen für die Azure Cosmos DB NoSQL-API aus Rust, einschließlich Dokumentenverwaltung, Containeroperationen und global verteiltem Datenzugriff.

...Alle erweitern
8
Zeit aktualisiert 12. September 2026

Azure Cosmos DB-Bibliothek für Rust

Client-Bibliothek für die Azure Cosmos DB NoSQL-API – CRUD-Operationen für Dokumente, Container und global verteilte Daten.

Verwenden Sie diese Funktion, wenn:

  • Eine App muss Dokumente in Cosmos DB aus Rust heraus speichern oder abfragen
  • Sie CRUD-Operationen für Elemente mit Partitionsschlüsseln benötigen
  • Sie benötigen eine schlüsselbasierte Authentifizierung als Alternative zu Entra ID

WICHTIG: Verwenden Sie ausschließlich das offizielle „azure_data_cosmos“- Crate, das vom crates.io-Benutzer „azure-sdk“ veröffentlicht wurde. Verwenden Sie NICHT die inoffiziellen Community-Crates „azure_cosmos “ oder „azure_sdk_for_rust “. Offizielle Crates verwenden Unterstriche in ihren Namen, und keine davon hat die Version 0.21.0.

Installation

cargo add azure_data_cosmos azure_identity serde serde_json tokio

Wenn Ihr Code azure_core-Typen direkt verwendet (z. B. azure_core::credentials::TokenCredential), fügen Sie azure_core zu Cargo.toml hinzu. Wenn Sie nur Re-Exporte von azure_data_cosmos verwenden, ist eine direkte Abhängigkeit von azure_core optional.

Umgebungsvariablen

COSMOS_ENDPOINT=https://.documents.azure.com/ # Für alle Vorgänge erforderlich

Authentifizierung

use azure_identity::DeveloperToolsCredential;
use azure_data_cosmos::{
    CosmosClient, AccountReference, AccountEndpoint, RoutingStrategy,
};

#[tokio::main]
async fn main() -> Result<(), Box> {
    // Lokale Entwicklung: DeveloperToolsCredential. Produktion: Verwenden Sie ManagedIdentityCredential.
    let credential = DeveloperToolsCredential::new(None)?;
    let endpoint: AccountEndpoint = "https://.documents.azure.com/"
        .parse()?;
    let account = AccountReference::with_credential(endpoint, credential);
    let client = CosmosClient::builder()
        .build(account, RoutingStrategy::ProximityTo("East US".into()))
        .await?;
    Ok(())
}

Client-Hierarchie

Client Zweck Zugriff
CosmosClient Vorgänge auf Kontoebene CosmosClient::builder().build(account).await?
DatabaseClient Datenbankoperationen client.database_client("db")
ContainerClient Container-/Elementoperationen database.container_client("c").await

Kern-Workflow

use serde::{Serialize, Deserialize};
use azure_data_cosmos::CosmosClient;

#[derive(Serialize, Deserialize)]
struct Item {
    pub id: String,
    pub partition_key: String,
    pub value: String,
}

async fn crud(client: CosmosClient) -> Result<(), Box> {
    let container = client
        .database_client("myDatabase")
        .container_client("myContainer")
        .await;

    let item = Item {
        id: "1".into(),
        partition_key: "pk1".into(),
        value: "hello".into(),
    };

    // Anlegen
    container.create_item("pk1", "1", item, None).await?;

    // Lesen
    let resp = container.read_item("pk1", "1", None).await?;
    let mut item: Item = resp.into_model()?;

    // Aktualisieren
    item.value = "updated".into();
    container.replace_item("pk1", "1", item, None).await?;

    // Löschen
    container.delete_item("pk1", "1", None).await?;
    Ok(())
}

Element ändern

use azure_data_cosmos::{PatchInstructions, PatchOperation};

let patch = PatchInstructions::from(vec![
    PatchOperation::set("/value", serde_json::json!("patched")),
]);
let patched: Item = container
    .patch_item("pk1", "1", patch, None)
    .await?
    .into_model()?;
println!("Geänderter Wert: {}", patched.value);

Schlüsselauthentifizierung (optional)

Aktivieren Sie die Authentifizierung per Kontoschlüssel mit dem Feature-Flag:

cargo add azure_data_cosmos --features key_auth

RBAC-Rollen

Weisen Sie für die Entra-ID-Authentifizierung eine der folgenden integrierten Cosmos DB-Rollen zu:

Rolle Zugriff
Cosmos DB – Integrierter Datenleser Nur-Lesezugriff
Cosmos DB – Integrierter Daten-Beitragender Lese-/Schreibzugriff

Bewährte Vorgehensweisen

  1. Verwenden Sie „cargo add“, um Abhängigkeiten zu verwalten, und bearbeiten Sie die Datei „Cargo.toml“ niemals direkt. Fügen Sie Rust-SDK-Abhängigkeiten mit „cargo“-Befehlen hinzu und entfernen Sie sie, anstatt das Manifest manuell zu bearbeiten.
  2. Fügen Sie „azure_core“ nur hinzu, wenn Sie Typen aus „azure_core“ direkt importieren. Wenn Ihr Code „azure_core::http::Url“, „azure_core::http::RequestContent“ oder „azure_core::error::ErrorKind“ importiert, fügen Sie „azure_core“ ein; andernfalls ist eine direkte Abhängigkeit optional.
  3. Verwenden Sie „DeveloperToolsCredential“ für die lokale Entwicklung und „ManagedIdentityCredential“ für die Produktion – Rust bietet keinen einheitlichen „DefaultAzureCredential“-Typ an
  4. Harden Sie Anmeldedaten niemals fest ein – verwenden Sie Umgebungsvariablen oder verwaltete Identitäten
  5. Verwenden Sie „CosmosClient“ wieder – Clients sind threadsicher; einmal erstellen und zwischen Aufgaben gemeinsam nutzen
  6. Verwenden Sie ` RoutingStrategy::ProximityTo ` – leiten Sie den Datenverkehr zur nächstgelegenen Region weiter, um die geringste Latenz zu erzielen
  7. Geben Sie bei Item-Operationenimmer den Partitionsschlüssel an – Cosmos DB verlangt dies für alle CRUD-Vorgänge

Weiterführende Links

Ressource Link
API-Referenz https://docs.rs/azure_data_cosmos/latest/azure_data_cosmos
crates.io https://crates.io/crates/azure_data_cosmos
Quellcode https://github.com/Azure/azure-sdk-for-rust/tree/main/sdk/cosmos/azure_data_cosmos
Auf GitHub ansehen
---
name: azure-cosmos-rust
description: Provides CRUD operations for Azure Cosmos DB NoSQL API from Rust, including document management, container operations, and globally distributed data access.
license: MIT
---

# Azure Cosmos DB library for Rust

Client library for Azure Cosmos DB NoSQL API — document CRUD, containers, and globally distributed data.

Use this skill when:

- An app needs to store or query documents in Cosmos DB from Rust
- You need CRUD operations on items with partition keys
- You need key-based auth as an alternative to Entra ID

> **IMPORTANT:** Only use the official `azure_data_cosmos` crate published by the [azure-sdk](https://crates.io/users/azure-sdk) crates.io user. Do NOT use the unofficial `azure_cosmos` or `azure_sdk_for_rust` community crates. Official crates use underscores in names and none have version 0.21.0.

## Installation

```sh
cargo add azure_data_cosmos azure_identity serde serde_json tokio
```

> If your code uses `azure_core` types directly (for example, `azure_core::credentials::TokenCredential`), add `azure_core` to `Cargo.toml`. If you only use `azure_data_cosmos` re-exports, direct `azure_core` dependency is optional.

## Environment Variables

```bash
COSMOS_ENDPOINT=https://<account>.documents.azure.com/ # Required for all operations
```

## Authentication

```rust
use azure_identity::DeveloperToolsCredential;
use azure_data_cosmos::{
    CosmosClient, AccountReference, AccountEndpoint, RoutingStrategy,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Local dev: DeveloperToolsCredential. Production: use ManagedIdentityCredential.
    let credential = DeveloperToolsCredential::new(None)?;
    let endpoint: AccountEndpoint = "https://<account>.documents.azure.com/"
        .parse()?;
    let account = AccountReference::with_credential(endpoint, credential);
    let client = CosmosClient::builder()
        .build(account, RoutingStrategy::ProximityTo("East US".into()))
        .await?;
    Ok(())
}
```

## Client Hierarchy

| Client            | Purpose                   | Access                                  |
| ----------------- | ------------------------- | --------------------------------------- |
| `CosmosClient`    | Account-level operations  | `CosmosClient::builder().build(account).await?` |
| `DatabaseClient`  | Database operations       | `client.database_client("db")`          |
| `ContainerClient` | Container/item operations | `database.container_client("c").await` |

## Core Workflow

```rust
use serde::{Serialize, Deserialize};
use azure_data_cosmos::CosmosClient;

#[derive(Serialize, Deserialize)]
struct Item {
    pub id: String,
    pub partition_key: String,
    pub value: String,
}

async fn crud(client: CosmosClient) -> Result<(), Box<dyn std::error::Error>> {
    let container = client
        .database_client("myDatabase")
        .container_client("myContainer")
        .await;

    let item = Item {
        id: "1".into(),
        partition_key: "pk1".into(),
        value: "hello".into(),
    };

    // Create
    container.create_item("pk1", "1", item, None).await?;

    // Read
    let resp = container.read_item("pk1", "1", None).await?;
    let mut item: Item = resp.into_model()?;

    // Update
    item.value = "updated".into();
    container.replace_item("pk1", "1", item, None).await?;

    // Delete
    container.delete_item("pk1", "1", None).await?;
    Ok(())
}
```

### Patch Item

```rust
use azure_data_cosmos::{PatchInstructions, PatchOperation};

let patch = PatchInstructions::from(vec![
    PatchOperation::set("/value", serde_json::json!("patched")),
]);
let patched: Item = container
    .patch_item("pk1", "1", patch, None)
    .await?
    .into_model()?;
println!("Patched value: {}", patched.value);
```

## Key Auth (Optional)

Enable account key authentication with the feature flag:

```sh
cargo add azure_data_cosmos --features key_auth
```

## RBAC Roles

For Entra ID auth, assign one of these built-in Cosmos DB roles:

| Role                                  | Access     |
| ------------------------------------- | ---------- |
| `Cosmos DB Built-in Data Reader`      | Read-only  |
| `Cosmos DB Built-in Data Contributor` | Read/write |

## Best Practices

1. **Use `cargo add` to manage dependencies, never edit `Cargo.toml` directly.** Add and remove Rust SDK dependencies with cargo commands instead of manual manifest edits.
2. **Add `azure_core` only when importing `azure_core` types directly.** If your code imports `azure_core::http::Url`, `azure_core::http::RequestContent`, or `azure_core::error::ErrorKind`, include `azure_core`; otherwise a direct dependency is optional.
3. **Use `DeveloperToolsCredential`** for local dev, **`ManagedIdentityCredential`** for production — Rust does not provide a single `DefaultAzureCredential` type
4. **Never hardcode credentials** — use environment variables or managed identity
5. **Reuse `CosmosClient`** — clients are thread-safe; create once, share across tasks
6. **Use `RoutingStrategy::ProximityTo`** — route to the nearest region for lowest latency
7. **Always specify partition key** for item operations — Cosmos DB requires it for all CRUD

## Reference Links

| Resource      | Link                                                                               |
| ------------- | ---------------------------------------------------------------------------------- |
| API Reference | https://docs.rs/azure_data_cosmos/latest/azure_data_cosmos                         |
| crates.io     | https://crates.io/crates/azure_data_cosmos                                         |
| Source Code   | https://github.com/Azure/azure-sdk-for-rust/tree/main/sdk/cosmos/azure_data_cosmos |

Alle Dateien

0 Dateien

azure-cosmos-rust installieren

Laden Sie die Skill-Dateien herunter und entpacken Sie sie in Ihr Verzeichnis „.claude/skills/“.

ZIP herunterladen

Klonen 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-rust/skills/azure-cosmos-rust # Copy SKILL.md to your .claude/skills/ directory

Kopieren Kopieren
Schnelle Einrichtung: Kopiere den Skill-Ordner nach .claude/skills/ Claude erkennt den Skill automatisch und nutzt ihn.
Repository microsoft/skills

Ähnliche Skills

algorithmic-art
Zeit aktualisiert 27. August 2026
receiving-code-review
Zeit aktualisiert 3. September 2026
tech-debt-tracker
Zeit aktualisiert 29. August 2026
deprecation-and-migration
Zeit aktualisiert 3. September 2026
OR