Quickstart: Use Azure Cosmos DB with Azure SDK for Rust

In this quickstart, you connect a Rust application to Azure Cosmos DB using the Azure SDK for Rust. Create, read, and query items in an existing container.

This quickstart uses version 1.0.0 of the generally available Azure Cosmos DB SDK for Rust.

Important

OpenTelemetry support (unstable_opentelemetry) and patch operations (unstable_patch) in the Azure Cosmos DB SDK for Rust remain in preview and aren't recommended for production workloads. These preview features are separate from the generally available SDK and aren't used in this quickstart.

API reference documentation | Library source code | Crate (Rust) | Azure Developer CLI

Prerequisites

If you don't have an Azure account, create a free account before you begin.

Tip

Agent Kit helps coding agents work with Azure Cosmos DB quickly and efficiently using recommended best practices. To get started, run:

npx skills add AzureCosmosDB/cosmosdb-agent-kit

To learn more, see Azure Cosmos DB Agent Kit.

Install the client library

You can get the client library as the azure_data_cosmos crate. The following commands use the latest stable Azure Cosmos DB and Azure Identity releases, version 1.0.0.

  1. Create a Rust application and open its directory.

    cargo new cosmos-quickstart
    cd cosmos-quickstart
    
  2. Add version 1.0.0 of the azure_data_cosmos crate by using cargo add.

    cargo add azure_data_cosmos@1.0.0
    
  3. Add version 1.0.0 of the azure_identity crate.

    cargo add azure_identity@1.0.0
    
  4. Add the dependencies for JSON serialization, asynchronous execution, and query iteration.

    cargo add serde --features derive
    cargo add tokio --features macros,rt-multi-thread
    cargo add futures
    

Import libraries

Add these imports to src/main.rs.

use azure_data_cosmos::{AccountReference, CosmosClient, FeedScope, PartitionKey, Query, RoutingStrategy};
use azure_identity::DeveloperToolsCredential;
use futures::TryStreamExt;

Object model

Name Description
CosmosClient The primary client for connecting to an account and getting database clients.
DatabaseClient A client for a database within the account.
ContainerClient A client for a container and its items.

Code examples

The examples use the existing cosmicworks database and products container. The container uses /category as its partition key. Place the Item type from the create example after your imports. Replace the generated main function with the following async entry point, then add the authentication, database, container, upsert, read, and query snippets in order before Ok(()).

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    Ok(())
}

Authenticate the client

Use DeveloperToolsCredential to authenticate through your signed-in developer tools. Set the AZURE_COSMOS_ENDPOINT environment variable to your account's endpoint URL, available on its Azure portal Overview page. Set AZURE_COSMOS_REGION to the Azure region closest to your application, for example 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?;

Reuse the client for subsequent operations. For Azure-hosted production applications, use a managed identity instead of a developer credential.

Get a database

Use client.database_client to obtain a client for the existing database named cosmicworks.

let database = client.database_client("cosmicworks");

Get a container

Obtain a client for the existing products container using database.container_client.

let container = database.container_client("products", None).await?;

Create an item

Build a new type with all of the members you want to serialize into JSON. In this example, the type has a unique identifier, and fields for category, name, quantity, price, and sale. Derive the serde::Serialize trait on this type, so that it can be serialized to 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,
}

Create an item in the container using container.upsert_item. This method "upserts" the item effectively replacing the item if it already exists.

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?;

Read an item

Perform a point read operation by using both the unique identifier (id) and partition key fields. Use container.read_item to efficiently retrieve the specific 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);

Query items

Perform a query over multiple items in a container using container.query_items. Find all items within a specified category using this parameterized query:

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);
}

Run the application after adding the snippets and setting the environment variables.

cargo run

Explore your data

Use the Visual Studio Code extension for Azure Cosmos DB to explore your NoSQL data. You can perform core database operations including, but not limited to:

  • Performing queries using a scrapbook or the query editor
  • Modifying, updating, creating, and deleting items
  • Importing bulk data from other sources
  • Managing databases and containers

For more information, see How-to use Visual Studio Code extension to explore Azure Cosmos DB for NoSQL data.

Next step