在這個快速入門中,你使用 Azure SDK for Rust 將 Rust 應用程式連接到 Azure Cosmos DB。 在現有容器中建立、讀取及查詢項目。
此快速入門使用了 Rust 的正式發行版 Azure Cosmos DB SDK 1.0.0 版本。
Important
Azure Cosmos DB SDK for Rust 中的 OpenTelemetry 支援(unstable_opentelemetry)與修補操作(unstable_patch)仍處於預覽階段,不建議用於正式工作負載。 這些預覽功能與一般可用的 SDK 是分開的,且不會在本快速入門中使用。
API 參考文件 | 函式庫原始碼 | 箱子(Rust) | Azure Developer CLI
Prerequisites
- Rust 1.88 或更新版本。
- 一個 Azure Cosmos DB 帳戶,擁有一個名為
cosmicworks的資料庫,以及一個容器products,其分割鍵為/category。 - 具有 Cosmos DB 內建資料貢獻者角色的身分,且作用範圍僅限於帳戶或
products容器。 - 已使用該身分登入的 Azure CLI 或 Azure Developer CLI。
如果您沒有 Azure 帳戶,請在開始之前建立 免費帳戶 。
Tip
Agent Kit 協助程式設計代理程式依據建議的最佳實務,快速且有效地使用 Azure Cosmos DB。 開始時,請執行:
npx skills add AzureCosmosDB/cosmosdb-agent-kit
欲了解更多,請參閱 Azure Cosmos DB Agent Kit。
安裝用戶端程式庫
你可以取得作為 azure_data_cosmos crate 的客戶端程式庫。 以下指令使用最新的穩定版 Azure Cosmos DB 與 Azure Identity 版本,版本為 1.0.0。
建立一個 Rust 應用程式並開啟其目錄。
cargo new cosmos-quickstart cd cosmos-quickstart使用
azure_data_cosmos新增cargo addcrate 的 1.0.0 版本cargo add azure_data_cosmos@1.0.0新增
azure_identitycrate 的 1.0.0 版本。cargo add azure_identity@1.0.0新增 JSON 序列化、非同步執行與查詢迭代的相依關係。
cargo add serde --features derive cargo add tokio --features macros,rt-multi-thread cargo add futures
匯入程式庫
將這些匯入新增至 src/main.rs。
use azure_data_cosmos::{AccountReference, CosmosClient, FeedScope, PartitionKey, Query, RoutingStrategy};
use azure_identity::DeveloperToolsCredential;
use futures::TryStreamExt;
物件模型
| Name | Description |
|---|---|
CosmosClient |
用於連接帳戶並取得資料庫用戶端的主要用戶端。 |
DatabaseClient |
帳戶內資料庫的用戶端。 |
ContainerClient |
一個容器及其項目的用戶端。 |
程式碼範例
範例使用現有的 cosmicworks 資料庫和 products 容器。 容器使用 /category 作為其分割鍵。 將建立範例中的 Item 類型放在匯入後。 將產生的 main 函式替換為以下非同步入口點,然後依序在 Ok(()) 前加入驗證、資料庫、容器、upsert、讀取及查詢片段。
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
驗證用戶端
使用 DeveloperToolsCredential 透過已登入的開發人員工具進行驗證。 將環境變數設定AZURE_COSMOS_ENDPOINT為您的帳戶端點 URL,該網址可於其 Azure 入口網站概覽頁面取得。 設AZURE_COSMOS_REGION為離您的應用程式最近的 Azure 區域,例如 East US。
let credential = DeveloperToolsCredential::new(None)?;
let endpoint = std::env::var("AZURE_COSMOS_ENDPOINT")?.parse()?;
let region = std::env::var("AZURE_COSMOS_REGION")?;
let account = AccountReference::with_credential(endpoint, credential);
let client = CosmosClient::builder()
.build(account, RoutingStrategy::ProximityTo(region.into()))
.await?;
在後續操作中重複使用該用戶端。 對於 Azure 託管的生產應用程式,請使用受控識別而非開發人員憑證。
取得資料庫
使用 client.database_client 取得名為 cosmicworks 的現有資料庫用戶端。
let database = client.database_client("cosmicworks");
找一個容器
使用 products 取得現有 database.container_client 容器的用戶端。
let container = database.container_client("products", None).await?;
建立項目
使用您想要串行化為 JSON 的所有成員,建置新的類型。 在此範例中,此類型具有唯一識別碼,以及類別、名稱、數量、價格和銷售的欄位。 在此類型上導出serde::Serialize特性,使其可以序列化為 JSON。
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Item {
pub id: String,
pub category: String,
pub name: String,
pub quantity: i32,
pub price: f64,
pub clearance: bool,
}
使用 container.upsert_item 在容器中建立一個項目。 此方法會有效地「更新插入」資料,如果該資料已存在,則會取代原資料。
let item = Item {
id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb".to_string(),
category: "gear-surf-surfboards".to_string(),
name: "Yamba Surfboard".to_string(),
quantity: 12,
price: 850.00,
clearance: false,
};
let partition_key = PartitionKey::from(item.category.clone());
container.upsert_item(partition_key, &item.id, &item, None).await?;
讀取項目
使用唯一識別碼 (id) 和分割區索引鍵欄位,來執行點讀取作業。 使用 container.read_item 有效率地擷取特定項目。
let item_id = "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb";
let item_partition_key = "gear-surf-surfboards";
let response = container.read_item(item_partition_key, item_id, None).await?;
let item: Item = response.into_model()?;
println!("Read item: {} ({})", item.name, item.id);
查詢項目
使用 container.query_items,以對容器中的多個項目執行查詢。 使用此參數化查詢,來尋找所指定類別內的所有項目:
SELECT * FROM c WHERE c.category = @category
let item_partition_key = "gear-surf-surfboards";
let query = Query::from("SELECT * FROM c WHERE c.category = @category")
.with_parameter("@category", item_partition_key)?;
let mut items = container
.query_items::<Item>(query, FeedScope::partition(item_partition_key), None)
.await?;
while let Some(item) = items.try_next().await? {
println!("Query result: {} ({})", item.name, item.id);
}
在新增片段並設定環境變數後執行應用程式。
cargo run
探索您的資料
使用適用於 Azure Cosmos DB 的 Visual Studio Code 擴充功能來探索您的 NoSQL 數據。 您可以執行核心資料庫作業,包括但不限於:
- 使用剪貼簿或查詢編輯器執行查詢
- 修改、更新、建立和刪除項目
- 從其他來源匯入大量數據
- 管理資料庫和容器
如需詳細資訊,請參閱 如何使用 Visual Studio Code 擴充功能來探索適用於 NoSQL 數據的 Azure Cosmos DB。