快速入门:将 Azure Cosmos DB 与 Azure SDK for Rust 配合使用

在本快速入门中,你将使用 Azure SDK for Rust 将 Rust 应用程序连接到 Azure Cosmos DB。 在现有容器中创建、读取和查询项。

本快速入门使用已正式发布的 Azure Cosmos DB SDK for Rust 版本 1.0.0。

Important

Azure Cosmos DB SDK for Rust 中的 OpenTelemetry 支持(unstable_opentelemetry)和修补操作(unstable_patch)保持预览状态,不建议用于生产工作负荷。 这些预览功能独立于正式版 SDK,在本快速入门中不使用。

API 参考文档 | 库源代码 | Crate(Rust) | Azure开发人员 CLI

Prerequisites

如果没有 Azure 帐户,请在开始前创建一个免费帐户。

Tip

代理工具包可帮助编码代理使用建议的最佳做法快速高效地与Azure Cosmos DB配合使用。 若要开始,请运行:

npx skills add AzureCosmosDB/cosmosdb-agent-kit

若要了解详细信息,请参阅Azure Cosmos DB代理工具包。

安装客户端库

可以将客户端库作为 azure_data_cosmos crate 获取。 以下命令使用最新的稳定版 Azure Cosmos DB 和 Azure Identity 发布版本 1.0.0。

  1. 创建 Rust 应用程序并打开其目录。

    cargo new cosmos-quickstart
    cd cosmos-quickstart
    
  2. 使用 azure_data_cosmos 添加版本为 1.0.0 的 cargo add crate。

    cargo add azure_data_cosmos@1.0.0
    
  3. 添加 azure_identity crate 的 1.0.0 版本。

    cargo add azure_identity@1.0.0
    
  4. 添加 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托管的生产应用程序,请使用托管标识而不是开发人员凭据。

获取数据库

使用获取名为的现有数据库的客户端。

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 扩展来浏览 Azure Cosmos DB for NoSQL 数据。

后续步骤