选项
首页首页 Skill 开发者工具 azure-cosmos-rust

azure-cosmos-rust

microsoft/skills microsoft/skills

提供基于 Rust 的 Azure Cosmos DB NoSQL API 的 CRUD 操作,包括文档管理、容器操作以及全球分布式数据访问。

...展开全部
8
更新时间 2026-09-12

适用于 Rust 的 Azure Cosmos DB 库

Azure Cosmos DB NoSQL API 的客户端库 — 文档 CRUD、容器以及全球分布式数据。

在以下情况下使用此技能:

  • 应用程序需要从 Rust 语言向 Cosmos DB 存储或查询文档
  • 您需要对具有分区键的项目执行 CRUD 操作
  • 需要基于密钥的身份验证作为 Entra ID 的替代方案

重要提示:请仅使用由 crates.io 用户 azure-sdk 发布的官方azure_data_cosmos库。 请勿使用非官方的azure_cosmosazure_sdk_for_rust社区库。官方库的名称中使用下划线,且均不存在 0.21.0 版本。

安装

cargo add azure_data_cosmos azure_identity serde serde_json tokio

如果您的代码直接使用azure_core类型(例如azure_core::credentials::TokenCredential),请在Cargo.toml 中添加azure_core。如果您仅使用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(())
}

客户端层次结构

客户端 用途 访问
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 内置数据贡献者 读写

最佳实践

  1. 请使用`cargo add`管理依赖项,切勿直接编辑`Cargo.toml`。请通过 `cargo` 命令添加和移除 Rust SDK 依赖项,而非手动编辑清单文件。
  2. 仅在直接导入azure_core类型时才添加azure_core如果您的代码导入了azure_core::http::Urlazure_core::http::RequestContentazure_core::error::ErrorKind,请包含azure_core;否则,直接依赖是可选的。
  3. 本地开发请使用DeveloperToolsCredential,生产环境请使用 ManagedIdentityCredential—— Rust 并未提供单一的DefaultAzureCredential类型
  4. 切勿硬编码凭据——请使用环境变量或托管身份
  5. 复用CosmosClient— 客户端是线程安全的;只需创建一次,即可在各个任务间共享
  6. 使用RoutingStrategy::ProximityTo— 路由至最近的区域以实现最低延迟
  7. 对项操作始终指定分区键— 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
在 GitHub 上查看
---
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

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ Claude 会自动检测并使用该技能

相关技能

algorithmic-art
更新时间 2026-08-27
receiving-code-review
更新时间 2026-09-03
tech-debt-tracker
更新时间 2026-08-29
deprecation-and-migration
更新时间 2026-09-03
OR