We’re excited to announce the public preview of the Azure Cosmos DB SDK for Rust, a native Rust SDK that enables developers to interact with Azure Cosmos DB for NoSQL accounts from their Rust applications.
Following the release of Azure SDK for Rust Beta, the Azure Cosmos DB Rust SDK provides an idiomatic API for performing operations on databases, containers, and items. With this release, Rust developers can now build high-performance, scalable applications using Azure Cosmos DB.
Rust is an excellent choice for modern application development due to its focus on performance, memory safety, and concurrency. Rust eliminates common bugs such as null pointer dereferences and buffer overflows through its powerful ownership model. Additionally, Rust’s strong type system and borrow checker ensure thread safety, making it ideal for building reliable, concurrent applications at scale. With its growing ecosystem and support for WebAssembly, Rust is increasingly becoming a go-to language for performance-critical workloads, cloud services, and distributed systems like Azure Cosmos DB.
Getting started
Prerequisites:
- An Azure subscription, an Azure Cosmos DB for NoSQL free trial account, or the Azure Cosmos DB Emulator.
- A working Rust development environment (Rust 1.70+ recommended).
Running a Rust program
To run a Rust program using the Azure Cosmos DB SDK, follow these steps:
- Ensure Rust and Cargo are installed. If not, install them using rustup.
- Create a new Rust project:
cargo new cosmosdb-example cd cosmosdb-example
- Install the Azure Cosmos DB Rust SDK dependencies:
cargo install azure_data_cosmos cargo install azure_identity
- Replace the contents of
src/main.rs
with your Rust program. - Build and run the program:
cargo run
Installing dependencies
For the samples below, create the following dependencies in Cargo.toml:
[dependencies]
azure_data_cosmos = "0.22.0"
azure_identity = "0.22.0"
azure_core = "0.22.0"
clap = { version = "4.3", features = ["derive"] }
tracing = "0.1"
tokio = { version = "1", features = ["full"] } # for async support
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
serde = { version = "1.0", features = ["derive"] } # For JSON serialization/deserialization
serde_json = "1.0" # For working with JSON data
futures = "0.3"
Creating a client
To interact with Azure Cosmos DB, you need an account. You can create one using the Azure portal, Azure CLI, or Azure Resource Manager templates. If you don’t have an Azure Subscription, you can create a free trial account or use the Azure Cosmos DB Emulator.
Once you have an account, you can create a client using CosmosClient::new
and authenticate using either the DefaultAzureCredential
(recommended) or an account key.
Use DefaultAzureCredential for authentication (recommended)
DefaultAzureCredential
provides authentication using Microsoft Entra ID (formerly Azure Active Directory) and is the recommended approach for production and development scenarios.
use azure_core::StatusCode;
use azure_data_cosmos::{CosmosClient, PartitionKey};
use azure_identity::DefaultAzureCredential;
use serde::Serialize;
use futures::StreamExt;
use std::env;
use tokio;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let credential = DefaultAzureCredential::new().unwrap();
let client = CosmosClient::new("myCosmosAccount", credential, None)?;
println!("Cosmos client initialized successfully");
Ok(())
}
Retrieve a database
To retrieve a database, use the database_client
method on client
:
// must exist - create database not supported in Entra ID
let database = client.database_client("my-database");
Creating a container
To retrieve a container, use container_client
on database
:
// must exist with myPartitionKey as partition key for examples below - create container not supported in Entra ID)
let container_client = database.container_client("my-container");
Performing operations on items
Create an item
To insert an item into a container, use create_item
:
#[derive(Serialize)] //ensure serde is in Cargo.toml as a dependency
struct Item {
id: String,
myPartitionKey: String,
name: String,
}
let item = Item {
id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb".to_string(),
myPartitionKey: "myPartitionKeyValue".to_string(),
name: "Theo".to_string(),
};
let partition_key = PartitionKey::from(item.myPartitionKey.clone());
container_client.create_item(partition_key, item, None).await?;
Read an item
To read an item, use read_item
:
// read item
let read_response = container_client
.read_item("myPartitionKeyValue", "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb", None)
.await;
match read_response {
Err(e) if e.http_status() == Some(StatusCode::NotFound) => println!("Item not found!"),
Ok(r) => {
let item: serde_json::Value = r.into_json_body().await?;
println!("Found item:");
println!("{:#?}", item);
}
Err(e) => return Err(e.into()),
};
Query items
You can perform queries using SQL-like syntax:
// query items
let query = "SELECT * FROM c";
let pk = PartitionKey::from("myPartitionKeyValue");
let mut items =
container_client.query_items::<serde_json::Value>(&query.to_string(), pk, None)?;
while let Some(page) = items.next().await {
let page = page?.into_body().await?;
println!("Query results page");
println!(" Items:");
for item in page.items {
println!(" * {:#?}", item);
}
}
Next steps
The Azure Cosmos DB client library for Rust enables developers to build highly available applications with Azure Cosmos DB. Check out our samples repository and follow the quickstart guide to get started. Find out more about the Azure SDK for Rust Beta here.
We welcome feedback! If you have questions or suggestions, please report issues on our GitHub repository. We look forward to seeing what you build with Azure Cosmos DB and Rust!
About Azure Cosmos DB
Azure Cosmos DB is a fully managed and serverless NoSQL and vector database for modern app development, including AI applications. With its SLA-backed speed and availability as well as instant dynamic scalability, it is ideal for real-time NoSQL and MongoDB applications that require high performance and distributed computing over massive volumes of NoSQL and vector data.
Try Azure Cosmos DB for free here. To stay in the loop on Azure Cosmos DB updates, follow us on X, YouTube, and LinkedIn.
0 comments
Be the first to start the discussion.