オプション
家 Skill 開発者ツール azure-cosmos-rust

azure-cosmos-rust

microsoft/skills microsoft/skills

Rust から Azure Cosmos DB NoSQL API に対する CRUD 操作(ドキュメント管理、コンテナ操作、グローバルに分散されたデータへのアクセスなど)を提供します。

...すべて拡張します
8
更新された時間 2026年9月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.tomlazure_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 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 を直接編集しないでください。Rust SDK の依存関係の追加や削除は、マニフェストを手動で編集するのではなく、cargo コマンドで行ってください。
  2. azure_core をインポートするのは、azure_coreの型を直接インポートする場合に限ってください。コードでazure_core::http::Urlazure_core::http::RequestContent、またはazure_core::error::ErrorKind をインポートする場合は、azure_core をインクルードしてください。それ以外の場合は、直接の依存関係は任意です。
  3. ローカル開発には `DeveloperToolsCredential` を、本番環境には`ManagedIdentityCredential`を使用してください。Rust には単一の`DefaultAzureCredential`型は提供されていません
  4. 認証情報を決してハードコードしないでください。環境変数またはマネージド ID を使用してください
  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 が自動的にそのスキルを検出して使用します。
リポジトリ microsoft/skills

関連スキル

algorithmic-art
更新された時間 2026年8月27日
receiving-code-review
更新された時間 2026年9月3日
tech-debt-tracker
更新された時間 2026年8月29日
deprecation-and-migration
更新された時間 2026年9月3日
OR