Rust 版 Azure Cosmos DB 数据库操作
azure-cosmos-rust
面向 Rust 的 Azure Cosmos DB 库(NoSQL API)。涵盖文档增删改查(CRUD)、容器以及全球分布式数据。 触发词:「cosmos db rust」「CosmosClient rust」「document crud rust」「NoSQL rust」「partition key rust」。
- License 许可
- MIT
- 所属仓库
- microsoft/skills
- 最近更新
- 2026-11-14
- Stars
- ★ 3.2k
- Forks
- 368
01 前言 Front Matter
- name
- azure-cosmos-rust
- license
- MIT
- metadata
- { "author": "Microsoft", "package": "azure_data_cosmos" }
- description
- Azure Cosmos DB library for Rust (NoSQL API). Document CRUD, containers, and globally distributed data. Triggers: "cosmos db rust", "CosmosClient rust", "document crud rust", "NoSQL rust", "partition key rust".
02 资源文件 1
- 参考文档references/validation.md5.6 KB
03 SKILL.md 正文
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_cosmoscrate published by the azure-sdk crates.io user. Do NOT use the unofficialazure_cosmosorazure_sdk_for_rustcommunity crates. Official crates use underscores in names and none have version 0.21.0.
Installation
cargo add azure_data_cosmos azure_identity serde serde_json tokio
If your code uses
azure_coretypes directly (for example,azure_core::credentials::TokenCredential), addazure_coretoCargo.toml. If you only useazure_data_cosmosre-exports, directazure_coredependency is optional.
Environment Variables
COSMOS_ENDPOINT=https://<account>.documents.azure.com/ # Required for all operations
Authentication
Rust Azure SDK code must not use DefaultAzureCredential. The Rust identity crate does not provide that type.
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(())
}
Prefer the crate README/examples when checking builder signatures and CRUD method shapes instead of reconstructing APIs from memory or generated internals.
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
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
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:
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
- Use
cargo addto manage dependencies, never editCargo.tomldirectly. Add and remove Rust SDK dependencies with cargo commands instead of manual manifest edits. - Add
azure_coreonly when importingazure_coretypes directly. If your code importsazure_core::http::Url,azure_core::http::RequestContent, orazure_core::error::ErrorKind, includeazure_core; otherwise a direct dependency is optional. - Use
DeveloperToolsCredentialfor local dev,ManagedIdentityCredentialfor production — Rust does not provide a singleDefaultAzureCredentialtype - Never hardcode credentials — use environment variables or managed identity
- Reuse
CosmosClient— clients are thread-safe; create once, share across tasks - Use
RoutingStrategy::ProximityTo— route to the nearest region for lowest latency - Always specify partition key for item operations — Cosmos DB requires it for all CRUD
- Run
cargo clippy -- -D warningswhen the prompt, eval, or CI expects lint-clean output - Future-proof
#[non_exhaustive]SDK models — when constructing SDK model/options structs, end the initializer with..Default::default()(add#[allow(clippy::needless_update)]) and use a_wildcard arm when matching SDK enums, so new service-added fields/variants don't break your build
Reference Links
04 同仓库更多 Skills
azure-advisor-cost-optimization
Analyze Azure Advisor Cost/IdleResources findings and prevalidate deletion safety, including Service Groups. WHEN: "find unused Azure resources", "what resources am I paying for but no longer using", "idle-resource savings", "historical idle-resource savings", "are these idle resources safe to delete". Generic Cost, other subcategories, and cross-category requests use azure-advisor.
Azure 技能创建与更新指南
skill-creator
面向使用 Azure SDK 和 Microsoft Foundry 服务的 AI 编码智能体,指导其创建高效技能的指南。在创建新技能或更新现有技能时使用。
AI 播客音频生成
podcast-generation
通过 WebSocket 使用 Azure OpenAI 的 GPT Realtime Mini 模型生成 AI 驱动的播客式音频叙述。当构建文本转语音功能、音频叙述生成、根据内容制作播客,或集成 Azure OpenAI Realtime API 以获得真实音频输出时使用。涵盖从 React 前端到 Python FastAPI 后端及 WebSocket 流式传输的全栈实现。
Microsoft 技术文档查询
microsoft-docs
通过查询官方文档来理解 Microsoft 技术。当用户询问某项技术的工作原理、想要教程、需要任何 Microsoft 技术(Azure、.NET、M365、Windows、Power Platform 等)的配置选项、限制、配额或最佳实践时使用——即使他们没有提到"文档"。如果问题是为了理解概念而非编写代码,那么这就是合适的技能。
MCP 服务器构建
mcp-builder
用于创建高质量 MCP(Model Context Protocol)服务器的指南,使大语言模型能够通过设计完善的工具与外部服务交互。当构建用于集成外部 API 或服务的 MCP 服务器时使用,无论采用 Python(FastMCP)、Node/TypeScript(MCP SDK),还是 C#/.NET(Microsoft MCP SDK)。
KQL 查询编写与调试
kql
KQL 语言专业能力,用于编写正确且高效的 Kusto Query Language 查询。涵盖语法陷阱、join 模式、dynamic 类型、datetime 陷阱、regex 模式、序列化、内存管理、结果集规模控制,以及高级函数(geo、vector、graph)。在编写、调试或审查 KQL 查询时均使用本技能——即使是简单查询——因为陷阱章节可防止最常见的错误,避免浪费工具调用并引发代价高昂的连锁重试。触发条件:KQL、Kusto、ADX、Azure Data Explorer、Fabric Real-Time Intelligence、EventHouse、Log Analytics、日志分析、数据探索、时间序列、异常检测、summarize、where 子句、join、extend、project、let 语句、parse 运算符、extract 函数,以及任何提及管道式查询语法的情形。