ContainerProxy Class
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.
Constructor
ContainerProxy(client_connection: CosmosClientConnection, database_link: str, id: str, properties: dict[str, Any] | None = None)
Parameters
| Name | Description |
|---|---|
|
client_connection
Required
|
|
|
database_link
Required
|
|
|
id
Required
|
|
|
properties
|
Default value: None
|
Variables
| Name | Description |
|---|---|
|
id
|
ID (name) of the container. |
|
container_link
|
The URL path of the container. |
Methods
| create_item |
Create an item in the container. To update or replace an existing item, use the upsert_item method. |
| delete_all_items_by_partition_key |
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. |
| delete_conflict |
Delete a specified conflict from the container. If the conflict does not already exist in the container, an exception is raised. |
| delete_item |
Delete the specified item from the container. If the item does not already exist in the container, an exception is raised. |
| execute_item_batch |
Executes the transactional batch for the specified partition key. |
| feed_range_from_partition_key |
Gets the feed range for a given partition key. 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. |
| get_conflict |
Get the conflict identified by conflict. |
| get_latest_session_token |
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 |
| get_throughput |
Get the ThroughputProperties object for this container. If no ThroughputProperties already exist for the container, an exception is raised. |
| is_feed_range_subset |
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 |
List all the conflicts in the container. |
| patch_item |
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. |
| query_conflicts |
Return all conflicts matching a given query. |
| query_items |
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. |
| query_items_change_feed |
Get a sorted list of items that were changed, in the order in which they were modified. |
| read |
Read the container properties. |
| read_all_items |
List all the items in the container. |
| read_feed_ranges |
Obtains a list of feed ranges that can be used to parallelize feed operations. 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. |
| read_item |
Get the item identified by item. |
| read_items |
Reads multiple items from the container. This method is a batched point-read operation. It is more efficient than issuing multiple individual point reads. |
| read_offer |
Get the ThroughputProperties object for this container. If no ThroughputProperties already exist for the container, an exception is raised. |
| replace_item |
Replaces the specified item if it exists in the container. If the item does not already exist in the container, an exception is raised. |
| replace_throughput |
Replace the container's throughput. If no ThroughputProperties already exist for the container, an exception is raised. |
| semantic_rerank |
provisional Rerank a list of documents using semantic reranking. This method uses a semantic reranker to score and reorder the provided documents based on their relevance to the given reranking context. |
| upsert_item |
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. |
create_item
Create an item in the container.
To update or replace an existing item, use the upsert_item method.
create_item(body: dict[str, Any], populate_query_metrics: bool | None = None, 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, priority: Literal['High', 'Low'] | None = None, no_response: bool | None = None, retry_write: int | None = None, throughput_bucket: int | None = None, response_hook: Callable[[Mapping[str, str], dict[str, Any]], None] | None = None, **kwargs: Any) -> CosmosDict
Parameters
| Name | Description |
|---|---|
|
body
Required
|
A dict-like object representing the item to create. |
|
pre_trigger_include
|
trigger id to be used as pre operation trigger. Default value: None
|
|
post_trigger_include
|
trigger id to be used as post operation trigger. Default value: None
|
|
indexing_directive
|
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. Default value: None
|
|
populate_query_metrics
|
Default value: None
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
enable_automatic_id_generation
|
Enable automatic id generation if no id present. Default value: False
|
|
session_token
|
Token for use with Session consistency. Default value: None
|
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
|
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. Default value: None
|
|
no_response
|
Indicates whether service should be instructed to skip sending response payloads. When not specified explicitly here, the default value will be determined from kwargs or when also not specified there from client-level kwargs. Default value: None
|
|
retry_write
|
Indicates how many times the SDK should automatically retry this write operation, even if the operation is not guaranteed to be idempotent. This should only be enabled if the application can tolerate such risks or has logic to safely detect and handle duplicate operations. Default is None (no retries). Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
Returns
| Type | Description |
|---|---|
|
A CosmosDict representing the new item. The dict will be empty if no_response is specified. |
Exceptions
| Type | Description |
|---|---|
|
Item with the given ID already exists. |
delete_all_items_by_partition_key
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.
delete_all_items_by_partition_key(partition_key: None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined | Sequence[None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined], *, pre_trigger_include: str | None = None, post_trigger_include: str | None = None, session_token: str | None = None, throughput_bucket: int | None = None, response_hook: Callable[[Mapping[str, str], None], None] | None = None, **kwargs: Any) -> None
Parameters
| Name | Description |
|---|---|
|
partition_key
Required
|
<xref:azure.cosmos.partition_key.PartitionKeyType>
Partition key for the items to be deleted. If the partition key is set to None, it will try to delete the items with a partition key of null. To learn more about using partition keys, see here. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
pre_trigger_include
|
trigger id to be used as pre operation trigger. Default value: None
|
|
post_trigger_include
|
trigger id to be used as post operation trigger. Default value: None
|
|
session_token
|
Token for use with Session consistency. Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
Returns
| Type | Description |
|---|---|
delete_conflict
Delete a specified conflict from the container.
If the conflict does not already exist in the container, an exception is raised.
delete_conflict(conflict: str | Mapping[str, Any], partition_key: None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined | Sequence[None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined], **kwargs: Any) -> None
Parameters
| Name | Description |
|---|---|
|
conflict
Required
|
The ID (name) or dict representing the conflict to be deleted. |
|
partition_key
Required
|
<xref:azure.cosmos.partition_key.PartitionKeyType>
Partition key for the conflict to delete. If the partition key is set to None, it will try to delete a conflict with a partition key value of null. To learn more about using partition keys, see here. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
response_hook
|
A callable invoked with the response metadata. |
Returns
| Type | Description |
|---|---|
Exceptions
| Type | Description |
|---|---|
|
The conflict wasn't deleted successfully. |
|
|
The conflict does not exist in the container. |
delete_item
Delete the specified item from the container.
If the item does not already exist in the container, an exception is raised.
delete_item(item: Mapping[str, Any] | str, partition_key: None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined | Sequence[None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined], populate_query_metrics: bool | None = None, 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, retry_write: int | None = None, throughput_bucket: int | None = None, response_hook: Callable[[Mapping[str, str], None], None] | None = None, **kwargs: Any) -> None
Parameters
| Name | Description |
|---|---|
|
item
Required
|
The ID (name) or dict representing item to be deleted. |
|
partition_key
Required
|
<xref:azure.cosmos.partition_key.PartitionKeyType>
Specifies the partition key value for the item. If the partition key is set to None, it will try to delete an item with a partition key value of null. To learn more about using partition keys, see here. |
|
pre_trigger_include
|
trigger id to be used as pre operation trigger. Default value: None
|
|
post_trigger_include
|
trigger id to be used as post operation trigger. Default value: None
|
|
populate_query_metrics
|
Default value: None
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
session_token
|
Token for use with Session consistency. Default value: None
|
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
etag
|
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. Default value: None
|
|
match_condition
|
The match condition to use upon the etag. Default value: None
|
|
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. Default value: None
|
|
retry_write
|
Indicates how many times the SDK should automatically retry this write operation, even if the operation is not guaranteed to be idempotent. This should only be enabled if the application can tolerate such risks or has logic to safely detect and handle duplicate operations. Default is None (no retries). Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
Returns
| Type | Description |
|---|---|
Exceptions
| Type | Description |
|---|---|
|
The item wasn't deleted successfully. |
|
|
The item does not exist in the container. |
execute_item_batch
Executes the transactional batch for the specified partition key.
execute_item_batch(batch_operations: Sequence[Tuple[str, Tuple[Any, ...]] | Tuple[str, Tuple[Any, ...], dict[str, Any]]], partition_key: None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined | Sequence[None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined], *, pre_trigger_include: str | None = None, post_trigger_include: str | None = None, session_token: str | None = None, priority: Literal['High', 'Low'] | None = None, throughput_bucket: int | None = None, response_hook: Callable[[Mapping[str, str], list[dict[str, Any]]], None] | None = None, **kwargs: Any) -> CosmosList
Parameters
| Name | Description |
|---|---|
|
batch_operations
Required
|
The batch of operations to be executed. |
|
partition_key
Required
|
<xref:azure.cosmos.partition_key.PartitionKeyType>
The partition key value of the batch operations. If the partition key is set to None, it will try to execute batch on an item with a partition key value of null. To learn more about using partition keys, see here. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
pre_trigger_include
|
trigger id to be used as pre operation trigger. Default value: None
|
|
post_trigger_include
|
trigger id to be used as post operation trigger. Default value: None
|
|
session_token
|
Token for use with Session consistency. Default value: None
|
|
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. Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
Returns
| Type | Description |
|---|---|
|
A CosmosList representing the items after the batch operations went through. |
Exceptions
| Type | Description |
|---|---|
|
The batch failed to execute. |
|
|
A transactional batch operation failed in the batch. |
feed_range_from_partition_key
Gets the feed range for a given partition key.
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.
feed_range_from_partition_key(partition_key: None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined | Sequence[None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined]) -> dict[str, Any]
Parameters
| Name | Description |
|---|---|
|
partition_key
Required
|
<xref:PartitionKeyType>
Partition key value used to derive the feed range. If set to |
Returns
| Type | Description |
|---|---|
|
A feed range corresponding to the supplied partition key value. |
get_conflict
Get the conflict identified by conflict.
get_conflict(conflict: str | Mapping[str, Any], partition_key: None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined | Sequence[None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined], **kwargs: Any) -> CosmosDict
Parameters
| Name | Description |
|---|---|
|
conflict
Required
|
The ID (name) or dict representing the conflict to retrieve. |
|
partition_key
Required
|
<xref:azure.cosmos.partition_key.PartitionKeyType>
Partition key for the conflict to retrieve. If the partition key is set to None, it will try to fetch a conflict with a partition key of null. To learn more about using partition keys, see here. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
response_hook
|
A callable invoked with the response metadata. |
Returns
| Type | Description |
|---|---|
|
A CosmosDict representing the retrieved conflict. |
Exceptions
| Type | Description |
|---|---|
|
The given conflict couldn't be retrieved. |
get_latest_session_token
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
get_latest_session_token(feed_ranges_to_session_tokens: list[Tuple[dict[str, Any], str]], target_feed_range: dict[str, Any]) -> str
Parameters
| Name | Description |
|---|---|
|
feed_ranges_to_session_tokens
Required
|
|
|
target_feed_range
Required
|
|
get_throughput
Get the ThroughputProperties object for this container.
If no ThroughputProperties already exist for the container, an exception is raised.
get_throughput(*, response_hook: Callable[[Mapping[str, Any], list[dict[str, Any]]], None] | None = None, **kwargs: Any) -> ThroughputProperties
Keyword-Only Parameters
| Name | Description |
|---|---|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
Returns
| Type | Description |
|---|---|
|
Throughput for the container. |
Exceptions
| Type | Description |
|---|---|
|
No throughput properties exists for the container or the throughput properties could not be retrieved. |
is_feed_range_subset
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.
is_feed_range_subset(parent_feed_range: dict[str, Any], child_feed_range: dict[str, Any]) -> bool
Parameters
| Name | Description |
|---|---|
|
parent_feed_range
Required
|
|
|
child_feed_range
Required
|
|
list_conflicts
List all the conflicts in the container.
list_conflicts(max_item_count: int | None = None, *, response_hook: Callable[[Mapping[str, Any], ItemPaged[dict[str, Any]]], None] | None = None, **kwargs: Any) -> ItemPaged[dict[str, Any]]
Parameters
| Name | Description |
|---|---|
|
max_item_count
|
Max number of items to be returned in the enumeration operation. Default value: None
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
Returns
| Type | Description |
|---|---|
|
An Iterable of conflicts (dicts). |
patch_item
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.
patch_item(item: str | dict[str, Any], partition_key: None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined | Sequence[None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined], 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, retry_write: int | None = None, throughput_bucket: int | None = None, response_hook: Callable[[Mapping[str, str], dict[str, Any]], None] | None = None, **kwargs: Any) -> CosmosDict
Parameters
| Name | Description |
|---|---|
|
item
Required
|
The ID (name) or dict representing item to be patched. |
|
partition_key
Required
|
<xref:azure.cosmos.partition_key.PartitionKeyType>
The partition key of the object to patch. If the partition key is set to None, it will try to patch an item with a partition key value of null. To learn more about using partition keys, see here. |
|
patch_operations
Required
|
The list of patch operations to apply to the item. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
filter_predicate
|
conditional filter to apply to Patch operations. Default value: None
|
|
pre_trigger_include
|
trigger id to be used as pre operation trigger. Default value: None
|
|
post_trigger_include
|
trigger id to be used as post operation trigger. Default value: None
|
|
session_token
|
Token for use with Session consistency. Default value: None
|
|
etag
|
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. Default value: None
|
|
match_condition
|
The match condition to use upon the etag. Default value: None
|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
|
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. Default value: None
|
|
no_response
|
Indicates whether service should be instructed to skip sending response payloads. When not specified explicitly here, the default value will be determined from kwargs or when also not specified there from client-level kwargs. Default value: None
|
|
retry_write
|
Indicates how many times the SDK should automatically retry this write operation, even if the operation is not guaranteed to be idempotent. This should only be enabled if the application can tolerate such risks or has logic to safely detect and handle duplicate operations. Default is None (no retries). Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
Returns
| Type | Description |
|---|---|
|
A CosmosDict representing the item after the patch operations went through. The dict will be empty if no_response is specified. |
Exceptions
| Type | Description |
|---|---|
|
The patch operations failed or the item with given id does not exist. |
query_conflicts
Return all conflicts matching a given query.
query_conflicts(query: str, parameters: list[dict[str, object]] | None = None, enable_cross_partition_query: bool | None = None, partition_key: None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined | Sequence[None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined] = None, max_item_count: int | None = None, *, response_hook: Callable[[Mapping[str, Any], ItemPaged[dict[str, Any]]], None] | None = None, **kwargs: Any) -> ItemPaged[dict[str, Any]]
Parameters
| Name | Description |
|---|---|
|
query
Required
|
The Azure Cosmos DB SQL query to execute. |
|
parameters
|
Optional array of parameters to the query. Ignored if no query is provided. Default value: None
|
|
enable_cross_partition_query
|
Allows sending of more than one request to execute the query in the Azure Cosmos DB service. More than one request is necessary if the query is not scoped to single partition key value. Default value: None
|
|
partition_key
|
<xref:azure.cosmos.partition_key.PartitionKeyType>
Specifies the partition key value for the item. If the partition key is set to None, it will perform a cross partition query. To learn more about using partition keys, see here. Default value: None
|
|
max_item_count
|
Max number of items to be returned in the enumeration operation. Default value: None
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
Returns
| Type | Description |
|---|---|
|
An Iterable of conflicts (dicts). |
query_items
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.
query_items(query: str, parameters: list[dict[str, object]] | None = None, partition_key: PartitionKeyType | None = None, enable_cross_partition_query: bool | None = None, max_item_count: int | None = None, enable_scan_in_query: bool | None = None, populate_query_metrics: bool | None = None, *, continuation_token_limit: int | None = None, initial_headers: dict[str, str] | None = None, max_integrated_cache_staleness_in_ms: int | None = None, populate_index_metrics: bool | None = None, priority: Literal['High', 'Low'] | None = None, response_hook: Callable[[Mapping[str, str], dict[str, Any]], None] | None = None, session_token: str | None = None, throughput_bucket: int | None = None, **kwargs: Any) -> ItemPaged[dict[str, Any]]
Parameters
| Name | Description |
|---|---|
|
args
Required
|
args |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
continuation_token_limit
|
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). |
|
enable_cross_partition_query
|
Allows sending of more than one request to execute the query in the Azure Cosmos DB service. More than one request is necessary if the query is not scoped to single partition key value. |
|
enable_scan_in_query
|
Allow scan on the queries which couldn't be served as indexing was opted out on the requested paths. |
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the Azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
|
feed_range
|
The feed range that is used to define the scope. |
|
initial_headers
|
Initial headers to be sent as part of the request. |
|
max_integrated_cache_staleness_in_ms
|
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. |
|
max_item_count
|
Max number of items to be returned in the enumeration operation. |
|
parameters
|
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
|
<xref:azure.cosmos.partition_key.PartitionKeyType>
Partition key at which the query request is targeted. If the partition key is set to None, it will perform a cross partition query. To learn more about using partition keys, see here. |
|
populate_index_metrics
|
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 option will incur overhead, so it should be enabled only when debugging slow queries. |
|
populate_query_metrics
|
Enable returning query metrics in response headers. |
|
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. |
|
query
|
The Azure Cosmos DB SQL query to execute. |
|
response_hook
|
A callable invoked with the response metadata. |
|
session_token
|
Token for use with Session consistency. |
|
throughput_bucket
|
The desired throughput bucket for the client. |
Returns
| Type | Description |
|---|---|
|
An Iterable of items (dicts). |
Examples
Get all products that have not been discontinued:
import json
for queried_item in container.query_items(
query='SELECT * FROM products p WHERE p.productModel <> "DISCONTINUED"',
enable_cross_partition_query=True,
):
print(json.dumps(queried_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")],
)
for discontinued_item in discontinued_items:
print(json.dumps(discontinued_item, indent=True))
query_items_change_feed
Get a sorted list of items that were changed, in the order in which they were modified.
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, mode: Literal['LatestVersion', 'AllVersionsAndDeletes'] | None = None, response_hook: Callable[[Mapping[str, str], dict[str, Any]], None] | None = None, **kwargs: Any) -> ItemPaged[dict[str, Any]]
Parameters
| Name | Description |
|---|---|
|
args
Required
|
args |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
continuation
|
The continuation token retrieved from previous response. It contains chang feed mode. |
|
feed_range
|
The feed range that is used to define the scope. |
|
partition_key
|
<xref:azure.cosmos.partition_key.PartitionKeyType>
The partition key that is used to define the scope (logical partition or a subset of a container). If the partition key is set to None, it will try to fetch the changes for an item with a partition key value of null. To learn more about using partition keys, see here. |
|
max_item_count
|
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. |
|
mode
|
Literal["LatestVersion", "AllVersionsAndDeletes"]
The modes to query change feed. If continuation was passed, 'mode' argument will be ignored. LATEST_VERSION: Query latest items from 'start_time' or 'continuation' token. ALL_VERSIONS_AND_DELETES: Query all versions and deleted items from either start_time='Now' or 'continuation' token. |
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
|
response_hook
|
A callable invoked with the response metadata. |
Returns
| Type | Description |
|---|---|
|
An Iterable of items (dicts). |
read
Read the container properties.
read(populate_query_metrics: bool | None = None, populate_partition_key_range_statistics: bool | None = None, populate_quota_info: bool | None = None, *, priority: Literal['High', 'Low'] | None = None, initial_headers: dict[str, str] | None = None, response_hook: Callable[[Mapping[str, str], dict[str, Any]], None] | None = None, **kwargs: Any) -> CosmosDict
Parameters
| Name | Description |
|---|---|
|
populate_partition_key_range_statistics
|
Enable returning partition key range statistics in response headers. Default value: None
|
|
populate_quota_info
|
Enable returning collection storage quota information in response headers. Default value: None
|
|
populate_query_metrics
|
Default value: None
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
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. Default value: None
|
|
initial_headers
|
Initial headers to be sent as part of the request. |
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
Returns
| Type | Description |
|---|---|
|
Dict representing the retrieved container. |
Exceptions
| Type | Description |
|---|---|
|
Raised if the container couldn't be retrieved. This includes if the container does not exist. |
read_all_items
List all the items in the container.
read_all_items(max_item_count: int | None = None, populate_query_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, throughput_bucket: int | None = None, response_hook: Callable[[Mapping[str, str], dict[str, Any]], None] | None = None, **kwargs: Any) -> ItemPaged[dict[str, Any]]
Parameters
| Name | Description |
|---|---|
|
max_item_count
|
Max number of items to be returned in the enumeration operation. Default value: None
|
|
populate_query_metrics
|
Default value: None
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
session_token
|
Token for use with Session consistency. Default value: None
|
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
|
max_integrated_cache_staleness_in_ms
|
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. Default value: None
|
|
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. Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
Returns
| Type | Description |
|---|---|
|
An Iterable of items (dicts). |
read_feed_ranges
Obtains a list of feed ranges that can be used to parallelize feed operations.
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.
read_feed_ranges(*, force_refresh: bool = False, **kwargs: Any) -> Iterable[dict[str, Any]]
Keyword-Only Parameters
| Name | Description |
|---|---|
|
force_refresh
|
Flag to indicate whether obtain the list of feed ranges directly from cache or refresh the cache. Default value: False
|
Returns
| Type | Description |
|---|---|
|
A list representing the feed ranges in base64 encoded string |
read_item
Get the item identified by item.
read_item(item: str | Mapping[str, Any], partition_key: None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined | Sequence[None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined], populate_query_metrics: bool | None = None, 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, throughput_bucket: int | None = None, response_hook: Callable[[Mapping[str, str], dict[str, Any]], None] | None = None, **kwargs: Any) -> CosmosDict
Parameters
| Name | Description |
|---|---|
|
item
Required
|
The ID (name) or dict representing item to retrieve. |
|
partition_key
Required
|
<xref:azure.cosmos.partition_key.PartitionKeyType>
Partition key for the item to retrieve. If the partition key is set to None, it will try to fetch an item with a partition key of null. To learn more about using partition keys, see here. |
|
post_trigger_include
|
trigger id to be used as post operation trigger. Default value: None
|
|
populate_query_metrics
|
Default value: None
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
session_token
|
Token for use with Session consistency. Default value: None
|
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
|
max_integrated_cache_staleness_in_ms
|
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. Default value: None
|
|
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. Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
Returns
| Type | Description |
|---|---|
|
A CosmosDict representing the item to be retrieved. |
Exceptions
| Type | Description |
|---|---|
|
The given item couldn't be retrieved. |
Examples
Get an item from the database and update one of its properties:
item = container.read_item("item2", partition_key="Widget")
item["productModel"] = "DISCONTINUED"
updated_item = container.upsert_item(item)
read_items
Reads multiple items from the container.
This method is a batched point-read operation. It is more efficient than issuing multiple individual point reads.
read_items(items: Sequence[Tuple[str, None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined | Sequence[None | bool | float | int | str | Type[NonePartitionKeyValue] | Type[NullPartitionKeyValue] | _Empty | _Undefined]]], *, executor: ThreadPoolExecutor | None = None, max_concurrency: int | None = None, consistency_level: str | None = None, session_token: str | None = None, initial_headers: dict[str, str] | None = None, excluded_locations: list[str] | None = None, priority: Literal['High', 'Low'] | None = None, throughput_bucket: int | None = None, **kwargs: Any) -> CosmosList
Parameters
| Name | Description |
|---|---|
|
items
Required
|
A list of tuples, where each tuple contains an item's ID and partition key. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
executor
|
Optional ThreadPoolExecutor for handling concurrent operations. If not provided, a new executor will be created as needed. Default value: None
|
|
max_concurrency
|
The maximum number of concurrent operations for the items request. This value is ignored if an executor is provided. If not specified, the default max_concurrency defined by Python's ThreadPoolExecutor will be applied. Default value: None
|
|
consistency_level
|
The consistency level to use for the request. Default value: None
|
|
session_token
|
Token for use with Session consistency. Default value: None
|
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. Default value: None
|
|
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. Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
Returns
| Type | Description |
|---|---|
|
A CosmosList containing the retrieved items. Items that were not found are omitted from the list. |
Exceptions
| Type | Description |
|---|---|
|
The read-many operation failed. |
read_offer
Get the ThroughputProperties object for this container. If no ThroughputProperties already exist for the container, an exception is raised.
read_offer(**kwargs: Any) -> ThroughputProperties
Keyword-Only Parameters
| Name | Description |
|---|---|
|
response_hook
|
A callable invoked with the response metadata. |
Returns
| Type | Description |
|---|---|
|
Throughput for the container. |
Exceptions
| Type | Description |
|---|---|
|
No throughput properties exists for the container or the throughput properties could not be retrieved. |
replace_item
Replaces the specified item if it exists in the container.
If the item does not already exist in the container, an exception is raised.
replace_item(item: str | Mapping[str, Any], body: dict[str, Any], populate_query_metrics: bool | None = None, 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, retry_write: int | None = None, throughput_bucket: int | None = None, response_hook: Callable[[Mapping[str, str], dict[str, Any]], None] | None = None, **kwargs: Any) -> CosmosDict
Parameters
| Name | Description |
|---|---|
|
item
Required
|
The ID (name) or dict representing item to be replaced. |
|
body
Required
|
A dict representing the item to replace. |
|
pre_trigger_include
|
trigger id to be used as pre operation trigger. Default value: None
|
|
post_trigger_include
|
trigger id to be used as post operation trigger. Default value: None
|
|
populate_query_metrics
|
Default value: None
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
session_token
|
Token for use with Session consistency. Default value: None
|
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
etag
|
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. Default value: None
|
|
match_condition
|
The match condition to use upon the etag. Default value: None
|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
|
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. Default value: None
|
|
no_response
|
Indicates whether service should be instructed to skip sending response payloads. When not specified explicitly here, the default value will be determined from kwargs or when also not specified there from client-level kwargs. Default value: None
|
|
retry_write
|
Indicates how many times the SDK should automatically retry this write operation, even if the operation is not guaranteed to be idempotent. This should only be enabled if the application can tolerate such risks or has logic to safely detect and handle duplicate operations. Default is None (no retries). Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
Returns
| Type | Description |
|---|---|
|
A CosmosDict representing the item after replace went through. The dict will be empty if no_response is specified. |
Exceptions
| Type | Description |
|---|---|
|
The replace operation failed or the item with given id does not exist. |
replace_throughput
Replace the container's throughput.
If no ThroughputProperties already exist for the container, an exception is raised.
replace_throughput(throughput: int | ThroughputProperties, *, response_hook: Callable[[Mapping[str, Any], CosmosDict], None] | None = None, **kwargs: Any) -> ThroughputProperties
Parameters
| Name | Description |
|---|---|
|
throughput
Required
|
The throughput to be set. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
Returns
| Type | Description |
|---|---|
|
ThroughputProperties for the container, updated with new throughput. |
Exceptions
| Type | Description |
|---|---|
|
No throughput properties exist for the container or the throughput properties could not be updated. |
semantic_rerank
provisional Rerank a list of documents using semantic reranking.
This method uses a semantic reranker to score and reorder the provided documents based on their relevance to the given reranking context.
semantic_rerank(*, context: str, documents: list[str], options: dict[str, Any] | None = None) -> CosmosDict
Keyword-Only Parameters
| Name | Description |
|---|---|
|
context
|
The reranking context or query string to use for reranking the documents. |
|
documents
|
A list of documents (as strings) to be reranked. |
|
options
|
Optional dictionary of additional request options to customize the semantic reranking process. Supported options:
Default value: None
|
Returns
| Type | Description |
|---|---|
|
A CosmosDict containing the reranking results. The structure typically includes results list with reranked documents and their relevance scores. Each result contains index, relevance_score, and optionally document. |
Exceptions
| Type | Description |
|---|---|
|
If the semantic reranking operation fails. |
upsert_item
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.
upsert_item(body: dict[str, Any], populate_query_metrics: bool | None = None, 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, retry_write: int | None = None, throughput_bucket: int | None = None, response_hook: Callable[[Mapping[str, str], dict[str, Any]], None] | None = None, **kwargs: Any) -> CosmosDict
Parameters
| Name | Description |
|---|---|
|
body
Required
|
A dict-like object representing the item to update or insert. |
|
pre_trigger_include
|
trigger id to be used as pre operation trigger. Default value: None
|
|
post_trigger_include
|
trigger id to be used as post operation trigger. Default value: None
|
|
populate_query_metrics
|
Default value: None
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
session_token
|
Token for use with Session consistency. Default value: None
|
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
etag
|
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. Default value: None
|
|
match_condition
|
The match condition to use upon the etag. Default value: None
|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
|
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. Default value: None
|
|
no_response
|
Indicates whether service should be instructed to skip sending response payloads. When not specified explicitly here, the default value will be determined from kwargs or when also not specified there from client-level kwargs. Default value: None
|
|
retry_write
|
Indicates how many times the SDK should automatically retry this write operation, even if the operation is not guaranteed to be idempotent. This should only be enabled if the application can tolerate such risks or has logic to safely detect and handle duplicate operations. Default is None (no retries). Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
|
excluded_locations
|
Excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. This excluded_location will override existing excluded_locations in client level. |
Returns
| Type | Description |
|---|---|
|
A CosmosDict representing the upserted item. The dict will be empty if no_response is specified. |
Exceptions
| Type | Description |
|---|---|
|
The given item could not be upserted. |