Struct ContainerClient

Source
pub struct ContainerClient { /* private fields */ }
Expand description

A client for working with a specific container in a Cosmos DB account.

You can get a Container by calling DatabaseClient::container_client().

Implementations§

Source§

impl ContainerClient

Source

pub async fn read( &self, options: Option<ReadContainerOptions<'_>>, ) -> Result<Response<ContainerProperties>>

Reads the properties of the container.

§Arguments
  • options - Optional parameters for the request.
§Examples
let response = container_client.read(None)
    .await?
    .into_body()
    .await?;
Source

pub async fn replace( &self, properties: ContainerProperties, options: Option<ReplaceContainerOptions<'_>>, ) -> Result<Response<ContainerProperties>>

Updates the indexing policy of the container.

NOTE: The ContainerProperties::id and ContainerProperties::partition_key must be the same as the existing container, they cannot be changed.

§Arguments
  • properties - The ContainerProperties to update the container with.
  • options - Optional parameters for the request.
§Examples
use azure_data_cosmos::models::{ContainerProperties, IndexingPolicy};
let new_properties = ContainerProperties {
    id: "MyContainer".into(),
    partition_key: "/id".into(),
    indexing_policy: Some(IndexingPolicy {
        included_paths: vec!["/index_me".into()],
        ..Default::default()
    }),
    ..Default::default()
};
let response = container_client.replace(new_properties, None)
    .await?
    .into_body()
    .await?;
Source

pub async fn read_throughput( &self, options: Option<ThroughputOptions<'_>>, ) -> Result<Option<Response<ThroughputProperties>>>

Reads container throughput properties, if any.

This will return None if the database does not have a throughput offer configured.

§Arguments
  • options - Optional parameters for the request.
Source

pub async fn replace_throughput( &self, throughput: ThroughputProperties, options: Option<ThroughputOptions<'_>>, ) -> Result<Response<ThroughputProperties>>

Replaces the container throughput properties.

§Arguments
  • throughput - The new throughput properties to set.
  • options - Optional parameters for the request.
Source

pub async fn delete( &self, options: Option<DeleteContainerOptions<'_>>, ) -> Result<Response<()>>

Deletes this container.

This is a control-plane API and requires that you authenticate using a key. To use Entra ID to perform this operation, you must use the Azure Resource Manager APIs.

§Arguments
  • options - Optional parameters for the request.
Source

pub async fn create_item<T: Serialize>( &self, partition_key: impl Into<PartitionKey>, item: T, options: Option<ItemOptions<'_>>, ) -> Result<Response<()>>

Creates a new item in the container.

§Arguments
  • partition_key - The partition key of the new item.
  • item - The item to create. The type must implement Serialize and Deserialize
  • options - Optional parameters for the request
§Examples
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Product {
    #[serde(rename = "id")] // Use serde attributes to control serialization
    product_id: String,
    category_id: String,
    product_name: String,
}
let p = Product {
    product_id: "product1".to_string(),
    category_id: "category1".to_string(),
    product_name: "Product #1".to_string(),
};
container_client
    .create_item("category1", p, None)
    .await?;
§Content Response on Write

By default, the newly created item is not returned in the HTTP response. If you want the new item to be returned, set the ItemOptions::enable_content_response_on_write option to true. You can deserialize the returned item by retrieving the ResponseBody using Response::into_raw_body and then calling ResponseBody::json, like this:

use azure_data_cosmos::ItemOptions;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Product {
    #[serde(rename = "id")] // Use serde attributes to control serialization
    product_id: String,
    category_id: String,
    product_name: String,
}
let p = Product {
    product_id: "product1".to_string(),
    category_id: "category1".to_string(),
    product_name: "Product #1".to_string(),
};
let options = ItemOptions {
    enable_content_response_on_write: true,
    ..Default::default()
};
let created_item = container_client
    .create_item("category1", p, Some(options))
    .await?
    .into_raw_body().json::<Product>()
    .await?;
Source

pub async fn replace_item<T: Serialize>( &self, partition_key: impl Into<PartitionKey>, item_id: &str, item: T, options: Option<ItemOptions<'_>>, ) -> Result<Response<()>>

Replaces an existing item in the container.

§Arguments
  • partition_key - The partition key of the item to replace.
  • item_id - The id of the item to replace.
  • item - The item to create. The type must implement Serialize and Deserialize
  • options - Optional parameters for the request
§Examples
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Product {
    #[serde(rename = "id")] // Use serde attributes to control serialization
    product_id: String,
    category_id: String,
    product_name: String,
}
let p = Product {
    product_id: "product1".to_string(),
    category_id: "category1".to_string(),
    product_name: "Product #1".to_string(),
};
container_client
    .replace_item("category1", "product1", p, None)
    .await?;
§Content Response on Write

By default, the replaced item is not returned in the HTTP response. If you want the replaced item to be returned, set the ItemOptions::enable_content_response_on_write option to true. You can deserialize the returned item by retrieving the ResponseBody using Response::into_raw_body and then calling ResponseBody::json, like this:

use azure_data_cosmos::ItemOptions;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Product {
    #[serde(rename = "id")] // Use serde attributes to control serialization
    product_id: String,
    category_id: String,
    product_name: String,
}
let p = Product {
    product_id: "product1".to_string(),
    category_id: "category1".to_string(),
    product_name: "Product #1".to_string(),
};
let options = ItemOptions {
    enable_content_response_on_write: true,
    ..Default::default()
};
let updated_product: Product = container_client
    .replace_item("category1", "product1", p, Some(options))
    .await?
    .into_raw_body().json::<Product>()
    .await?;
Source

pub async fn upsert_item<T: Serialize>( &self, partition_key: impl Into<PartitionKey>, item: T, options: Option<ItemOptions<'_>>, ) -> Result<Response<()>>

Creates or replaces an item in the container.

If an item with the same ID is found in the container, it is updated with the provided content. If no item with the same ID is found in the container, a new item is created with the provided content.

§Arguments
  • partition_key - The partition key of the item to create or replace.
  • item - The item to create. The type must implement Serialize and Deserialize
  • options - Optional parameters for the request
§Examples
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Product {
    #[serde(rename = "id")] // Use serde attributes to control serialization
    product_id: String,
    category_id: String,
    product_name: String,
}
let p = Product {
    product_id: "product1".to_string(),
    category_id: "category1".to_string(),
    product_name: "Product #1".to_string(),
};
container_client
    .upsert_item("category1", p, None)
    .await?;
§Content Response on Write

By default, the created/replaced item is not returned in the HTTP response. If you want the created/replaced item to be returned, set the ItemOptions::enable_content_response_on_write option to true. You can deserialize the returned item by retrieving the ResponseBody using Response::into_raw_body and then calling ResponseBody::json, like this:

use azure_data_cosmos::ItemOptions;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Product {
    #[serde(rename = "id")] // Use serde attributes to control serialization
    product_id: String,
    category_id: String,
    product_name: String,
}
let p = Product {
    product_id: "product1".to_string(),
    category_id: "category1".to_string(),
    product_name: "Product #1".to_string(),
};
let options = ItemOptions {
    enable_content_response_on_write: true,
    ..Default::default()
};
let updated_product = container_client
    .upsert_item("category1", p, Some(options))
    .await?
    .into_raw_body().json::<Product>()
    .await?;
Ok(())
Source

pub async fn read_item<T>( &self, partition_key: impl Into<PartitionKey>, item_id: &str, options: Option<ItemOptions<'_>>, ) -> Result<Response<T>>

Reads a specific item from the container.

§Arguments
  • partition_key - The partition key of the item to read. See PartitionKey for more information on how to specify a partition key.
  • item_id - The id of the item to read.
  • options - Optional parameters for the request

NOTE: The read item is always returned, so the ItemOptions::enable_content_response_on_write option is ignored.

§Examples
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Product {
    #[serde(rename = "id")] // Use serde attributes to control serialization
    product_id: String,
    category_id: String,
    product_name: String,
}
let item: Product = container_client
    .read_item("partition1", "item1", None)
    .await?
    .into_body()
    .await?;
println!("Read Item: {:#?}", item);
Source

pub async fn delete_item( &self, partition_key: impl Into<PartitionKey>, item_id: &str, options: Option<ItemOptions<'_>>, ) -> Result<Response<()>>

Deletes an item from the container.

§Arguments
  • partition_key - The partition key of the item to delete.
  • item_id - The id of the item to delete.
  • options - Optional parameters for the request

NOTE: The deleted item is never returned by the Cosmos API, so the ItemOptions::enable_content_response_on_write option is ignored.

§Examples
use serde::{Deserialize, Serialize};
container_client
    .delete_item("partition1", "item1", None)
    .await?;
Source

pub async fn patch_item( &self, partition_key: impl Into<PartitionKey>, item_id: &str, patch: PatchDocument, options: Option<ItemOptions<'_>>, ) -> Result<Response<()>>

Patches an item in the container.

§Arguments
  • partition_key - The partition key of the item to patch.
  • item_id - The id of the item to patch.
  • patch - The patch document to apply to the item.
  • options - Optional parameters for the request.
§Examples
use azure_data_cosmos::models::PatchDocument;
use serde::{Deserialize, Serialize};
let patch = PatchDocument::default().with_add("/some/path", "some value")?;
container_client
    .patch_item("partition1", "item1", patch, None)
    .await?;
§Content Response on Write

By default, the patched item is not returned in the HTTP response. If you want the patched item to be returned, set the ItemOptions::enable_content_response_on_write option to true. You can deserialize the returned item by retrieving the ResponseBody using Response::into_raw_body and then calling ResponseBody::json, like this:

For example:

use azure_data_cosmos::{models::PatchDocument, ItemOptions};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Product {
    #[serde(rename = "id")] // Use serde attributes to control serialization
    product_id: String,
    category_id: String,
    product_name: String,
}
let options = ItemOptions {
    enable_content_response_on_write: true,
    ..Default::default()
};
let patch = PatchDocument::default().with_add("/some/path", "some value")?;
let patched_item = client
    .patch_item("partition1", "item1", patch, Some(options))
    .await?
    .into_raw_body().json::<Product>()
    .await?;
Source

pub fn query_items<T: DeserializeOwned + Send + 'static>( &self, query: impl Into<Query>, partition_key: impl Into<PartitionKey>, options: Option<QueryOptions<'_>>, ) -> Result<FeedPager<T>>

Executes a single-partition query against items in the container.

The resulting document will be deserialized into the type provided as T. If you want to deserialize the document to a direct representation of the JSON returned, use serde_json::Value as the target type.

We recommend using “turbofish” syntax (query_items::<SomeTargetType>(...)) to specify the target type, as it makes type inference easier.

NOTE: Currently, the Azure Cosmos DB SDK for Rust only supports single-partition querying. Cross-partition queries may be supported in the future.

§Arguments
  • query - The query to execute.
  • partition_key - The partition key to scope the query on, or specify an empty key (()) to perform a cross-partition query.
  • options - Optional parameters for the request.
§Cross Partition Queries

Cross-partition queries are significantly limited in the current version of the Cosmos DB SDK. They are run on the gateway and limited to simple projections (SELECT) and filtering (WHERE). For more details, see the Cosmos DB documentation page on cross-partition queries.

§Examples

The query and partition_key parameters accept anything that can be transformed Into their relevant types. This allows simple queries without parameters to be expressed easily:

#[derive(serde::Deserialize)]
struct Customer {
    id: u64,
    name: String,
}
let items = container_client.query_items::<Customer>(
    "SELECT * FROM c",
    "some_partition_key",
    None)?;

You can specify parameters by using Query::from() and Query::with_parameter():

use azure_data_cosmos::Query;
#[derive(serde::Deserialize)]
struct Customer {
    id: u64,
    name: String,
}
let query = Query::from("SELECT COUNT(*) FROM c WHERE c.customer_id = @customer_id")
    .with_parameter("@customer_id", 42)?;
let items = container_client.query_items::<Customer>(query, "some_partition_key", None)?;

See PartitionKey for more information on how to specify a partition key, and Query for more information on how to specify a query.

Trait Implementations§

Source§

impl Clone for ContainerClient

Source§

fn clone(&self) -> ContainerClient

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,