azure-cosmos-rust
microsoft/skills
提供透過 Rust 對 Azure Cosmos DB NoSQL API 進行 CRUD 操作的功能,包括文件管理、容器操作以及全球分散式資料存取。
...展開全部適用於 Rust 的 Azure Cosmos DB 函式庫
Azure Cosmos DB NoSQL API 的客戶端函式庫 — 文件 CRUD、容器及全球分散式資料。
在以下情況下使用此函式庫:
- 應用程式需要從 Rust 儲存或查詢 Cosmos DB 中的文件
- 您需要對具有分區金鑰的項目執行 CRUD 操作
- 您需要以金鑰為基礎的驗證機制,作為 Entra ID 的替代方案
重要:請僅使用由 crates.io 使用者 azure-sdk 發佈的官方
azure_data_cosmos套件。 請勿使用非官方的azure_cosmos或azure_sdk_for_rust社群套件。官方套件的名稱中會使用底線,且均無 0.21.0 版本。
安裝
cargo add azure_data_cosmos azure_identity serde serde_json tokio
若您的程式碼直接使用
azure_core類型(例如azure_core::credentials::TokenCredential),請將azure_core加入Cargo.toml。若您僅使用azure_data_cosmos的重新導出功能,則直接依賴azure_core屬可選操作。
環境變數
COSMOS_ENDPOINT=https://.documents.azure.com/ # 所有操作皆需此設定
身份驗證
use azure_identity::DeveloperToolsCredential;
use azure_data_cosmos::{
CosmosClient, AccountReference, AccountEndpoint, RoutingStrategy,
};
#[tokio::main]
async fn main() -> Result<(), Box> {
// 本地開發環境:DeveloperToolsCredential。生產環境:請使用 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 | 用途 | 存取 |
|---|---|---|
CosmosClient |
帳戶層級操作 | CosmosClient::builder().build(account).await? |
DatabaseClient |
資料庫操作 | client.database_client("db") |
ContainerClient |
容器/項目操作 | database.container_client("c").await |
核心工作流程
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(),
};
// 建立
container.create_item("pk1", "1", item, None).await?;
// 讀取
let resp = container.read_item("pk1", "1", None).await?;
let mut item: Item = resp.into_model()?;
// 更新
item.value = "updated".into();
container.replace_item("pk1", "1", item, None).await?;
// 刪除
container.delete_item("pk1", "1", None).await?;
Ok(())
}
修訂項目
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);
金鑰驗證(可選)
透過功能標誌啟用帳戶金鑰驗證:
cargo add azure_data_cosmos --features key_auth
RBAC 角色
若使用 Entra ID 驗證,請指派以下其中一個 Cosmos DB 內建角色:
| 角色 | 存取權限 |
|---|---|
Cosmos DB 內建資料讀取者 |
唯讀 |
Cosmos DB 內建資料貢獻者 |
讀寫 |
最佳實務
- 請使用
`cargo add`來管理依賴項,切勿直接編輯`Cargo.toml`。請透過 `cargo` 指令新增或移除 Rust SDK 依賴項,而非手動編輯清單檔案。 - 僅在直接導入
azure_core類型時才需加入azure_core。若您的程式碼導入了azure_core::http::Url、azure_core::http::RequestContent或azure_core::error::ErrorKind,請包含azure_core;否則,直接依賴項為可選。 - 本地開發時使用
`DeveloperToolsCredential`,生產環境則使用`ManagedIdentityCredential`—— Rust 並未提供單一的`DefaultAzureCredential`類型 - 切勿將憑證硬編碼— 請使用環境變數或受管身分識別
- 重複使用
CosmosClient— 客戶端是執行緒安全的;只需建立一次,即可在各任務間共用 - 使用`
RoutingStrategy::ProximityTo` — 路由至最近的區域以獲得最低延遲 - 執行項目操作時務必指定分區金鑰— Cosmos DB 要求所有 CRUD 操作皆須提供此參數
參考連結
| 資源 | 連結 |
|---|---|
| API 參考 | https://docs.rs/azure_data_cosmos/latest/azure_data_cosmos |
| crates.io | https://crates.io/crates/azure_data_cosmos |
| 原始碼 | https://github.com/Azure/azure-sdk-for-rust/tree/main/sdk/cosmos/azure_data_cosmos |
---
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 |
所有檔案
0 個檔案安裝 azure-cosmos-rust
請下載並將技能檔案解壓縮至您的 .claude/skills/ 目錄中。
下載 ZIP複製儲存庫並將技能檔案複製到您的專案中。
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
複製





首頁
