azure.cosmos.aio package

class azure.cosmos.aio.ContainerProxy(client_connection: CosmosClientConnection, database_link: str, id: str, properties: Dict[str, Any] | None = None)[source]

An interface to interact with a specific DB Container.

This class should not be instantiated directly. Instead, use the get_container_client() method to get an existing container, or the create_container() method to create a new container.

A container in an Azure Cosmos DB SQL API database is a collection of documents, each of which is represented as an Item.

Variables:
  • id (str) – ID (name) of the container

  • session_token (str) – The session token for the container.

async create_item(body: Dict[str, Any], *, pre_trigger_include: str | None = None, post_trigger_include: str | None = None, indexing_directive: int | None = None, enable_automatic_id_generation: bool = False, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, priority: Literal['High', 'Low'] | None = None, no_response: bool | None = None, **kwargs: Any) CosmosDict[source]

Create an item in the container.

To update or replace an existing item, use the ContainerProxy.upsert_item() method.

Parameters:

body (dict[str, str]) – A dict-like object representing the item to create.

Keyword Arguments:
  • pre_trigger_include (str) – trigger id to be used as pre operation trigger.

  • post_trigger_include (str) – trigger id to be used as post operation trigger.

  • indexing_directive (Union[int, IndexingDirective]) – Enumerates the possible values to indicate whether the document should be omitted from indexing. Possible values include: 0 for Default, 1 for Exclude, or 2 for Include.

  • enable_automatic_id_generation (bool) – Enable automatic id generation if no id present.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

  • no_response (bool) – Indicates whether service should be instructed to skip sending response payloads. When not specified explicitly here, the default value will be determined from client-level options.

Raises:

CosmosHttpResponseError – Item with the given ID already exists.

Returns:

A CosmosDict representing the new item. The dict will be empty if no_response is specified.

Return type:

CosmosDict[str, Any]

async delete_all_items_by_partition_key(partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], *, pre_trigger_include: str | None = None, post_trigger_include: str | None = None, session_token: str | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any) None[source]

The delete by partition key feature is an asynchronous, background operation that allows you to delete all documents with the same logical partition key value, using the Cosmos SDK. The delete by partition key operation is constrained to consume at most 10% of the total available RU/s on the container each second. This helps in limiting the resources used by this background task.

Parameters:

partition_key (Union[str, int, float, bool, Sequence[Union[str, int, float, bool, None]]]) – Partition key for the items to be deleted.

Keyword Arguments:
  • pre_trigger_include (str) – trigger id to be used as pre operation trigger.

  • post_trigger_include (str) – trigger id to be used as post operation trigger.

  • session_token (str) – Token for use with Session consistency.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • response_hook (Callable) – A callable invoked with the response metadata.

Return type:

None

async delete_conflict(conflict: str | Mapping[str, Any], partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], **kwargs: Any) None[source]

Delete a specified conflict from the container.

If the conflict does not already exist in the container, an exception is raised.

Parameters:
  • conflict (Union[str, Dict[str, Any]]) – The ID (name) or dict representing the conflict to retrieve.

  • partition_key (Union[str, int, float, bool, Sequence[Union[str, int, float, bool, None]]]) – Partition key for the conflict to retrieve.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], None], None]) – A callable invoked with the response metadata.

Raises:
Return type:

None

async delete_item(item: str | Mapping[str, Any], partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], *, pre_trigger_include: str | None = None, post_trigger_include: str | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) None[source]

Delete the specified item from the container.

If the item does not already exist in the container, an exception is raised.

Parameters:
  • item (Union[str, Dict[str, Any]]) – The ID (name) or dict representing item to be deleted.

  • partition_key (Union[str, int, float, bool, Sequence[Union[str, int, float, bool, None]]]) – Specifies the partition key value for the item.

Keyword Arguments:
  • pre_trigger_include (str) – trigger id to be used as pre operation trigger.

  • post_trigger_include (str) – trigger id to be used as post operation trigger.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

  • response_hook (Callable[[Dict[str, str], None], None]) – A callable invoked with the response metadata.

Raises:
Return type:

None

async execute_item_batch(batch_operations: Sequence[Tuple[str, Tuple[Any, ...]] | Tuple[str, Tuple[Any, ...], Dict[str, Any]]], partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], *, pre_trigger_include: str | None = None, post_trigger_include: str | None = None, session_token: str | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) CosmosList[source]

Executes the transactional batch for the specified partition key.

Parameters:
  • batch_operations (List[Tuple[Any]]) – The batch of operations to be executed.

  • partition_key (Union[str, int, float, bool, Sequence[Union[str, int, float, bool, None]]]) – The partition key value of the batch operations.

Keyword Arguments:
  • pre_trigger_include (str) – trigger id to be used as pre operation trigger.

  • post_trigger_include (str) – trigger id to be used as post operation trigger.

  • session_token (str) – Token for use with Session consistency.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

  • response_hook (Callable) – A callable invoked with the response metadata.

Returns:

A CosmosList representing the items after the batch operations went through.

Raises:
Return type:

CosmosList[Dict[str, Any]]

async feed_range_from_partition_key(partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue]) Dict[str, Any][source]

Gets the feed range for a given partition key. :param partition_key: partition key to get feed range. :type partition_key: PartitionKeyType :returns: a feed range :rtype: Dict[str, Any]

Warning

The structure of the dict representation of a feed range may vary, including which keys are present. It therefore should only be treated as an opaque value.

async get_conflict(conflict: str | Mapping[str, Any], partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], **kwargs: Any) Dict[str, Any][source]

Get the conflict identified by conflict.

Parameters:
  • conflict (Union[str, Dict[str, Any]]) – The ID (name) or dict representing the conflict to retrieve.

  • partition_key (Union[str, int, float, bool, Sequence[Union[str, int, float, bool, None]]]) – Partition key for the conflict to retrieve.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – The given conflict couldn’t be retrieved.

Returns:

A dict representing the retrieved conflict.

Return type:

Dict[str, Any]

async get_latest_session_token(feed_ranges_to_session_tokens: List[Tuple[Dict[str, Any], str]], target_feed_range: Dict[str, Any]) str[source]

provisional This method is still in preview and may be subject to breaking changes.

Gets the the most up to date session token from the list of session token and feed range tuples for a specific target feed range. The feed range can be obtained from a partition key or by reading the container feed ranges. This should only be used if maintaining own session token or else the CosmosClient instance will keep track of session token. Session tokens and feed ranges are scoped to a container. Only input session tokens and feed ranges obtained from the same container. :param feed_ranges_to_session_tokens: List of feed range and session token tuples. :type feed_ranges_to_session_tokens: List[Tuple[Dict[str, Any], str]] :param target_feed_range: feed range to get most up to date session token. :type target_feed_range: Dict[str, Any] :returns: a session token :rtype: str

async get_throughput(**kwargs: Any) ThroughputProperties[source]

Get the ThroughputProperties object for this container.

If no ThroughputProperties already exists for the container, an exception is raised.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], List[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – No throughput properties exist for the container or the throughput properties could not be retrieved.

Returns:

ThroughputProperties for the container.

Return type:

ThroughputProperties

async is_feed_range_subset(parent_feed_range: Dict[str, Any], child_feed_range: Dict[str, Any]) bool[source]

Checks if child feed range is a subset of parent feed range. :param parent_feed_range: left feed range :type parent_feed_range: Dict[str, Any] :param child_feed_range: right feed range :type child_feed_range: Dict[str, Any] :returns: a boolean indicating if child feed range is a subset of parent feed range :rtype: bool

Warning

The structure of the dict representation of a feed range may vary, including which keys are present. It therefore should only be treated as an opaque value.

list_conflicts(*, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

List all the conflicts in the container.

Keyword Arguments:
  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

  • response_hook (Callable[[Dict[str, str], AsyncItemPaged[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of conflicts (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

async patch_item(item: str | Dict[str, Any], partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], patch_operations: List[Dict[str, Any]], *, filter_predicate: str | None = None, pre_trigger_include: str | None = None, post_trigger_include: str | None = None, session_token: str | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, priority: Literal['High', 'Low'] | None = None, no_response: bool | None = None, **kwargs: Any) CosmosDict[source]
Patches the specified item with the provided operations if it

exists in the container.

If the item does not already exist in the container, an exception is raised.

Parameters:
  • item (Union[str, Dict[str, Any]]) – The ID (name) or dict representing item to be patched.

  • partition_key (Union[str, int, float, bool, Sequence[Union[str, int, float, bool, None]]]) – The partition key of the object to patch.

  • patch_operations (List[Dict[str, Any]]) – The list of patch operations to apply to the item.

Keyword Arguments:
  • filter_predicate (str) – conditional filter to apply to Patch operations.

  • pre_trigger_include (str) – trigger id to be used as pre operation trigger.

  • post_trigger_include (str) – trigger id to be used as post operation trigger.

  • session_token (str) – Token for use with Session consistency.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • response_hook (Callable) – A callable invoked with the response metadata.

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

  • no_response (bool) – Indicates whether service should be instructed to skip sending response payloads. When not specified explicitly here, the default value will be determined from client-level options.

Raises:

CosmosHttpResponseError – The patch operations failed or the item with given id does not exist.

Returns:

A CosmosDict representing the item after the patch operations went through. The dict will be empty if no_response is specified.

Return type:

CosmosDict[str, Any]

query_conflicts(query: str, *, parameters: List[Dict[str, object]] | None = None, partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue] | None = None, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

Return all conflicts matching a given query.

Parameters:

query (str) – The Azure Cosmos DB SQL query to execute.

Keyword Arguments:
  • parameters (List[Dict[str, Any]]) – Optional array of parameters to the query. Ignored if no query is provided.

  • partition_key (Union[str, int, float, bool, Sequence[Union[str, int, float, bool, None]]]) – Specifies the partition key value for the item. If none is passed in, a cross partition query will be executed.

  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

  • response_hook (Callable[[Dict[str, str], AsyncItemPaged[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of conflicts (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

query_items(query: str, *, parameters: List[Dict[str, object]] | None = None, partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue] | None = None, max_item_count: int | None = None, enable_scan_in_query: bool | None = None, populate_query_metrics: bool | None = None, populate_index_metrics: bool | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, max_integrated_cache_staleness_in_ms: int | None = None, priority: Literal['High', 'Low'] | None = None, continuation_token_limit: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

Return all results matching the given query.

You can use any value for the container name in the FROM clause, but often the container name is used. In the examples below, the container name is “products,” and is aliased as “p” for easier referencing in the WHERE clause.

Parameters:

query (str) – The Azure Cosmos DB SQL query to execute.

Keyword Arguments:
  • parameters (List[Dict[str, Any]]) – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys. Ignored if no query is provided.

  • partition_key (Union[str, int, float, bool, Sequence[Union[str, int, float, bool, None]]]) – Specifies the partition key value for the item. If none is provided, a cross-partition query will be executed.

  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

  • enable_scan_in_query (bool) – Allow scan on the queries which couldn’t be served as indexing was opted out on the requested paths.

  • populate_query_metrics (bool) – Enable returning query metrics in response headers.

  • populate_index_metrics (bool) – Used to obtain the index metrics to understand how the query engine used existing indexes and how it could use potential new indexes. Please note that this options will incur overhead, so it should be enabled only when debugging slow queries.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • response_hook (Callable[[Dict[str, str], AsyncItemPaged[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

  • continuation_token_limit (int) – The size limit in kb of the response continuation token in the query response. Valid values are positive integers. A value of 0 is the same as not passing a value (default no limit).

  • max_integrated_cache_staleness_in_ms (int) – The max cache staleness for the integrated cache in milliseconds. For accounts configured to use the integrated cache, using Session or Eventual consistency, responses are guaranteed to be no staler than this value.

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

Returns:

An AsyncItemPaged of items (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

Example:

Get all products that have not been discontinued:
        import json

        async for item in container.query_items(
                query='SELECT * FROM products p WHERE p.productModel <> "DISCONTINUED"'
        ):
            print(json.dumps(item, indent=True))
Parameterized query to get all products that have been discontinued:
        discontinued_items = container.query_items(
            query='SELECT * FROM products p WHERE p.productModel = @model AND p.productName="Widget"',
            parameters=[dict(name="@model", value="DISCONTINUED")],
        )
        async for item in discontinued_items:
            print(json.dumps(item, indent=True))
query_items_change_feed(*, max_item_count: int | None = None, start_time: datetime | Literal['Now', 'Beginning'] | None = None, partition_key: PartitionKeyType, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]
query_items_change_feed(*, feed_range: Dict[str, Any], max_item_count: int | None = None, start_time: datetime | Literal['Now', 'Beginning'] | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]]
query_items_change_feed(*, continuation: str, max_item_count: int | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]]
query_items_change_feed(*, max_item_count: int | None = None, start_time: datetime | Literal['Now', 'Beginning'] | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]]

Get a sorted list of items that were changed, in the order in which they were modified.

Keyword Arguments:
  • continuation (str) – The continuation token retrieved from previous response.

  • feed_range (Dict[str, Any]) – The feed range that is used to define the scope.

  • partition_key – The partition key that is used to define the scope (logical partition or a subset of a container)

  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

  • start_time – The start time to start processing chang feed items. Beginning: Processing the change feed items from the beginning of the change feed. Now: Processing change feed from the current time, so only events for all future changes will be retrieved. ~datetime.datetime: processing change feed from a point of time. Provided value will be converted to UTC. By default, it is start from current (“Now”)

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

  • response_hook (Callable) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of items (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

async read(*, populate_partition_key_range_statistics: bool | None = None, populate_quota_info: bool | None = None, session_token: str | None = None, priority: Literal['High', 'Low'] | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) Dict[str, Any][source]

Read the container properties.

Keyword Arguments:
  • populate_partition_key_range_statistics (bool) – Enable returning partition key range statistics in response headers.

  • populate_quota_info (bool) – Enable returning collection storage quota information in response headers.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

Raises:

CosmosHttpResponseError – Raised if the container couldn’t be retrieved. This includes if the container does not exist.

Returns:

Dict representing the retrieved container.

Return type:

Dict[str, Any]

read_all_items(*, max_item_count: int | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, max_integrated_cache_staleness_in_ms: int | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

List all the items in the container.

Keyword Arguments:
  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • response_hook (Callable[[Dict[str, str], AsyncItemPaged[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

  • max_integrated_cache_staleness_in_ms (int) – The max cache staleness for the integrated cache in milliseconds. For accounts configured to use the integrated cache, using Session or Eventual consistency, responses are guaranteed to be no staler than this value.

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

Returns:

An AsyncItemPaged of items (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

read_feed_ranges(*, force_refresh: bool = False, **kwargs: Any) AsyncIterable[Dict[str, Any]][source]

Obtains a list of feed ranges that can be used to parallelize feed operations.

Keyword Arguments:

force_refresh (bool) – Flag to indicate whether obtain the list of feed ranges directly from cache or refresh the cache.

Returns:

AsyncIterable representing the feed ranges in base64 encoded string

Return type:

AsyncIterable[Dict[str, Any]]

Warning

The structure of the dict representation of a feed range may vary, including which keys are present. It therefore should only be treated as an opaque value.

async read_item(item: str | Mapping[str, Any], partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], *, post_trigger_include: str | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, max_integrated_cache_staleness_in_ms: int | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) CosmosDict[source]

Get the item identified by item.

Parameters:
  • item (Union[str, Dict[str, Any]]) – The ID (name) or dict representing item to retrieve.

  • partition_key (Union[str, int, float, bool, Sequence[Union[str, int, float, bool, None]]]) – Partition key for the item to retrieve.

Keyword Arguments:
  • post_trigger_include (str) – trigger id to be used as post operation trigger.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

  • max_integrated_cache_staleness_in_ms (int) – The max cache staleness for the integrated cache in milliseconds. For accounts configured to use the integrated cache, using Session or Eventual consistency, responses are guaranteed to be no staler than this value.

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

Raises:

CosmosHttpResponseError – The given item couldn’t be retrieved.

Returns:

A CosmosDict representing the retrieved item.

Return type:

CosmosDict[str, Any]

Example:

Get an item from the database and update one of its properties:
        item = await container.read_item("item2", partition_key="Widget")
        item["productModel"] = "DISCONTINUED"
        updated_item = await container.upsert_item(item)
async replace_item(item: str | Mapping[str, Any], body: Dict[str, Any], *, pre_trigger_include: str | None = None, post_trigger_include: str | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, priority: Literal['High', 'Low'] | None = None, no_response: bool | None = None, **kwargs: Any) CosmosDict[source]

Replaces the specified item if it exists in the container.

If the item does not already exist in the container, an exception is raised.

Parameters:
  • item (Union[str, Dict[str, Any]]) – The ID (name) or dict representing item to be replaced.

  • body (Dict[str, Any]) – A dict representing the item to replace.

Keyword Arguments:
  • pre_trigger_include (str) – trigger id to be used as pre operation trigger.

  • post_trigger_include (str) – trigger id to be used as post operation trigger.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

  • no_response (bool) – Indicates whether service should be instructed to skip sending response payloads. When not specified explicitly here, the default value will be determined from client-level options.

Raises:

CosmosHttpResponseError – The replace operation failed or the item with given id does not exist.

Returns:

A CosmosDict representing the item after replace went through. The dict will be empty if no_response is specified.

Return type:

CosmosDict[str, Any]

async replace_throughput(throughput: int | ThroughputProperties, **kwargs: Any) ThroughputProperties[source]

Replace the container’s throughput.

If no ThroughputProperties already exist for the container, an exception is raised.

Parameters:

throughput (Union[int, ThroughputProperties]) – The throughput to be set.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – No throughput properties exist for the container or the throughput properties could not be updated.

Returns:

ThroughputProperties for the container, updated with new throughput.

Return type:

ThroughputProperties

async upsert_item(body: Dict[str, Any], *, pre_trigger_include: str | None = None, post_trigger_include: str | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, priority: Literal['High', 'Low'] | None = None, no_response: bool | None = None, **kwargs: Any) CosmosDict[source]

Insert or update the specified item.

If the item already exists in the container, it is replaced. If the item does not already exist, it is inserted.

Parameters:

body (Dict[str, Any]) – A dict-like object representing the item to update or insert.

Keyword Arguments:
  • pre_trigger_include (str) – trigger id to be used as pre operation trigger.

  • post_trigger_include (str) – trigger id to be used as post operation trigger.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

  • priority (Literal["High", "Low"]) – Priority based execution allows users to set a priority for each request. Once the user has reached their provisioned throughput, low priority requests are throttled before high priority requests start getting throttled. Feature must first be enabled at the account level.

  • no_response (bool) – Indicates whether service should be instructed to skip sending response payloads. When not specified explicitly here, the default value will be determined from client-level options.

Raises:

CosmosHttpResponseError – The given item could not be upserted.

Returns:

A CosmosDict representing the upserted item. The dict will be empty if no_response is specified.

Return type:

CosmosDict[str, Any]

property is_system_key: bool
property scripts: ScriptsProxy
class azure.cosmos.aio.CosmosClient(url: str, credential: str | Dict[str, str] | AsyncTokenCredential, *, consistency_level: str | None = None, **kwargs: Any)[source]

A client-side logical representation of an Azure Cosmos DB account.

Use this client to configure and execute requests to the Azure Cosmos DB service.

It’s recommended to maintain a single instance of CosmosClient per lifetime of the application which enables

efficient connection management and performance.

CosmosClient initialization is a heavy operation - don’t use initialization CosmosClient instances as

credentials or network connectivity validations.

Parameters:
  • url (str) – The URL of the Cosmos DB account.

  • credential (Union[str, Dict[str, str], AsyncTokenCredential]) – Can be the account key, or a dictionary of resource tokens.

Keyword Arguments:
  • consistency_level (str) – Consistency level to use for the session. Default value is None (account-level). More on consistency levels and possible values: https://aka.ms/cosmos-consistency-levels

  • timeout (int) – An absolute timeout in seconds, for the combined HTTP request and response processing.

  • connection_timeout (int) – The HTTP request timeout in seconds.

  • connection_mode (str) – The connection mode for the client - currently only supports ‘Gateway’.

  • proxy_config (ProxyConfiguration) – Connection proxy configuration.

  • ssl_config (SSLConfiguration) – Connection SSL configuration.

  • connection_verify (bool) – Whether to verify the connection, default value is True.

  • connection_cert (str) – An alternative certificate to verify the connection.

  • retry_total (int) – Maximum retry attempts.

  • retry_backoff_max (int) – Maximum retry wait time in seconds.

  • retry_fixed_interval (int) – Fixed retry interval in milliseconds.

  • retry_read (int) – Maximum number of socket read retry attempts.

  • retry_connect (int) – Maximum number of connection error retry attempts.

  • retry_status (int) – Maximum number of retry attempts on error status codes.

  • retry_on_status_codes (list[int]) – A list of specific status codes to retry on.

  • retry_backoff_factor (float) – Factor to calculate wait time between retry attempts.

  • enable_endpoint_discovery (bool) – Enable endpoint discovery for geo-replicated database accounts. (Default: True)

  • preferred_locations (list[str]) – The preferred locations for geo-replicated database accounts.

  • enable_diagnostics_logging (bool) – Enable the CosmosHttpLogging policy. Must be used along with a logger to work.

  • logger (Logger) – Logger to be used for collecting request diagnostics. Can be passed in at client level (to log all requests) or at a single request level. Requests will be logged at INFO level.

  • no_response_on_write (bool) – Indicates whether service should be instructed to skip sending response payloads for write operations on items by default unless specified differently per operation.

Example:

Create a new instance of the Cosmos DB client:
    async with CosmosClient(url, key) as client:

Instantiate a new CosmosClient.

async close() None[source]

Close this instance of CosmosClient.

async create_database(id: str, *, offer_throughput: int | ThroughputProperties | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any) DatabaseProxy[source]

Create a new database with the given ID (name).

Parameters:

id (str) – ID (name) of the database to create.

Keyword Arguments:
  • offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosResourceExistsError – Database with the given ID already exists.

Returns:

A DatabaseProxy instance representing the new database.

Return type:

DatabaseProxy

Example:

Create a database in the Cosmos DB account:
        database_name = "testDatabase"
        try:
            database = await client.create_database(id=database_name)
        except exceptions.CosmosResourceExistsError:
            database = client.get_database_client(database=database_name)
async create_database_if_not_exists(id: str, *, offer_throughput: int | ThroughputProperties | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any) DatabaseProxy[source]

Create the database if it does not exist already.

If the database already exists, the existing settings are returned.

..note::

This function does not check or update existing database settings or offer throughput if they differ from what is passed in.

Parameters:

id (str) – ID (name) of the database to read or create.

Keyword Arguments:
  • offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – The database read or creation failed.

Returns:

A DatabaseProxy instance representing the database.

Return type:

DatabaseProxy

async delete_database(database: str | DatabaseProxy | Dict[str, Any], *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any) None[source]

Delete the database with the given ID (name).

Parameters:

database (Union[str, DatabaseProxy, Dict[str, Any]]) – The ID (name), dict representing the properties, or DatabaseProxy instance of the database to delete.

Keyword Arguments:
  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • response_hook (Callable[[Dict[str, str]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the database couldn’t be deleted.

Return type:

None

classmethod from_connection_string(conn_str: str, *, credential: str | Dict[str, str] | None = None, consistency_level: str | None = None, **kwargs: Any) CosmosClient[source]

Create a CosmosClient instance from a connection string.

This can be retrieved from the Azure portal.For full list of optional keyword arguments, see the CosmosClient constructor.

Parameters:

conn_str (str) – The connection string.

Keyword Arguments:
  • credential (Union[str, Dict[str, str]]) – Alternative credentials to use instead of the key provided in the connection string.

  • consistency_level (str) – Consistency level to use for the session. Default value is None (account-level). More on consistency levels and possible values: https://aka.ms/cosmos-consistency-levels

Returns:

a CosmosClient instance

Return type:

CosmosClient

get_database_client(database: str | DatabaseProxy | Dict[str, Any]) DatabaseProxy[source]

Retrieve an existing database with the ID (name) id.

Parameters:

database (Union[str, DatabaseProxy, Dict[str, Any]]) – The ID (name), dict representing the properties, or DatabaseProxy instance of the database to get.

Returns:

A DatabaseProxy instance representing the retrieved database.

Return type:

DatabaseProxy

list_databases(*, max_item_count: int | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

List the databases in a Cosmos DB SQL database account.

Keyword Arguments:
  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • response_hook (Callable[[Dict[str, str]], None]) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of database properties (dicts).

Return type:

AsyncItemPaged[Dict[str, str]]

query_databases(query: str, *, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

Query the databases in a Cosmos DB SQL database account.

Parameters:

query (Union[str, Dict[str, Any]]) – The Azure Cosmos DB SQL query to execute.

Keyword Arguments:
  • parameters (List[Dict[str, Any]]) – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys.

  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • response_hook (Callable[[Dict[str, str]], None]) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of database properties (dicts).

Return type:

AsyncItemPaged[Dict[str, str]]

class azure.cosmos.aio.DatabaseProxy(client_connection: CosmosClientConnection, id: str, properties: Dict[str, Any] | None = None)[source]

An interface to interact with a specific database.

This class should not be instantiated directly. Instead use the get_database_client() method to get an existing database, or the create_database() method to create a new database.

A database contains one or more containers, each of which can contain items, stored procedures, triggers, and user-defined functions.

A database can also have associated users, each of which is configured with a set of permissions for accessing certain containers, stored procedures, triggers, user-defined functions, or items.

Variables:

id – The ID (name) of the database.

An Azure Cosmos DB SQL API database has the following system-generated properties. These properties are read-only:

  • _rid: The resource ID.

  • _ts: When the resource was last updated. The value is a timestamp.

  • _self: The unique addressable URI for the resource.

  • _etag: The resource etag required for optimistic concurrency control.

  • _colls: The addressable path of the collections resource.

  • _users: The addressable path of the users resource.

Parameters:
  • client_connection (CosmosClientConnection) – Client from which this database was retrieved.

  • id (str) – ID (name) of the database.

async create_container(id: str, partition_key: PartitionKey, *, indexing_policy: Dict[str, str] | None = None, default_ttl: int | None = None, offer_throughput: int | ThroughputProperties | None = None, unique_key_policy: Dict[str, str] | None = None, conflict_resolution_policy: Dict[str, str] | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, analytical_storage_ttl: int | None = None, vector_embedding_policy: Dict[str, Any] | None = None, full_text_policy: Dict[str, Any] | None = None, **kwargs: Any) ContainerProxy[source]

Create a new container with the given ID (name).

If a container with the given ID already exists, a CosmosResourceExistsError is raised.

Parameters:
  • id (str) – ID (name) of container to create.

  • partition_key (PartitionKey) – The partition key to use for the container.

Keyword Arguments:
  • indexing_policy (dict[str, str]) – The indexing policy to apply to the container.

  • default_ttl (int) – Default time to live (TTL) for items in the container. If unspecified, items do not expire.

  • offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.

  • unique_key_policy (dict[str, str]) – The unique key policy to apply to the container.

  • conflict_resolution_policy (dict[str, str]) – The conflict resolution policy to apply to the container.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • computed_properties (List[Dict[str, str]]) – provisional Sets The computed properties for this container in the Azure Cosmos DB Service. For more Information on how to use computed properties visit here: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/query/computed-properties?tabs=dotnet

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

  • analytical_storage_ttl (int) – Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.

  • vector_embedding_policy (Dict[str, Any]) – The vector embedding policy for the container. Each vector embedding possesses a predetermined number of dimensions, is associated with an underlying data type, and is generated for a particular distance function.

  • full_text_policy (Dict[str, Any]) – provisional The full text policy for the container. Used to denote the default language to be used for all full text indexes, or to individually assign a language to each full text index path.

Raises:

CosmosHttpResponseError – The container creation failed.

Returns:

A ContainerProxy instance representing the new container.

Return type:

ContainerProxy

Example:

Create a container with default settings:
        container_name = "products"
        try:
            container = await database.create_container(
                id=container_name, partition_key=PartitionKey(path="/productName")
            )
        except exceptions.CosmosResourceExistsError:
            container = database.get_container_client(container_name)
Create a container with specific settings; in this case, a custom partition key:
        customer_container_name = "customers"
        try:
            customer_container = await database.create_container(
                id=customer_container_name,
                partition_key=PartitionKey(path="/city"),
                default_ttl=200,
            )
        except exceptions.CosmosResourceExistsError:
            customer_container = database.get_container_client(customer_container_name)
async create_container_if_not_exists(id: str, partition_key: PartitionKey, *, indexing_policy: Dict[str, str] | None = None, default_ttl: int | None = None, offer_throughput: int | ThroughputProperties | None = None, unique_key_policy: Dict[str, str] | None = None, conflict_resolution_policy: Dict[str, str] | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, analytical_storage_ttl: int | None = None, vector_embedding_policy: Dict[str, Any] | None = None, full_text_policy: Dict[str, Any] | None = None, **kwargs: Any) ContainerProxy[source]

Create a container if it does not exist already.

If the container already exists, the existing settings are returned. Note: it does not check or update the existing container settings or offer throughput if they differ from what was passed into the method.

Parameters:
  • id (str) – ID (name) of container to create.

  • partition_key (PartitionKey) – The partition key to use for the container.

Keyword Arguments:
  • indexing_policy (dict[str, str]) – The indexing policy to apply to the container.

  • default_ttl (int) – Default time to live (TTL) for items in the container. If unspecified, items do not expire.

  • offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.

  • unique_key_policy (dict[str, str]) – The unique key policy to apply to the container.

  • conflict_resolution_policy (dict[str, str]) – The conflict resolution policy to apply to the container.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • computed_properties (List[Dict[str, str]]) – provisional Sets The computed properties for this container in the Azure Cosmos DB Service. For more Information on how to use computed properties visit here: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/query/computed-properties?tabs=dotnet

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

  • analytical_storage_ttl (int) – Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.

  • vector_embedding_policy (Dict[str, Any]) – provisional The vector embedding policy for the container. Each vector embedding possesses a predetermined number of dimensions, is associated with an underlying data type, and is generated for a particular distance function.

  • full_text_policy (Dict[str, Any]) – provisional The full text policy for the container. Used to denote the default language to be used for all full text indexes, or to individually assign a language to each full text index path.

Raises:

CosmosHttpResponseError – The container creation failed.

Returns:

A ContainerProxy instance representing the new container.

Return type:

ContainerProxy

async create_user(body: Dict[str, Any], **kwargs: Any) UserProxy[source]

Create a new user in the container.

To update or replace an existing user, use the ContainerProxy.upsert_user() method.

Parameters:

body (Dict[str, Any]) – A dict object with an id key and value representing the user to be created. The user ID must be unique within the database, and consist of no more than 255 characters.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the given user couldn’t be created.

Returns:

A UserProxy instance representing the new user.

Return type:

UserProxy

Example:

Create a database user:
        try:
            await database.create_user(dict(id="Walter Harp"))
            print("Created user Walter Harp.")
        except exceptions.CosmosResourceExistsError:
            print("A user with that ID already exists.")
        except exceptions.CosmosHttpResponseError as failure:
            print("Failed to create user. Status code:{}".format(failure.status_code))
async delete_container(container: str | ContainerProxy | Mapping[str, Any], *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, **kwargs: Any) None[source]

Delete a container.

Parameters:

container (str or Dict[str, Any] or ContainerProxy) – The ID (name) of the container to delete. You can either pass in the ID of the container to delete, a ContainerProxy instance or a dict representing the properties of the container.

Keyword Arguments:
  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • response_hook (Callable[[Dict[str, str], None], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the container couldn’t be deleted.

Return type:

None

async delete_user(user: str | UserProxy | Mapping[str, Any], **kwargs: Any) None[source]

Delete the specified user from the container.

Parameters:

user (Union[str, Dict[str, Any], UserProxy]) – The ID (name), dict representing the properties or UserProxy instance of the user to be deleted.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], None], None]) – A callable invoked with the response metadata.

Raises:
Return type:

None

get_container_client(container: str | ContainerProxy | Dict[str, Any]) ContainerProxy[source]

Get a ContainerProxy for a container with specified ID (name).

Parameters:

container (Union[str, Dict[str, Any], ContainerProxy]) – The ID (name), dict representing the properties, or ContainerProxy instance of the container to get.

Returns:

A ContainerProxy instance representing the container.

Return type:

ContainerProxy

Example:

Get an existing container, handling a failure if encountered:
        database = client.get_database_client(database_name)
        container = database.get_container_client(container_name)
async get_throughput(**kwargs: Any) ThroughputProperties[source]

Get the ThroughputProperties object for this database.

If no ThroughputProperties already exists for the database, an exception is raised.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], List[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – No throughput properties exist for the database or the throughput properties could not be retrieved.

Returns:

ThroughputProperties for the database.

Return type:

ThroughputProperties

get_user_client(user: str | UserProxy | Mapping[str, Any]) UserProxy[source]

Get a UserProxy for a user with specified ID.

Parameters:

user (Union[str, Dict[str, Any], UserProxy]) – The ID (name), dict representing the properties, or UserProxy instance of the user to get.

Returns:

A UserProxy instance representing the retrieved user.

Return type:

UserProxy

list_containers(*, session_token: str | None = None, max_item_count: int | None = None, initial_headers: Dict[str, str] | None = None, **kwargs) AsyncItemPaged[Dict[str, Any]][source]

List the containers in the database.

Keyword Arguments:
  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • response_hook (Callable[[Dict[str, str], AsyncItemPaged[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of container properties (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

Example:

List all containers in the database:
        database = client.get_database_client(database_name)
        async for container in database.list_containers():
            print("Container ID: {}".format(container['id']))
list_users(*, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

List all the users in the container.

Keyword Arguments:
  • max_item_count (int) – Max number of users to be returned in the enumeration operation.

  • response_hook (Callable[[Dict[str, str], AsyncItemPaged[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of user properties (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

query_containers(query: str, *, parameters: List[Dict[str, Any]] | None = None, session_token: str | None = None, max_item_count: int | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

List the properties for containers in the current database.

Parameters:

query (str) – The Azure Cosmos DB SQL query to execute.

Keyword Arguments:
  • parameters (Optional[List[Dict[str, Any]]]) – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys.

  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • response_hook (Callable[[Dict[str, str], AsyncItemPaged[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of container properties (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

query_users(query: str, *, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

Return all users matching the given query.

Parameters:

query (str) – The Azure Cosmos DB SQL query to execute.

Keyword Arguments:
  • parameters (Optional[List[Dict[str, Any]]]) – Optional array of parameters to the query. Each parameter is a dict() with ‘name’ and ‘value’ keys. Ignored if no query is provided.

  • max_item_count (int) – Max number of users to be returned in the enumeration operation.

  • response_hook (Callable[[Dict[str, str], AsyncItemPaged[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of user properties (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

async read(*, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) Dict[str, Any][source]

Read the database properties.

Keyword Arguments:
  • session_token (str) – Token for use with Session consistency.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the given database couldn’t be retrieved.

Returns:

A dict representing the database properties

Return type:

Dict[str, Any]

async replace_container(container: str | ContainerProxy | Mapping[str, Any], partition_key: PartitionKey, *, indexing_policy: Dict[str, str] | None = None, default_ttl: int | None = None, conflict_resolution_policy: Dict[str, str] | None = None, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, etag: str | None = None, match_condition: MatchConditions | None = None, analytical_storage_ttl: int | None = None, full_text_policy: Dict[str, Any] | None = None, **kwargs: Any) ContainerProxy[source]

Reset the properties of the container.

Property changes are persisted immediately. Any properties not specified will be reset to their default values.

Parameters:
  • container (Union[str, Dict[str, Any], ContainerProxy]) – The ID (name), dict representing the properties or ContainerProxy instance of the container to be replaced.

  • partition_key (PartitionKey) – The partition key to use for the container.

Keyword Arguments:
  • indexing_policy (dict[str, str]) – The indexing policy to apply to the container.

  • default_ttl (int) – Default time to live (TTL) for items in the container. If unspecified, items do not expire.

  • conflict_resolution_policy (dict[str, str]) – The conflict resolution policy to apply to the container.

  • session_token (str) – Token for use with Session consistency.

  • etag (str) – An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

  • match_condition (MatchConditions) – The match condition to use upon the etag.

  • initial_headers (dict[str, str]) – Initial headers to be sent as part of the request.

  • analytical_storage_ttl (int) – Analytical store time to live (TTL) for items in the container. A value of None leaves analytical storage off and a value of -1 turns analytical storage on with no TTL. Please note that analytical storage can only be enabled on Synapse Link enabled accounts.

  • response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

  • full_text_policy (Dict[str, Any]) – provisional The full text policy for the container. Used to denote the default language to be used for all full text indexes, or to individually assign a language to each full text index path.

Returns:

A ContainerProxy instance representing the container after replace completed.

Raises:

CosmosHttpResponseError – Raised if the container couldn’t be replaced. This includes if the container with given id does not exist.

Return type:

ContainerProxy

Example:

Reset the TTL property on a container, and display the updated properties:
        # Set the TTL on the container to 3600 seconds (one hour)
        await database.replace_container(container, partition_key=PartitionKey(path='/productName'), default_ttl=3600)

        # Display the new TTL setting for the container
        container_props = await database.get_container_client(container_name).read()
        print("New container TTL: {}".format(json.dumps(container_props['defaultTtl'])))
async replace_throughput(throughput: int | ThroughputProperties, **kwargs: Any) ThroughputProperties[source]

Replace the database-level throughput.

If no ThroughputProperties already exist for the database, an exception is raised.

Parameters:

throughput (Union[int, ThroughputProperties]) – The throughput to be set.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – No throughput properties exist for the database or the throughput properties could not be updated.

Returns:

ThroughputProperties for the database, updated with new throughput.

Return type:

ThroughputProperties

async replace_user(user: str | UserProxy | Mapping[str, Any], body: Dict[str, Any], **kwargs: Any) UserProxy[source]

Replaces the specified user if it exists in the container.

Parameters:
  • user (Union[str, Dict[str, Any], UserProxy]) – The ID (name), dict representing the properties or UserProxy instance of the user to be replaced.

  • body (Dict[str, Any]) – A dict object representing the user to replace.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the replace operation failed or the user with given ID does not exist.

Returns:

A UserProxy instance representing the user after replace went through.

Return type:

UserProxy

async upsert_user(body: Dict[str, Any], **kwargs: Any) UserProxy[source]

Insert or update the specified user.

If the user already exists in the container, it is replaced. If the user does not already exist, it is inserted.

Parameters:

body (Dict[str, Any]) – A dict-like object representing the user to update or insert.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the given user could not be upserted.

Returns:

A UserProxy instance representing the upserted user.

Return type:

UserProxy

class azure.cosmos.aio.ScriptsProxy(container: ContainerProxy, client_connection: CosmosClientConnection, container_link: str)[source]

An interface to interact with stored procedures.

This class should not be instantiated directly. Instead, use the ContainerProxy.scripts() attribute.

async create_stored_procedure(body: Dict[str, Any], **kwargs: Any) Dict[str, Any][source]

Create a new stored procedure in the container.

To replace an existing stored procedure, use the Container.scripts.replace_stored_procedure() method.

Parameters:

body (Dict[str, Any]) – A dict representing the stored procedure to create.

Raises:

CosmosHttpResponseError – If the given stored procedure couldn’t be created.

Returns:

A dict representing the new stored procedure.

Return type:

Dict[str, Any]

async create_trigger(body: Dict[str, Any], **kwargs: Any) Dict[str, Any][source]

Create a trigger in the container.

To replace an existing trigger, use the ContainerProxy.scripts.replace_trigger() method.

Parameters:

body (Dict[str, Any]) – A dict-like object representing the trigger to create.

Raises:

CosmosHttpResponseError – If the given trigger couldn’t be created.

Returns:

A dict representing the new trigger.

Return type:

Dict[str, Any]

async create_user_defined_function(body: Dict[str, Any], **kwargs: Any) Dict[str, Any][source]

Create a user-defined function in the container.

To replace an existing user-defined function, use the ContainerProxy.scripts.replace_user_defined_function() method.

Parameters:

body (Dict[str, Any]) – A dict-like object representing the user-defined function to create.

Raises:

CosmosHttpResponseError – If the user-defined function couldn’t be created.

Returns:

A dict representing the new user-defined function.

Return type:

Dict[str, Any]

async delete_stored_procedure(sproc: str | Mapping[str, Any], **kwargs: Any) None[source]

Delete a specified stored procedure from the container.

If the stored procedure does not already exist in the container, an exception is raised.

Parameters:

sproc (Union[str, Dict[str, Any]]) – The ID (name) or dict representing stored procedure to be deleted.

Raises:
Return type:

None

async delete_trigger(trigger: str | Mapping[str, Any], **kwargs: Any) None[source]

Delete a specified trigger from the container.

If the trigger does not already exist in the container, an exception is raised.

Parameters:

trigger (Union[str, Dict[str, Any]]) – The ID (name) or dict representing trigger to be deleted.

Raises:
Return type:

None

async delete_user_defined_function(udf: str | Mapping[str, Any], **kwargs: Any) None[source]

Delete a specified user-defined function from the container.

If the user-defined function does not already exist in the container, an exception is raised.

Parameters:

udf (Union[str, Dict[str, Any]]) – The ID (name) or dict representing udf to be deleted.

Raises:
Return type:

None

async execute_stored_procedure(sproc: str | Dict[str, Any], *, partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue] | None = None, parameters: List[Dict[str, Any]] | None = None, enable_script_logging: bool | None = None, **kwargs: Any) Dict[str, Any][source]

Execute a specified stored procedure.

If the stored procedure does not already exist in the container, an exception is raised.

Parameters:

sproc (Union[str, Dict[str, Any]]) – The ID (name) or dict representing the stored procedure to be executed.

Keyword Arguments:
  • partition_key (Union[str, bool, int, float, List[Union[str, bool, int, float]]]) – Specifies the partition key to indicate which partition the stored procedure should execute on.

  • parameters (List[Dict[str, Any]]) – List of parameters to be passed to the stored procedure to be executed.

  • enable_script_logging (bool) – Enables or disables script logging for the current request.

Raises:

CosmosHttpResponseError – If the stored procedure execution failed or if the stored procedure with given id does not exists in the container.

Returns:

Result of the executed stored procedure for the given parameters.

Return type:

Dict[str, Any]

async get_stored_procedure(sproc: str | Mapping[str, Any], **kwargs: Any) Dict[str, Any][source]

Get the stored procedure identified by sproc.

Parameters:

sproc (Union[str, Dict[str, Any]]) – The ID (name) or dict representing the stored procedure to retrieve.

Raises:

CosmosHttpResponseError – If the given stored procedure couldn’t be retrieved.

Returns:

A dict representing the retrieved stored procedure.

Return type:

Dict[str, Any]

async get_trigger(trigger: str | Mapping[str, Any], **kwargs: Any) Dict[str, Any][source]

Get a trigger identified by id.

Parameters:

trigger (Union[str, Dict[str, Any]]) – The ID (name) or dict representing trigger to retrieve.

Raises:

CosmosHttpResponseError – If the given trigger couldn’t be retrieved.

Returns:

A dict representing the retrieved trigger.

Return type:

Dict[str, Any]

async get_user_defined_function(udf: str | Mapping[str, Any], **kwargs: Any) Dict[str, Any][source]

Get a user-defined function identified by id.

Parameters:

udf (Union[str, Dict[str, Any]]) – The ID (name) or dict representing udf to retrieve.

Raises:

CosmosHttpResponseError – If the user-defined function couldn’t be retrieved.

Returns:

A dict representing the retrieved user-defined function.

Return type:

Dict[str, Any]

list_stored_procedures(*, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

List all stored procedures in the container.

Keyword Arguments:

max_item_count (int) – Max number of items to be returned in the enumeration operation.

Returns:

An AsyncItemPaged of stored procedures (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

list_triggers(*, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

List all triggers in the container.

Keyword Arguments:

max_item_count (int) – Max number of items to be returned in the enumeration operation.

Returns:

An AsyncItemPaged of triggers (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

list_user_defined_functions(*, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

List all the user-defined functions in the container.

Keyword Arguments:

max_item_count (int) – Max number of items to be returned in the enumeration operation.

Returns:

An AsyncItemPaged of user-defined functions (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

query_stored_procedures(query: str, *, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

Return all stored procedures matching the given query.

Parameters:

query (str) – The Azure Cosmos DB SQL query to execute.

Keyword Arguments:
  • parameters (List[Dict[str, Any]]) – Optional array of parameters to the query. Ignored if no query is provided.

  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

Returns:

An AsyncItemPaged of stored procedures (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

query_triggers(query: str, *, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

Return all triggers matching the given query.

Parameters:

query (str) – The Azure Cosmos DB SQL query to execute.

Keyword Arguments:
  • parameters (List[Dict[str, Any]]) – Optional array of parameters to the query. Ignored if no query is provided.

  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

Returns:

An AsyncItemPaged of triggers (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

query_user_defined_functions(query: str, *, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

Return user-defined functions matching a given query.

Parameters:

query (str) – The Azure Cosmos DB SQL query to execute.

Keyword Arguments:
  • parameters (List[Dict[str, Any]]) – Optional array of parameters to the query. Ignored if no query is provided.

  • max_item_count (int) – Max number of items to be returned in the enumeration operation.

Returns:

An AsyncItemPaged of user-defined functions (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

async replace_stored_procedure(sproc: str | Mapping[str, Any], body: Dict[str, Any], **kwargs: Any) Dict[str, Any][source]

Replace a specified stored procedure in the container.

If the stored procedure does not already exist in the container, an exception is raised.

Parameters:
  • sproc (Union[str, Dict[str, Any]]) – The ID (name) or dict representing stored procedure to be replaced.

  • body (Dict[str, Any]) – A dict representing the stored procedure to replace.

Raises:

CosmosHttpResponseError – If the replace operation failed or the stored procedure with given id does not exist.

Returns:

A dict representing the stored procedure after replace went through.

Return type:

Dict[str, Any]

async replace_trigger(trigger: str | Mapping[str, Any], body: Dict[str, Any], **kwargs: Any) Dict[str, Any][source]

Replace a specified trigger in the container.

If the trigger does not already exist in the container, an exception is raised.

Parameters:
  • trigger (Union[str, Dict[str, Any]]) – The ID (name) or dict representing trigger to be replaced.

  • body (Dict[str, Any]) – A dict-like object representing the trigger to replace.

Raises:

CosmosHttpResponseError – If the replace operation failed or the trigger with given id does not exist.

Returns:

A dict representing the trigger after replace went through.

Return type:

Dict[str, Any]

async replace_user_defined_function(udf: str | Mapping[str, Any], body: Dict[str, Any], **kwargs: Any) Dict[str, Any][source]

Replace a specified user-defined function in the container.

If the user-defined function does not already exist in the container, an exception is raised.

Parameters:
  • udf (Union[str, Dict[str, Any]]) – The ID (name) or dict representing user-defined function to be replaced.

  • body (Dict[str, Any]) – A dict-like object representing the udf to replace.

Raises:

CosmosHttpResponseError – If the replace operation failed or the user-defined function with the given id does not exist.

Returns:

A dict representing the user-defined function after replace went through.

Return type:

Dict[str, Any]

class azure.cosmos.aio.UserProxy(client_connection: CosmosClientConnection, id: str, database_link: str, properties: Dict[str, Any] | None = None)[source]

An interface to interact with a specific user.

This class should not be instantiated directly. Instead, use the DatabaseProxy.get_user_client() method.

Variables:
async create_permission(body: Dict[str, Any], **kwargs: Any) Permission[source]

Create a permission for the user.

To update or replace an existing permission, use the UserProxy.upsert_permission() method.

Parameters:

body (Dict[str, Any]) – A dict-like object representing the permission to create.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the given permission couldn’t be created.

Returns:

A permission object representing the new permission.

Return type:

Permission

async delete_permission(permission: str | Mapping[str, Any] | Permission, **kwargs: Any) None[source]

Delete the specified permission from the user.

If the permission does not already exist, an exception is raised.

Parameters:

permission (Union[str, Dict[str, Any], Permission]) – The ID (name), dict representing the properties or Permission instance of the permission to be deleted.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], None], None]) – A callable invoked with the response metadata.

Raises:
Return type:

None

async get_permission(permission: str | Mapping[str, Any] | Permission, **kwargs: Any) Permission[source]

Get the permission identified by id.

Parameters:

permission (Union[str, Dict[str, Any], Permission]) – The ID (name), dict representing the properties or Permission instance of the permission to be retrieved.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the given permission couldn’t be retrieved.

Returns:

The retrieved permission object.

Return type:

Permission

list_permissions(*, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

List all permission for the user.

Keyword Arguments:
  • max_item_count (int) – Max number of permissions to be returned in the enumeration operation.

  • response_hook (Callable[[Dict[str, str], AsyncItemPaged[Dict[str, Any]], None]) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of permissions (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

query_permissions(query: str, *, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) AsyncItemPaged[Dict[str, Any]][source]

Return all permissions matching the given query.

Parameters:

query (str) – The Azure Cosmos DB SQL query to execute.

Keyword Arguments:
  • parameters (Optional[List[Dict[str, Any]]]) – Optional array of parameters to the query. Ignored if no query is provided.

  • max_item_count (int) – Max number of permissions to be returned in the enumeration operation.

  • response_hook (Callable[[Dict[str, str], AsyncItemPaged[Dict[str, Any]]], None]) – A callable invoked with the response metadata.

Returns:

An AsyncItemPaged of permissions (dicts).

Return type:

AsyncItemPaged[Dict[str, Any]]

async read(**kwargs: Any) Dict[str, Any][source]

Read user properties.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the given user couldn’t be retrieved.

Returns:

A dictionary of the retrieved user properties.

Return type:

Dict[str, Any]

async replace_permission(permission: str | Mapping[str, Any] | Permission, body: Dict[str, Any], **kwargs: Any) Permission[source]

Replaces the specified permission if it exists for the user.

If the permission does not already exist, an exception is raised.

Parameters:
  • permission (Union[str, Dict[str, Any], Permission]) – The ID (name), dict representing the properties or Permission instance of the permission to be replaced.

  • body (Dict[str, Any]) – A dict-like object representing the permission to replace.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the replace operation failed or the permission with given id does not exist.

Returns:

A permission object representing the permission after the replace operation went through.

Return type:

Permission

async upsert_permission(body: Dict[str, Any], **kwargs: Any) Permission[source]

Insert or update the specified permission.

If the permission already exists in the container, it is replaced. If the permission does not exist, it is inserted.

Parameters:

body (Dict[str, Any]) – A dict-like object representing the permission to update or insert.

Keyword Arguments:

response_hook (Callable[[Dict[str, str], Dict[str, Any]], None]) – A callable invoked with the response metadata.

Raises:

CosmosHttpResponseError – If the given permission could not be upserted.

Returns:

A dict representing the upserted permission.

Return type:

Permission