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)을 직접 사용하는 경우,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 기본 제공 데이터 기여자 |
읽기/쓰기 |
모범 사례
- 의존성을 관리할 때는 `
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타입을 제공하지 않습니다. - 절대 자격 증명을 하드코딩하지 마십시오. 환경 변수나 관리형 ID를 사용하십시오.
-
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
복사





집
