Azure SDK for Rust - Azure Cosmos DB crate
The Cosmos DB crate.
azure-cosmos offers functionality needed to interact with Cosmos DB from Rust. As an abstraction over the Cosmos DB
Rest API, anything that is possible through that Rest API
should also be possible with this crate.
Examples
use azure_data_cosmos::prelude::*;
use azure_core::Context;
use azure_core::error::Result;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct MySampleStruct {
id: String,
a_string: String,
a_number: u64,
a_timestamp: i64,
}
impl<'a> azure_data_cosmos::CosmosEntity<'a> for MySampleStruct {
type Entity = u64;
fn partition_key(&'a self) -> Self::Entity {
self.a_number
}
}
#[tokio::main]
async fn main() -> Result<()> {
let master_key =
std::env::var("COSMOS_MASTER_KEY").expect("Set env variable COSMOS_MASTER_KEY first!");
let account = std::env::var("COSMOS_ACCOUNT").expect("Set env variable COSMOS_ACCOUNT first!");
let database_name = std::env::args()
.nth(1)
.expect("please specify the database name as first command line parameter");
let collection_name = std::env::args()
.nth(2)
.expect("please specify the collection name as first command line parameter");
let authorization_token = AuthorizationToken::primary_from_base64(&master_key)?;
let client = CosmosClient::new(account.clone(), authorization_token, CosmosOptions::default());
let database = client.database_client(database_name);
let collection = database.collection_client(collection_name);
println!("Inserting 10 documents...");
for i in 0..10 {
let document_to_insert = MySampleStruct {
id: format!("unique_id{}", i),
a_string: "Something here".to_owned(),
a_number: i * 100, a_timestamp: chrono::Utc::now().timestamp(),
};
collection
.create_document(
Context::new(),
&document_to_insert,
CreateDocumentOptions::new().is_upsert(true),
)
.await?;
}
println!("Done!");
Ok(())
}