azure.cosmos package¶
- class azure.cosmos.ConnectionRetryPolicy(**kwargs)[source]¶
-
- get_retry_after(response: PipelineResponse[Any, AllHttpResponseType]) float | None ¶
Get the value of Retry-After in seconds.
- Parameters:
response (PipelineResponse) – The PipelineResponse object
- Returns:
Value of Retry-After in seconds.
- Return type:
float or None
- increment(settings: Dict[str, Any], response: PipelineRequest[HTTPRequestType] | PipelineResponse[HTTPRequestType, AllHttpResponseType] | None = None, error: Exception | None = None) bool ¶
Increment the retry counters.
- Parameters:
settings (dict) – The retry settings.
response (PipelineResponse) – A pipeline response object.
error (AzureError) – An error encountered during the request, or None if the response was received successfully.
- Returns:
Whether any retry attempt is available True if more retry attempts available, False otherwise
- Return type:
- is_retry(settings: Dict[str, Any], response: PipelineResponse[HTTPRequestType, AllHttpResponseType]) bool ¶
Checks if method/status code is retryable.
Based on allowlists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upon on the presence of the aforementioned header.
The behavior is: - If status_code < 400: don’t retry - Else if Retry-After present: retry - Else: retry based on the safe status code list ([408, 429, 500, 502, 503, 504])
- Parameters:
settings (dict) – The retry settings.
response (PipelineResponse) – The PipelineResponse object
- Returns:
True if method/status code is retryable. False if not retryable.
- Return type:
- classmethod no_retries() ClsRetryPolicy ¶
Disable retries.
- Returns:
A retry policy with retries disabled.
- Return type:
- send(request)[source]¶
Sends the PipelineRequest object to the next policy. Uses retry settings if necessary. Also enforces an absolute client-side timeout that spans multiple retry attempts.
- Parameters:
request (PipelineRequest) – The PipelineRequest object
- Returns:
Returns the PipelineResponse or raises error if maximum retries exceeded.
- Return type:
- Raises:
AzureError – Maximum retries exceeded.
CosmosClientTimeoutError – Specified timeout exceeded.
ClientAuthenticationError – Authentication failed.
- sleep(settings: Dict[str, Any], transport: HttpTransport[HTTPRequestType, HTTPResponseType], response: PipelineResponse[HTTPRequestType, HTTPResponseType] | None = None) None ¶
Sleep between retry attempts.
This method will respect a server’s
Retry-After
response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and this method will return immediately.- Parameters:
settings (dict) – The retry settings.
transport (HttpTransport) – The HTTP transport type.
response (PipelineResponse) – The PipelineResponse object.
- update_context(context: PipelineContext, retry_settings: Dict[str, Any]) None ¶
Updates retry history in pipeline context.
- Parameters:
context (PipelineContext) – The pipeline context.
retry_settings (dict) – The retry settings.
- BACKOFF_MAX = 120¶
Maximum backoff time.
- next: HTTPPolicy[HTTPRequestType, HTTPResponseType]¶
Pointer to the next policy or a transport (wrapped as a policy). Will be set at pipeline creation.
- class azure.cosmos.ConsistencyLevel[source]¶
Represents the consistency levels supported for Azure Cosmos client operations.
The requested ConsistencyLevel must match or be weaker than that provisioned for the database account. Consistency levels.
Consistency levels by order of strength are Strong, BoundedStaleness, Session, ConsistentPrefix and Eventual.
- BoundedStaleness: Literal['BoundedStaleness'] = 'BoundedStaleness'¶
Bounded Staleness guarantees that reads are not too out-of-date. This can be configured based on number of operations (MaxStalenessPrefix) or time (MaxStalenessIntervalInSeconds).
- ConsistentPrefix: Literal['ConsistentPrefix'] = 'ConsistentPrefix'¶
ConsistentPrefix Consistency guarantees that reads will return some prefix of all writes with no gaps. All writes will be eventually be available for reads.
- Eventual: Literal['Eventual'] = 'Eventual'¶
Eventual Consistency guarantees that reads will return a subset of writes. All writes will be eventually be available for reads.
- class azure.cosmos.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 thecreate_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:
- 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, etag: str | None = None, match_condition: MatchConditions | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) Dict[str, Any] [source]¶
Create an item in the container.
To update or replace an existing item, use the
ContainerProxy.upsert_item()
method.- Parameters:
body (Dict[str, Any]) – A dict-like object representing the item to create.
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.
- Keyword Arguments:
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) – 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.
- Returns:
A dict representing the new item.
- Raises:
CosmosHttpResponseError – Item with the given ID already exists.
- Return type:
Dict[str, Any]
- 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, List[Union[str, int, float, bool]]]) – 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
- 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:
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Raises:
CosmosHttpResponseError – The conflict wasn’t deleted successfully.
CosmosResourceNotFoundError – The conflict does not exist in the container.
- Return type:
None
- delete_item(item: Mapping[str, Any] | str, partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], 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, **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, List[Union[str, int, float, bool]]]) – Specifies the partition key value for the item.
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.
- 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.
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.
- Raises:
CosmosHttpResponseError – The item wasn’t deleted successfully.
CosmosResourceNotFoundError – The item does not exist in the container.
- Return type:
None
- 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) List[Dict[str, Any]] [source]¶
Executes the transactional batch for the specified partition key.
- Parameters:
- 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 list representing the item after the batch operations went through.
- Raises:
CosmosHttpResponseError – The batch failed to execute.
CosmosBatchOperationError – A transactional batch operation failed in the batch.
- Return type:
List[Dict[str, Any]]
- 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:
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
A dict representing the retrieved conflict.
- Raises:
CosmosHttpResponseError – The given conflict couldn’t be retrieved.
- Return type:
Dict[str, Any]
- get_throughput(**kwargs: Any) ThroughputProperties [source]¶
Get the ThroughputProperties object for this container.
If no ThroughputProperties already exist for the container, an exception is raised.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
Throughput for the container.
- Raises:
CosmosHttpResponseError – No throughput properties exists for the container or the throughput properties could not be retrieved.
- Return type:
- list_conflicts(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all the conflicts in the container.
- 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, **kwargs: Any) Dict[str, Any] [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, List[Union[str, int, float, bool]]]) – 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.
- Returns:
A dict representing the item after the patch operations went through.
- Raises:
CosmosHttpResponseError – The patch operations failed or the item with given id does not exist.
- Return type:
- query_conflicts(query: str, parameters: List[Dict[str, object]] | None = None, enable_cross_partition_query: bool | 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) ItemPaged[Dict[str, Any]] [source]¶
Return all conflicts matching a given query.
- Parameters:
query (str) – The Azure Cosmos DB SQL query to execute.
parameters (List[Dict[str, object]]) – Optional array of parameters to the query. Ignored if no query is provided.
enable_cross_partition_query (bool) – 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.
partition_key (Union[str, int, float, bool, List[Union[str, int, float, bool]]]) – Specifies the partition key value for the item.
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
An Iterable of conflicts (dicts).
- Return type:
Iterable[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, 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, *, 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) ItemPaged[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.
parameters ([List[Dict[str, object]]]) – 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, List[Union[str, int, float, bool]]]) – partition key at which the query request is targeted.
enable_cross_partition_query (bool) – 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.
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.
- 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) – 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.
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.
- Returns:
An Iterable of items (dicts).
- Return type:
ItemPaged[Dict[str, Any]]
Example:
import json for item in container.query_items( query='SELECT * FROM products p WHERE p.productModel <> "DISCONTINUED"', enable_cross_partition_query=True, ): print(json.dumps(item, indent=True))
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 item in discontinued_items: print(json.dumps(item, indent=True))
- query_items_change_feed(partition_key_range_id: str | None = None, is_start_from_beginning: bool = False, continuation: str | None = None, max_item_count: int | None = None, *, start_time: datetime | None = None, partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue] | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Get a sorted list of items that were changed, in the order in which they were modified.
- Parameters:
partition_key_range_id (str) – ChangeFeed requests can be executed against specific partition key ranges. This is used to process the change feed in parallel across multiple consumers.
is_start_from_beginning (bool) – Get whether change feed should start from beginning (true) or from current (false). By default, it’s start from current (false).
max_item_count (int) – Max number of items to be returned in the enumeration operation.
continuation (str) – e_tag value to be used as continuation for reading change feed.
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments:
start_time (datetime) – Specifies a point of time to start change feed. Provided value will be converted to UTC. This value will be ignored if is_start_from_beginning is set to true.
partition_key (Union[str, int, float, bool, List[Union[str, int, float, bool]]]) – partition key at which ChangeFeed requests are targeted.
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.
- Returns:
An Iterable of items (dicts).
- Return type:
- read(populate_query_metrics: bool | None = None, 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.
- Parameters:
- 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.
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.
initial_headers – Initial headers to be sent as part of the request.
response_hook (Callable) – A callable invoked with the response metadata.
- 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:
- 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, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all the items in the container.
- Parameters:
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- 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) – 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 Iterable of items (dicts).
- Return type:
Iterable[Dict[str, Any]]
- read_item(item: str | Mapping[str, Any], partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], 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, **kwargs: Any) Dict[str, Any] [source]¶
Get the item identified by item.
- Parameters:
- 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) – 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:
Dict representing the item to be retrieved.
- Raises:
CosmosHttpResponseError – The given item couldn’t be retrieved.
- Return type:
Example:
item = container.read_item("item2", partition_key="Widget") item["productModel"] = "DISCONTINUED" updated_item = container.upsert_item(item)
- read_offer(**kwargs: Any) ThroughputProperties [source]¶
Get the ThroughputProperties object for this container. If no ThroughputProperties already exist for the container, an exception is raised.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
Throughput for the container.
- Raises:
CosmosHttpResponseError – No throughput properties exists for the container or the throughput properties could not be retrieved.
- Return type:
- 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, **kwargs: Any) Dict[str, Any] [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.
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.
- 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) – 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.
- Returns:
A dict representing the item after replace went through.
- Raises:
CosmosHttpResponseError – The replace operation failed or the item with given id does not exist.
- Return type:
Dict[str, Any]
- 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) – A callable invoked with the response metadata.
- Returns:
ThroughputProperties for the container, updated with new throughput.
- Raises:
CosmosHttpResponseError – No throughput properties exist for the container or the throughput properties could not be updated.
- Return type:
- 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, **kwargs: Any) Dict[str, Any] [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:
- 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) – 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.
- Returns:
A dict representing the upserted item.
- Raises:
CosmosHttpResponseError – The given item could not be upserted.
- Return type:
Dict[str, Any]
- property scripts: ScriptsProxy¶
- class azure.cosmos.CosmosClient(url: str, credential: TokenCredential | str | Dict[str, Any], consistency_level: str | None = None, **kwargs)[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], TokenCredential]) – Can be the account key, or a dictionary of resource tokens.
consistency_level (str) – Consistency level to use for the session. The default value is None (Account level). More on consistency levels and possible values: https://aka.ms/cosmos-consistency-levels
- Keyword Arguments:
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.
Example:
from azure.cosmos import exceptions, CosmosClient, PartitionKey import os url = os.environ["ACCOUNT_URI"] key = os.environ["ACCOUNT_KEY"] client = CosmosClient(url, key)
Instantiate a new CosmosClient.
- create_database(id: str, populate_query_metrics: bool | None = None, 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.
offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.
- 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) – A callable invoked with the response metadata.
- Returns:
A DatabaseProxy instance representing the new database.
- Return type:
- Raises:
CosmosResourceExistsError – Database with the given ID already exists.
Example:
database_name = "testDatabase" try: database = client.create_database(id=database_name) except exceptions.CosmosResourceExistsError: database = client.get_database_client(database=database_name)
- create_database_if_not_exists(id: str, populate_query_metrics: bool | None = None, 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.
populate_query_metrics (bool) – Enable returning query metrics in response headers.
offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.
- 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) – A callable invoked with the response metadata.
- Returns:
A DatabaseProxy instance representing the database.
- Return type:
- Raises:
CosmosHttpResponseError – The database read or creation failed.
- delete_database(database: str | DatabaseProxy | Mapping[str, Any], populate_query_metrics: bool | 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) None [source]¶
Delete the database with the given ID (name).
- Parameters:
database (Union[str, Dict[str, str], DatabaseProxy]) – 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) – 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: TokenCredential | str | Dict[str, Any] | None = None, consistency_level: str | None = None, **kwargs) 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:
- Returns:
A CosmosClient instance representing the new client.
- Return type:
- get_database_account(**kwargs) DatabaseAccount [source]¶
Retrieve the database account information.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
A DatabaseAccount instance representing the Cosmos DB Database Account.
- Return type:
- get_database_client(database: str | DatabaseProxy | Mapping[str, Any]) DatabaseProxy [source]¶
Retrieve an existing database with the ID (name) id.
- Parameters:
database (str or dict(str, str) or DatabaseProxy) – The ID (name), dict representing the properties or DatabaseProxy instance of the database to read.
- Returns:
A DatabaseProxy instance representing the retrieved database.
- Return type:
- list_databases(max_item_count: int | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List the databases in a Cosmos DB SQL database account.
- Parameters:
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments:
- Returns:
An Iterable of database properties (dicts).
- Return type:
- query_databases(query: str | None = None, parameters: List[Dict[str, Any]] | None = None, enable_cross_partition_query: bool | None = None, max_item_count: int | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Query the databases in a Cosmos DB SQL database account.
- Parameters:
query (str) – The Azure Cosmos DB SQL query to execute.
parameters (List[Dict[str, Any]]) – Optional array of parameters to the query. Ignored if no query is provided.
enable_cross_partition_query (bool) – Allow scan on the queries which couldn’t be served as indexing was opted out on the requested paths.
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments:
- Returns:
An Iterable of database properties (dicts).
- Return type:
- class azure.cosmos.DatabaseAccount[source]¶
Database account.
A DatabaseAccount is the container for databases.
- Variables:
DatabaseLink (str) – The self-link for Databases in the databaseAccount.
MediaLink (str) – The self-link for Media in the databaseAccount.
MaxMediaStorageUsageInMB (int) – Attachment content (media) storage quota in MBs (Retrieved from gateway).
CurrentMediaStorageUsageInMB (int) – Current attachment content (media) usage in MBs (Retrieved from gateway). Value is returned from cached information updated periodically and is not guaranteed to be real time.
ConsistencyPolicy (Dict[str, Union[str, int]]) – UserConsistencyPolicy settings.
EnableMultipleWritableLocations (boolean) – Flag on the azure Cosmos account that indicates if writes can take place in multiple locations.
- class azure.cosmos.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
CosmosClient.get_database_client()
method.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 (ClientSession) – Client from which this database was retrieved.
id (str) – ID (name) of the database.
- create_container(id: str, partition_key: PartitionKey, indexing_policy: Dict[str, Any] | None = None, default_ttl: int | None = None, populate_query_metrics: bool | None = None, offer_throughput: int | ThroughputProperties | None = None, unique_key_policy: Dict[str, Any] | None = None, conflict_resolution_policy: Dict[str, Any] | 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, **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.
indexing_policy (Dict[str, Any]) – The indexing policy to apply to the container.
default_ttl (int) – Default time to live (TTL) for items in the container. If unused, items do not expire.
offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.
unique_key_policy (Dict[str, Any]) – The unique key policy to apply to the container.
conflict_resolution_policy (Dict[str, Any]) – The conflict resolution policy to apply to 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) – 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.
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
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.
- Returns:
A ContainerProxy instance representing the new container.
- Raises:
CosmosHttpResponseError – The container creation failed.
- Return type:
Example:
container_name = "products" try: container = database.create_container( id=container_name, partition_key=PartitionKey(path="/productName") ) except exceptions.CosmosResourceExistsError: container = database.get_container_client(container_name)
customer_container_name = "customers" try: customer_container = 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)
- create_container_if_not_exists(id: str, partition_key: PartitionKey, indexing_policy: Dict[str, Any] | None = None, default_ttl: int | None = None, populate_query_metrics: bool | None = None, offer_throughput: int | ThroughputProperties | None = None, unique_key_policy: Dict[str, Any] | None = None, conflict_resolution_policy: Dict[str, Any] | 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, **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.
indexing_policy (Dict[str, Any]) – The indexing policy to apply to the container.
default_ttl (int) – Default time to live (TTL) for items in the container. If unused, items do not expire.
offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.
unique_key_policy (Dict[str, Any]) – The unique key policy to apply to the container.
conflict_resolution_policy (Dict[str, Any]) – The conflict resolution policy to apply to 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) – 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.
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
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.
- Returns:
A ContainerProxy instance representing the container.
- Raises:
CosmosHttpResponseError – The container read or creation failed.
- Return type:
- 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-like 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) – A callable invoked with the response metadata.
- Returns:
A UserProxy instance representing the new user.
- Raises:
CosmosHttpResponseError – If the given user couldn’t be created.
- Return type:
Example:
try: database.create_user(dict(id="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))
- delete_container(container: str | ContainerProxy | Mapping[str, Any], populate_query_metrics: bool | 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) None [source]¶
Delete a container.
- Parameters:
container (Union[str, ContainerProxy, Dict[str, Any]]) – 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) – A callable invoked with the response metadata.
- Raises:
CosmosHttpResponseError – If the container couldn’t be deleted.
- Return type:
None
- delete_user(user: str | UserProxy | Mapping[str, Any], **kwargs: Any) None [source]¶
Delete the specified user from the container.
- Parameters:
user (Union[str, UserProxy, Dict[str, Any]]) – The ID (name), dict representing the properties or
UserProxy
instance of the user to be deleted.- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Raises:
CosmosHttpResponseError – The user wasn’t deleted successfully.
CosmosResourceNotFoundError – The user does not exist in the container.
- Return type:
None
- get_container_client(container: str | ContainerProxy | Mapping[str, Any]) ContainerProxy [source]¶
Get a ContainerProxy for a container with specified ID (name).
- Parameters:
container (Union[str, ContainerProxy, Dict[str, Any]]) – The ID (name) of the container, a
ContainerProxy
instance, or a dict representing the properties of the container to be retrieved.- Returns:
A ContainerProxy instance representing the retrieved database.
- Return type:
Example:
database = client.get_database_client(database_name) container = database.get_container_client(container_name)
- get_throughput(**kwargs: Any) ThroughputProperties [source]¶
Get the ThroughputProperties object for this database.
If no ThroughputProperties already exist for the database, an exception is raised.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
ThroughputProperties for the database.
- Raises:
CosmosHttpResponseError – No throughput properties exists for the container or the throughput properties could not be retrieved.
- Return type:
- get_user_client(user: str | UserProxy | Mapping[str, Any]) UserProxy [source]¶
Get a UserProxy for a user with specified ID.
- list_containers(max_item_count: int | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List the containers in the database.
- Parameters:
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments:
- Returns:
An Iterable of container properties (dicts).
- Return type:
Iterable[Dict[str, Any]]
Example:
database = client.get_database_client(database_name) for container in database.list_containers(): print("Container ID: {}".format(container['id']))
- list_users(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all the users in the container.
- query_containers(query: str | None = None, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List the properties for containers in the current database.
- Parameters:
- Keyword Arguments:
- Returns:
An Iterable of container properties (dicts).
- Return type:
Iterable[Dict[str, Any]]
- query_users(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Return all users matching the given query.
- Parameters:
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
An Iterable of user properties (dicts).
- Return type:
Iterable[Dict[str, Any]]
- read(populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) Dict[str, Any] [source]¶
Read the database properties.
- Keyword Arguments:
- Returns:
A dict representing the database properties.
- Return type:
Dict[Str, Any]
- Raises:
CosmosHttpResponseError – If the given database couldn’t be retrieved.
- read_offer(**kwargs: Any) ThroughputProperties [source]¶
Get the ThroughputProperties object for this database.
If no ThroughputProperties already exist for the database, an exception is raised.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
ThroughputProperties for the database.
- Raises:
CosmosHttpResponseError – No throughput properties exists for the container or the throughput properties could not be retrieved.
- Return type:
- replace_container(container: str | ContainerProxy | Mapping[str, Any], partition_key: PartitionKey, indexing_policy: Dict[str, Any] | None = None, default_ttl: int | None = None, conflict_resolution_policy: Dict[str, Any] | None = None, populate_query_metrics: bool | 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, **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, ContainerProxy, Dict[str, Any]]) – 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.
indexing_policy (Dict[str, Any]) – 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, Any]) – The conflict resolution policy to apply to the container.
- Keyword Arguments:
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) – A callable invoked with the response metadata.
- 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:
Example:
# Set the TTL on the container to 3600 seconds (one hour) database.replace_container(container, partition_key=PartitionKey(path='/productName'), default_ttl=3600) # Display the new TTL setting for the container container_props = database.get_container_client(container_name).read() print("New container TTL: {}".format(json.dumps(container_props['defaultTtl'])))
- replace_throughput(throughput: int | ThroughputProperties, **kwargs: Any) ThroughputProperties [source]¶
Replace the database-level throughput.
- Parameters:
throughput (Union[int, ThroughputProperties]) – The throughput to be set (an integer).
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
ThroughputProperties for the database, updated with new throughput.
- Raises:
CosmosHttpResponseError – If no throughput properties exists for the database or if the throughput properties could not be updated.
- Return type:
- 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:
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
A UserProxy instance representing the user after replace went through.
- Raises:
CosmosHttpResponseError – If the replace operation failed or the user with given ID does not exist.
- Return type:
- 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) – A callable invoked with the response metadata.
- Returns:
A UserProxy instance representing the upserted user.
- Raises:
CosmosHttpResponseError – If the given user could not be upserted.
- Return type:
- class azure.cosmos.IndexKind[source]¶
Specifies the index kind of index specs.
- class azure.cosmos.IndexingMode[source]¶
Specifies the supported indexing modes.
- Consistent: Literal['consistent'] = 'consistent'¶
Index is updated synchronously with a create or update operation. With consistent indexing, query behavior is the same as the default consistency level for the collection. The index is always kept up to date with the data.
- Lazy: Literal['lazy'] = 'lazy'¶
Index is updated asynchronously with respect to a create or update operation. Not supported for new containers since June/2020. With lazy indexing, queries are eventually consistent. The index is updated when the collection is idle.
- NoIndex: Literal['none'] = 'none'¶
No index is provided. Setting IndexingMode to “None” drops the index. Use this if you don’t want to maintain the index for a document collection, to save the storage cost or improve the write throughput. Your queries will degenerate to scans of the entire collection.
- azure.cosmos.Offer¶
alias of
ThroughputProperties
- class azure.cosmos.PartitionKey(path: List[str], *, kind: Literal['MultiHash'] = 'MultiHash', version: int = 2)[source]¶
- class azure.cosmos.PartitionKey(path: str, *, kind: Literal['Hash'] = 'Hash', version: int = 2)
Key used to partition a container into logical partitions.
See https://docs.microsoft.com/azure/cosmos-db/partitioning-overview#choose-partitionkey for information on how to choose partition keys.
- Variables:
- clear() None. Remove all items from D. ¶
- copy() a shallow copy of D ¶
- fromkeys(value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items ¶
- keys() a set-like object providing a view on D's keys ¶
- pop(k[, d]) v, remove specified key and return the corresponding value. ¶
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem()¶
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from dict/iterable E and F. ¶
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values() an object providing a view on D's values ¶
- class azure.cosmos.Permission(id: str, user_link: str, permission_mode: str, resource_link: str, properties: Mapping[str, Any])[source]¶
Represents a Permission object in the Azure Cosmos DB SQL API service.
- class azure.cosmos.SSLConfiguration[source]¶
Configuration for SSL connections.
See https://requests.readthedocs.io/en/master/user/advanced/#ssl-cert-verification for more information.
- class azure.cosmos.ScriptsProxy(client_connection: CosmosClientConnection, container_link: str, is_system_key: bool)[source]¶
An interface to interact with stored procedures.
This class should not be instantiated directly. Instead, use the
ContainerProxy.scripts()
attribute.- 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 sproc, use the
Container.scripts.replace_stored_procedure()
method.- Parameters:
body (Dict[str, Any]) – A dict-like object representing the sproc to create.
- Returns:
A dict representing the new stored procedure.
- Raises:
CosmosHttpResponseError – If the given stored procedure couldn’t be created.
- Return type:
Dict[str, Any]
- 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.
- Returns:
A dict representing the new trigger.
- Raises:
CosmosHttpResponseError – If the given trigger couldn’t be created.
- Return type:
Dict[str, Any]
- 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 UDF, use the
ContainerProxy.scripts.replace_user_defined_function()
method.- Parameters:
body (Dict[str, Any]) – A dict-like object representing the udf to create.
- Returns:
A dict representing the new user-defined function.
- Raises:
CosmosHttpResponseError – If the user-defined function couldn’t be created.
- Return type:
Dict[str, Any]
- 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:
CosmosHttpResponseError – The sproc wasn’t deleted successfully.
CosmosResourceNotFoundError – The sproc does not exist in the container.
- Return type:
None
- 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:
CosmosHttpResponseError – The trigger wasn’t deleted successfully.
CosmosResourceNotFoundError – The trigger does not exist in the container.
- Return type:
None
- delete_user_defined_function(udf: str | Mapping[str, Any], **kwargs: Any) None [source]¶
Delete a specified user-defined function from the container.
If the UDF 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:
CosmosHttpResponseError – The udf wasn’t deleted successfully.
CosmosResourceNotFoundError – The UDF does not exist in the container.
- Return type:
None
- execute_stored_procedure(sproc: str | Mapping[str, Any], partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue] | None = None, params: 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 stored procedure to be executed.
partition_key (Union[str, int, float, bool]) – Specifies the partition key to indicate which partition the sproc should execute on.
params (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.
- Returns:
Result of the executed stored procedure for the given parameters.
- Raises:
CosmosHttpResponseError – If the stored procedure execution failed or if the stored procedure with given id does not exist in the container.
- Return type:
Dict[str, Any]
- get_stored_procedure(sproc: str | Mapping[str, Any], **kwargs: Any) Dict[str, Any] [source]¶
Get the stored procedure identified by id.
- Parameters:
sproc (Union[str, Dict[str, Any]]) – The ID (name) or dict representing stored procedure to retrieve.
- Returns:
A dict representing the retrieved stored procedure.
- Raises:
CosmosHttpResponseError – If the given stored procedure couldn’t be retrieved.
- Return type:
Dict[str, Any]
- 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.
- Returns:
A dict representing the retrieved trigger.
- Raises:
CosmosHttpResponseError – If the given trigger couldn’t be retrieved.
- Return type:
Dict[str, Any]
- get_user_defined_function(udf: str | Mapping[str, Any], **kwargs: Any) Dict[str, Any] [source]¶
Get a user-defined functions identified by id.
- Parameters:
udf (Union[str, Dict[str, Any]]) – The ID (name) or dict representing udf to retrieve.
- Returns:
A dict representing the retrieved user-defined function.
- Raises:
CosmosHttpResponseError – If the user-defined function couldn’t be retrieved.
- Return type:
Iterable[Dict[str, Any]]
- list_stored_procedures(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all stored procedures in the container.
- list_triggers(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all triggers in the container.
- list_user_defined_functions(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all the user-defined functions in the container.
- query_stored_procedures(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Return all stored procedures matching the given query.
- Parameters:
- Returns:
An Iterable of stored procedures (dicts).
- Return type:
Iterable[Dict[str, Any]]
- query_triggers(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Return all triggers matching the given query.
- Parameters:
- Returns:
An Iterable of triggers (dicts).
- Return type:
- query_user_defined_functions(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Return user-defined functions matching a given query.
- Parameters:
- Returns:
An Iterable of user-defined functions (dicts).
- Return type:
Iterable[Dict[str, Any]]
- 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:
- Returns:
A dict representing the stored procedure after replace went through.
- Raises:
CosmosHttpResponseError – If the replace operation failed or the stored procedure with given id does not exist.
- Return type:
Dict[str, Any]
- 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:
- Returns:
A dict representing the trigger after replace went through.
- Raises:
CosmosHttpResponseError – If the replace operation failed or the trigger with given id does not exist.
- Return type:
Dict[str, Any]
- 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 UDF does not already exist in the container, an exception is raised.
- Parameters:
- Returns:
A dict representing the user-defined function after replace went through.
- Raises:
CosmosHttpResponseError – If the replace operation failed or the user-defined function with the given id does not exist.
- Return type:
Dict[str, Any]
- class azure.cosmos.ThroughputProperties(*args, **kwargs)[source]¶
Represents the throughput properties in an Azure Cosmos DB SQL API container.
To read and update throughput properties, use the associated methods on the
Container
. If configuring auto-scale, auto_scale_max_throughput needs to be set and auto_scale_increment_percent can also be set in conjunction with it. The value of offer_throughput will not be allowed to be set in conjunction with the auto-scale settings.- Keyword Arguments:
offer_throughput (int) – The provisioned throughput in request units per second as a number.
auto_scale_max_throughput (int) – The max auto-scale throughput. It should have a valid throughput value between 1000 and 1000000 inclusive, in increments of 1000.
auto_scale_increment_percent (int) – is the % from the base selected RU it increases at a given time, the increment percent should be greater than or equal to zero.
- class azure.cosmos.TriggerOperation[source]¶
Specifies the operations on which a trigger should be executed.
- class azure.cosmos.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.- create_permission(body: Dict[str, Any], **kwargs: Any) Permission [source]¶
Create a permission for the user.
To update or replace an existing permision, 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) – A callable invoked with the response metadata.
- Returns:
A dict representing the new permission.
- Raises:
CosmosHttpResponseError – If the given permission couldn’t be created.
- Return type:
Dict[str, Any]
- delete_permission(permission: str | Permission | Mapping[str, Any], **kwargs) None [source]¶
Delete the specified permission from the user.
If the permission does not already exist, an exception is raised.
- Parameters:
permission (Union[str, Permission, Dict[str, Any]]) – The ID (name), dict representing the properties or
Permission
instance of the permission to be replaced.- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Raises:
CosmosHttpResponseError – The permission wasn’t deleted successfully.
CosmosResourceNotFoundError – The permission does not exist for the user.
- Return type:
None
- get_permission(permission: str | Permission | Mapping[str, Any], **kwargs: Any) Permission [source]¶
Get the permission identified by id.
- Parameters:
permission (Union[str, Permission, Dict[str, Any]]) – The ID (name), dict representing the properties or
Permission
instance of the permission to be retrieved.- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
A dict representing the retrieved permission.
- Raises:
CosmosHttpResponseError – If the given permission couldn’t be retrieved.
- Return type:
Dict[str, Any]
- list_permissions(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all permission for the user.
- query_permissions(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Return all permissions matching the given query.
- Parameters:
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
An Iterable of permissions (dicts).
- Return type:
Iterable[Dict[str, Any]]
- read(**kwargs: Any) Dict[str, Any] [source]¶
Read user properties.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
A dictionary of the retrieved user properties.
- Raises:
CosmosHttpResponseError – If the given user couldn’t be retrieved.
- Return type:
- replace_permission(permission: str | Permission | Mapping[str, Any], body: Dict[str, Any], **kwargs) 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, Permission, Dict[str, Any]]) – 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) – A callable invoked with the response metadata.
- Returns:
A dict representing the permission after replace went through.
- Raises:
CosmosHttpResponseError – If the replace operation failed or the permission with given id does not exist.
- Return type:
Dict[str, Any]
- 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) – A callable invoked with the response metadata.
- Returns:
A dict representing the upserted permission.
- Raises:
CosmosHttpResponseError – If the given permission could not be upserted.
- Return type:
Dict[str, Any]
Subpackages¶
- azure.cosmos.aio package
ContainerProxy
ContainerProxy.create_item()
ContainerProxy.delete_all_items_by_partition_key()
ContainerProxy.delete_conflict()
ContainerProxy.delete_item()
ContainerProxy.execute_item_batch()
ContainerProxy.get_conflict()
ContainerProxy.get_throughput()
ContainerProxy.list_conflicts()
ContainerProxy.patch_item()
ContainerProxy.query_conflicts()
ContainerProxy.query_items()
ContainerProxy.query_items_change_feed()
ContainerProxy.read()
ContainerProxy.read_all_items()
ContainerProxy.read_item()
ContainerProxy.replace_item()
ContainerProxy.replace_throughput()
ContainerProxy.upsert_item()
ContainerProxy.is_system_key
ContainerProxy.scripts
CosmosClient
DatabaseProxy
DatabaseProxy.create_container()
DatabaseProxy.create_container_if_not_exists()
DatabaseProxy.create_user()
DatabaseProxy.delete_container()
DatabaseProxy.delete_user()
DatabaseProxy.get_container_client()
DatabaseProxy.get_throughput()
DatabaseProxy.get_user_client()
DatabaseProxy.list_containers()
DatabaseProxy.list_users()
DatabaseProxy.query_containers()
DatabaseProxy.query_users()
DatabaseProxy.read()
DatabaseProxy.replace_container()
DatabaseProxy.replace_throughput()
DatabaseProxy.replace_user()
DatabaseProxy.upsert_user()
ScriptsProxy
ScriptsProxy.create_stored_procedure()
ScriptsProxy.create_trigger()
ScriptsProxy.create_user_defined_function()
ScriptsProxy.delete_stored_procedure()
ScriptsProxy.delete_trigger()
ScriptsProxy.delete_user_defined_function()
ScriptsProxy.execute_stored_procedure()
ScriptsProxy.get_stored_procedure()
ScriptsProxy.get_trigger()
ScriptsProxy.get_user_defined_function()
ScriptsProxy.list_stored_procedures()
ScriptsProxy.list_triggers()
ScriptsProxy.list_user_defined_functions()
ScriptsProxy.query_stored_procedures()
ScriptsProxy.query_triggers()
ScriptsProxy.query_user_defined_functions()
ScriptsProxy.replace_stored_procedure()
ScriptsProxy.replace_trigger()
ScriptsProxy.replace_user_defined_function()
UserProxy
Submodules¶
azure.cosmos.auth module¶
Authorization helper functions in the Azure Cosmos database service.
azure.cosmos.container module¶
Create, read, update and delete items in the Azure Cosmos DB SQL API service.
- class azure.cosmos.container.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 thecreate_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:
- 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, etag: str | None = None, match_condition: MatchConditions | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) Dict[str, Any] [source]¶
Create an item in the container.
To update or replace an existing item, use the
ContainerProxy.upsert_item()
method.- Parameters:
body (Dict[str, Any]) – A dict-like object representing the item to create.
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.
- Keyword Arguments:
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) – 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.
- Returns:
A dict representing the new item.
- Raises:
CosmosHttpResponseError – Item with the given ID already exists.
- Return type:
Dict[str, Any]
- 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, List[Union[str, int, float, bool]]]) – 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
- 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:
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Raises:
CosmosHttpResponseError – The conflict wasn’t deleted successfully.
CosmosResourceNotFoundError – The conflict does not exist in the container.
- Return type:
None
- delete_item(item: Mapping[str, Any] | str, partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], 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, **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, List[Union[str, int, float, bool]]]) – Specifies the partition key value for the item.
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.
- 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.
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.
- Raises:
CosmosHttpResponseError – The item wasn’t deleted successfully.
CosmosResourceNotFoundError – The item does not exist in the container.
- Return type:
None
- 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) List[Dict[str, Any]] [source]¶
Executes the transactional batch for the specified partition key.
- Parameters:
- 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 list representing the item after the batch operations went through.
- Raises:
CosmosHttpResponseError – The batch failed to execute.
CosmosBatchOperationError – A transactional batch operation failed in the batch.
- Return type:
List[Dict[str, Any]]
- 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:
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
A dict representing the retrieved conflict.
- Raises:
CosmosHttpResponseError – The given conflict couldn’t be retrieved.
- Return type:
Dict[str, Any]
- get_throughput(**kwargs: Any) ThroughputProperties [source]¶
Get the ThroughputProperties object for this container.
If no ThroughputProperties already exist for the container, an exception is raised.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
Throughput for the container.
- Raises:
CosmosHttpResponseError – No throughput properties exists for the container or the throughput properties could not be retrieved.
- Return type:
- list_conflicts(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all the conflicts in the container.
- 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, **kwargs: Any) Dict[str, Any] [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, List[Union[str, int, float, bool]]]) – 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.
- Returns:
A dict representing the item after the patch operations went through.
- Raises:
CosmosHttpResponseError – The patch operations failed or the item with given id does not exist.
- Return type:
- query_conflicts(query: str, parameters: List[Dict[str, object]] | None = None, enable_cross_partition_query: bool | 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) ItemPaged[Dict[str, Any]] [source]¶
Return all conflicts matching a given query.
- Parameters:
query (str) – The Azure Cosmos DB SQL query to execute.
parameters (List[Dict[str, object]]) – Optional array of parameters to the query. Ignored if no query is provided.
enable_cross_partition_query (bool) – 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.
partition_key (Union[str, int, float, bool, List[Union[str, int, float, bool]]]) – Specifies the partition key value for the item.
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
An Iterable of conflicts (dicts).
- Return type:
Iterable[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, 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, *, 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) ItemPaged[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.
parameters ([List[Dict[str, object]]]) – 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, List[Union[str, int, float, bool]]]) – partition key at which the query request is targeted.
enable_cross_partition_query (bool) – 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.
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.
- 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) – 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.
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.
- Returns:
An Iterable of items (dicts).
- Return type:
ItemPaged[Dict[str, Any]]
Example:
import json for item in container.query_items( query='SELECT * FROM products p WHERE p.productModel <> "DISCONTINUED"', enable_cross_partition_query=True, ): print(json.dumps(item, indent=True))
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 item in discontinued_items: print(json.dumps(item, indent=True))
- query_items_change_feed(partition_key_range_id: str | None = None, is_start_from_beginning: bool = False, continuation: str | None = None, max_item_count: int | None = None, *, start_time: datetime | None = None, partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue] | None = None, priority: Literal['High', 'Low'] | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Get a sorted list of items that were changed, in the order in which they were modified.
- Parameters:
partition_key_range_id (str) – ChangeFeed requests can be executed against specific partition key ranges. This is used to process the change feed in parallel across multiple consumers.
is_start_from_beginning (bool) – Get whether change feed should start from beginning (true) or from current (false). By default, it’s start from current (false).
max_item_count (int) – Max number of items to be returned in the enumeration operation.
continuation (str) – e_tag value to be used as continuation for reading change feed.
max_item_count – Max number of items to be returned in the enumeration operation.
- Keyword Arguments:
start_time (datetime) – Specifies a point of time to start change feed. Provided value will be converted to UTC. This value will be ignored if is_start_from_beginning is set to true.
partition_key (Union[str, int, float, bool, List[Union[str, int, float, bool]]]) – partition key at which ChangeFeed requests are targeted.
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.
- Returns:
An Iterable of items (dicts).
- Return type:
- read(populate_query_metrics: bool | None = None, 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.
- Parameters:
- 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.
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.
initial_headers – Initial headers to be sent as part of the request.
response_hook (Callable) – A callable invoked with the response metadata.
- 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:
- 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, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all the items in the container.
- Parameters:
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- 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) – 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 Iterable of items (dicts).
- Return type:
Iterable[Dict[str, Any]]
- read_item(item: str | Mapping[str, Any], partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue], 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, **kwargs: Any) Dict[str, Any] [source]¶
Get the item identified by item.
- Parameters:
- 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) – 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:
Dict representing the item to be retrieved.
- Raises:
CosmosHttpResponseError – The given item couldn’t be retrieved.
- Return type:
Example:
item = container.read_item("item2", partition_key="Widget") item["productModel"] = "DISCONTINUED" updated_item = container.upsert_item(item)
- read_offer(**kwargs: Any) ThroughputProperties [source]¶
Get the ThroughputProperties object for this container. If no ThroughputProperties already exist for the container, an exception is raised.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
Throughput for the container.
- Raises:
CosmosHttpResponseError – No throughput properties exists for the container or the throughput properties could not be retrieved.
- Return type:
- 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, **kwargs: Any) Dict[str, Any] [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.
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.
- 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) – 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.
- Returns:
A dict representing the item after replace went through.
- Raises:
CosmosHttpResponseError – The replace operation failed or the item with given id does not exist.
- Return type:
Dict[str, Any]
- 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) – A callable invoked with the response metadata.
- Returns:
ThroughputProperties for the container, updated with new throughput.
- Raises:
CosmosHttpResponseError – No throughput properties exist for the container or the throughput properties could not be updated.
- Return type:
- 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, **kwargs: Any) Dict[str, Any] [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:
- 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) – 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.
- Returns:
A dict representing the upserted item.
- Raises:
CosmosHttpResponseError – The given item could not be upserted.
- Return type:
Dict[str, Any]
- property scripts: ScriptsProxy¶
azure.cosmos.cosmos_client module¶
Create, read, and delete databases in the Azure Cosmos DB SQL API service.
- class azure.cosmos.cosmos_client.CosmosClient(url: str, credential: TokenCredential | str | Dict[str, Any], consistency_level: str | None = None, **kwargs)[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], TokenCredential]) – Can be the account key, or a dictionary of resource tokens.
consistency_level (str) – Consistency level to use for the session. The default value is None (Account level). More on consistency levels and possible values: https://aka.ms/cosmos-consistency-levels
- Keyword Arguments:
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.
Example:
from azure.cosmos import exceptions, CosmosClient, PartitionKey import os url = os.environ["ACCOUNT_URI"] key = os.environ["ACCOUNT_KEY"] client = CosmosClient(url, key)
Instantiate a new CosmosClient.
- create_database(id: str, populate_query_metrics: bool | None = None, 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.
offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.
- 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) – A callable invoked with the response metadata.
- Returns:
A DatabaseProxy instance representing the new database.
- Return type:
- Raises:
CosmosResourceExistsError – Database with the given ID already exists.
Example:
database_name = "testDatabase" try: database = client.create_database(id=database_name) except exceptions.CosmosResourceExistsError: database = client.get_database_client(database=database_name)
- create_database_if_not_exists(id: str, populate_query_metrics: bool | None = None, 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.
populate_query_metrics (bool) – Enable returning query metrics in response headers.
offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.
- 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) – A callable invoked with the response metadata.
- Returns:
A DatabaseProxy instance representing the database.
- Return type:
- Raises:
CosmosHttpResponseError – The database read or creation failed.
- delete_database(database: str | DatabaseProxy | Mapping[str, Any], populate_query_metrics: bool | 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) None [source]¶
Delete the database with the given ID (name).
- Parameters:
database (Union[str, Dict[str, str], DatabaseProxy]) – 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) – 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: TokenCredential | str | Dict[str, Any] | None = None, consistency_level: str | None = None, **kwargs) 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:
- Returns:
A CosmosClient instance representing the new client.
- Return type:
- get_database_account(**kwargs) DatabaseAccount [source]¶
Retrieve the database account information.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
A DatabaseAccount instance representing the Cosmos DB Database Account.
- Return type:
- get_database_client(database: str | DatabaseProxy | Mapping[str, Any]) DatabaseProxy [source]¶
Retrieve an existing database with the ID (name) id.
- Parameters:
database (str or dict(str, str) or DatabaseProxy) – The ID (name), dict representing the properties or DatabaseProxy instance of the database to read.
- Returns:
A DatabaseProxy instance representing the retrieved database.
- Return type:
- list_databases(max_item_count: int | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List the databases in a Cosmos DB SQL database account.
- Parameters:
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments:
- Returns:
An Iterable of database properties (dicts).
- Return type:
- query_databases(query: str | None = None, parameters: List[Dict[str, Any]] | None = None, enable_cross_partition_query: bool | None = None, max_item_count: int | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Query the databases in a Cosmos DB SQL database account.
- Parameters:
query (str) – The Azure Cosmos DB SQL query to execute.
parameters (List[Dict[str, Any]]) – Optional array of parameters to the query. Ignored if no query is provided.
enable_cross_partition_query (bool) – Allow scan on the queries which couldn’t be served as indexing was opted out on the requested paths.
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments:
- Returns:
An Iterable of database properties (dicts).
- Return type:
azure.cosmos.database module¶
Interact with databases in the Azure Cosmos DB SQL API service.
- class azure.cosmos.database.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
CosmosClient.get_database_client()
method.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 (ClientSession) – Client from which this database was retrieved.
id (str) – ID (name) of the database.
- create_container(id: str, partition_key: PartitionKey, indexing_policy: Dict[str, Any] | None = None, default_ttl: int | None = None, populate_query_metrics: bool | None = None, offer_throughput: int | ThroughputProperties | None = None, unique_key_policy: Dict[str, Any] | None = None, conflict_resolution_policy: Dict[str, Any] | 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, **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.
indexing_policy (Dict[str, Any]) – The indexing policy to apply to the container.
default_ttl (int) – Default time to live (TTL) for items in the container. If unused, items do not expire.
offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.
unique_key_policy (Dict[str, Any]) – The unique key policy to apply to the container.
conflict_resolution_policy (Dict[str, Any]) – The conflict resolution policy to apply to 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) – 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.
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
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.
- Returns:
A ContainerProxy instance representing the new container.
- Raises:
CosmosHttpResponseError – The container creation failed.
- Return type:
Example:
container_name = "products" try: container = database.create_container( id=container_name, partition_key=PartitionKey(path="/productName") ) except exceptions.CosmosResourceExistsError: container = database.get_container_client(container_name)
customer_container_name = "customers" try: customer_container = 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)
- create_container_if_not_exists(id: str, partition_key: PartitionKey, indexing_policy: Dict[str, Any] | None = None, default_ttl: int | None = None, populate_query_metrics: bool | None = None, offer_throughput: int | ThroughputProperties | None = None, unique_key_policy: Dict[str, Any] | None = None, conflict_resolution_policy: Dict[str, Any] | 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, **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.
indexing_policy (Dict[str, Any]) – The indexing policy to apply to the container.
default_ttl (int) – Default time to live (TTL) for items in the container. If unused, items do not expire.
offer_throughput (Union[int, ThroughputProperties]) – The provisioned throughput for this offer.
unique_key_policy (Dict[str, Any]) – The unique key policy to apply to the container.
conflict_resolution_policy (Dict[str, Any]) – The conflict resolution policy to apply to 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) – 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.
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
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.
- Returns:
A ContainerProxy instance representing the container.
- Raises:
CosmosHttpResponseError – The container read or creation failed.
- Return type:
- 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-like 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) – A callable invoked with the response metadata.
- Returns:
A UserProxy instance representing the new user.
- Raises:
CosmosHttpResponseError – If the given user couldn’t be created.
- Return type:
Example:
try: database.create_user(dict(id="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))
- delete_container(container: str | ContainerProxy | Mapping[str, Any], populate_query_metrics: bool | 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) None [source]¶
Delete a container.
- Parameters:
container (Union[str, ContainerProxy, Dict[str, Any]]) – 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) – A callable invoked with the response metadata.
- Raises:
CosmosHttpResponseError – If the container couldn’t be deleted.
- Return type:
None
- delete_user(user: str | UserProxy | Mapping[str, Any], **kwargs: Any) None [source]¶
Delete the specified user from the container.
- Parameters:
user (Union[str, UserProxy, Dict[str, Any]]) – The ID (name), dict representing the properties or
UserProxy
instance of the user to be deleted.- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Raises:
CosmosHttpResponseError – The user wasn’t deleted successfully.
CosmosResourceNotFoundError – The user does not exist in the container.
- Return type:
None
- get_container_client(container: str | ContainerProxy | Mapping[str, Any]) ContainerProxy [source]¶
Get a ContainerProxy for a container with specified ID (name).
- Parameters:
container (Union[str, ContainerProxy, Dict[str, Any]]) – The ID (name) of the container, a
ContainerProxy
instance, or a dict representing the properties of the container to be retrieved.- Returns:
A ContainerProxy instance representing the retrieved database.
- Return type:
Example:
database = client.get_database_client(database_name) container = database.get_container_client(container_name)
- get_throughput(**kwargs: Any) ThroughputProperties [source]¶
Get the ThroughputProperties object for this database.
If no ThroughputProperties already exist for the database, an exception is raised.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
ThroughputProperties for the database.
- Raises:
CosmosHttpResponseError – No throughput properties exists for the container or the throughput properties could not be retrieved.
- Return type:
- get_user_client(user: str | UserProxy | Mapping[str, Any]) UserProxy [source]¶
Get a UserProxy for a user with specified ID.
- list_containers(max_item_count: int | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List the containers in the database.
- Parameters:
max_item_count (int) – Max number of items to be returned in the enumeration operation.
- Keyword Arguments:
- Returns:
An Iterable of container properties (dicts).
- Return type:
Iterable[Dict[str, Any]]
Example:
database = client.get_database_client(database_name) for container in database.list_containers(): print("Container ID: {}".format(container['id']))
- list_users(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all the users in the container.
- query_containers(query: str | None = None, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List the properties for containers in the current database.
- Parameters:
- Keyword Arguments:
- Returns:
An Iterable of container properties (dicts).
- Return type:
Iterable[Dict[str, Any]]
- query_users(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Return all users matching the given query.
- Parameters:
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
An Iterable of user properties (dicts).
- Return type:
Iterable[Dict[str, Any]]
- read(populate_query_metrics: bool | None = None, *, session_token: str | None = None, initial_headers: Dict[str, str] | None = None, **kwargs: Any) Dict[str, Any] [source]¶
Read the database properties.
- Keyword Arguments:
- Returns:
A dict representing the database properties.
- Return type:
Dict[Str, Any]
- Raises:
CosmosHttpResponseError – If the given database couldn’t be retrieved.
- read_offer(**kwargs: Any) ThroughputProperties [source]¶
Get the ThroughputProperties object for this database.
If no ThroughputProperties already exist for the database, an exception is raised.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
ThroughputProperties for the database.
- Raises:
CosmosHttpResponseError – No throughput properties exists for the container or the throughput properties could not be retrieved.
- Return type:
- replace_container(container: str | ContainerProxy | Mapping[str, Any], partition_key: PartitionKey, indexing_policy: Dict[str, Any] | None = None, default_ttl: int | None = None, conflict_resolution_policy: Dict[str, Any] | None = None, populate_query_metrics: bool | 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, **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, ContainerProxy, Dict[str, Any]]) – 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.
indexing_policy (Dict[str, Any]) – 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, Any]) – The conflict resolution policy to apply to the container.
- Keyword Arguments:
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) – A callable invoked with the response metadata.
- 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:
Example:
# Set the TTL on the container to 3600 seconds (one hour) database.replace_container(container, partition_key=PartitionKey(path='/productName'), default_ttl=3600) # Display the new TTL setting for the container container_props = database.get_container_client(container_name).read() print("New container TTL: {}".format(json.dumps(container_props['defaultTtl'])))
- replace_throughput(throughput: int | ThroughputProperties, **kwargs: Any) ThroughputProperties [source]¶
Replace the database-level throughput.
- Parameters:
throughput (Union[int, ThroughputProperties]) – The throughput to be set (an integer).
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
ThroughputProperties for the database, updated with new throughput.
- Raises:
CosmosHttpResponseError – If no throughput properties exists for the database or if the throughput properties could not be updated.
- Return type:
- 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:
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
A UserProxy instance representing the user after replace went through.
- Raises:
CosmosHttpResponseError – If the replace operation failed or the user with given ID does not exist.
- Return type:
- 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) – A callable invoked with the response metadata.
- Returns:
A UserProxy instance representing the upserted user.
- Raises:
CosmosHttpResponseError – If the given user could not be upserted.
- Return type:
azure.cosmos.diagnostics module¶
Diagnostic tools for Azure Cosmos database service operations. IMPORTANT: This file has been marked for deprecation and will be removed in the future. For diagnostics logging in our SDK, please use our CosmosHttpLoggingPolicy outlined in our README.
azure.cosmos.documents module¶
Classes and enums for documents in the Azure Cosmos database service.
- class azure.cosmos.documents.ConnectionMode[source]¶
Represents the connection mode to be used by the client.
- class azure.cosmos.documents.ConnectionPolicy[source]¶
Represents the Connection policy associated with a CosmosClientConnection.
- Variables:
RequestTimeout (int) – Gets or sets the request timeout (time to wait for a response from a network peer).
ConnectionMode (ConnectionMode) – Gets or sets the connection mode used in the client. (Currently only Gateway is supported.)
SSLConfiguration (SSLConfiguration) – Gets or sets the SSL configuration.
ProxyConfiguration (ProxyConfiguration) – Gets or sets the proxy configuration.
EnableEndpointDiscovery (boolean) – Gets or sets endpoint discovery flag for geo-replicated database accounts. When EnableEndpointDiscovery is true, the client will automatically discover the current write and read locations and direct the requests to the correct location taking into consideration of the user’s preference(if provided) as PreferredLocations.
PreferredLocations (List[str]) – Gets or sets the preferred locations for geo-replicated database accounts. When EnableEndpointDiscovery is true and PreferredLocations is non-empty, the client will use this list to evaluate the final location, taking into consideration the order specified in PreferredLocations. The locations in this list are specified as the names of the azure Cosmos locations like, ‘West US’, ‘East US’, ‘Central India’ and so on.
RetryOptions (~RetryOptions) – Gets or sets the retry options to be applied to all requests when retrying.
DisableSSLVerification (boolean) – Flag to disable SSL verification for the requests. SSL verification is enabled by default. This is intended to be used only when targeting emulator endpoint to avoid failing your requests with SSL related error. DO NOT set this when targeting production endpoints.
UseMultipleWriteLocations (boolean) – Flag to enable writes on any locations (regions) for geo-replicated database accounts in the Azure Cosmos database service.
ConnectionRetryConfiguration (int or ConnectionRetryPolicy) – Retry Configuration to be used for connection retries.
- class azure.cosmos.documents.ConsistencyLevel[source]¶
Represents the consistency levels supported for Azure Cosmos client operations.
The requested ConsistencyLevel must match or be weaker than that provisioned for the database account. Consistency levels.
Consistency levels by order of strength are Strong, BoundedStaleness, Session, ConsistentPrefix and Eventual.
- BoundedStaleness: Literal['BoundedStaleness'] = 'BoundedStaleness'¶
Bounded Staleness guarantees that reads are not too out-of-date. This can be configured based on number of operations (MaxStalenessPrefix) or time (MaxStalenessIntervalInSeconds).
- ConsistentPrefix: Literal['ConsistentPrefix'] = 'ConsistentPrefix'¶
ConsistentPrefix Consistency guarantees that reads will return some prefix of all writes with no gaps. All writes will be eventually be available for reads.
- Eventual: Literal['Eventual'] = 'Eventual'¶
Eventual Consistency guarantees that reads will return a subset of writes. All writes will be eventually be available for reads.
- class azure.cosmos.documents.DatabaseAccount[source]¶
Database account.
A DatabaseAccount is the container for databases.
- Variables:
DatabaseLink (str) – The self-link for Databases in the databaseAccount.
MediaLink (str) – The self-link for Media in the databaseAccount.
MaxMediaStorageUsageInMB (int) – Attachment content (media) storage quota in MBs (Retrieved from gateway).
CurrentMediaStorageUsageInMB (int) – Current attachment content (media) usage in MBs (Retrieved from gateway). Value is returned from cached information updated periodically and is not guaranteed to be real time.
ConsistencyPolicy (Dict[str, Union[str, int]]) – UserConsistencyPolicy settings.
EnableMultipleWritableLocations (boolean) – Flag on the azure Cosmos account that indicates if writes can take place in multiple locations.
- class azure.cosmos.documents.IndexKind[source]¶
Specifies the index kind of index specs.
- class azure.cosmos.documents.IndexingDirective[source]¶
Specifies whether or not the resource is to be indexed.
- class azure.cosmos.documents.IndexingMode[source]¶
Specifies the supported indexing modes.
- Consistent: Literal['consistent'] = 'consistent'¶
Index is updated synchronously with a create or update operation. With consistent indexing, query behavior is the same as the default consistency level for the collection. The index is always kept up to date with the data.
- Lazy: Literal['lazy'] = 'lazy'¶
Index is updated asynchronously with respect to a create or update operation. Not supported for new containers since June/2020. With lazy indexing, queries are eventually consistent. The index is updated when the collection is idle.
- NoIndex: Literal['none'] = 'none'¶
No index is provided. Setting IndexingMode to “None” drops the index. Use this if you don’t want to maintain the index for a document collection, to save the storage cost or improve the write throughput. Your queries will degenerate to scans of the entire collection.
- class azure.cosmos.documents.PartitionKind[source]¶
Specifies the kind of partitioning to be applied.
- class azure.cosmos.documents.SSLConfiguration[source]¶
Configuration for SSL connections.
See https://requests.readthedocs.io/en/master/user/advanced/#ssl-cert-verification for more information.
- class azure.cosmos.documents.TriggerOperation[source]¶
Specifies the operations on which a trigger should be executed.
- class azure.cosmos.documents.UserConsistencyPolicy[source]¶
- clear() None. Remove all items from D. ¶
- copy() a shallow copy of D ¶
- fromkeys(value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items ¶
- keys() a set-like object providing a view on D's keys ¶
- pop(k[, d]) v, remove specified key and return the corresponding value. ¶
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem()¶
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from dict/iterable E and F. ¶
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values() an object providing a view on D's values ¶
azure.cosmos.errors module¶
Service-specific Exceptions in the Azure Cosmos database service.
Warning
This module is DEPRECATED. Use azure.cosmos.exceptions instead.
azure.cosmos.exceptions module¶
Service-specific Exceptions in the Azure Cosmos database service.
- exception azure.cosmos.exceptions.CosmosAccessConditionFailedError(status_code=None, message=None, response=None, **kwargs)[source]¶
An HTTP error response with status code 412.
- add_note()¶
Exception.add_note(note) – add a note to the exception
- raise_with_traceback() None ¶
Raise the exception with the existing traceback.
Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args¶
- exception azure.cosmos.exceptions.CosmosBatchOperationError(error_index=None, headers=None, status_code=None, message=None, operation_responses=None, **kwargs)[source]¶
A transactional batch request to the Azure Cosmos database service has failed.
- Variables:
Example:
batch_operations = [create_item_operation, create_item_operation] try: container.execute_item_batch(batch_operations, partition_key="Account1") except exceptions.CosmosBatchOperationError as e: error_operation_index = e.error_index error_operation_response = e.operation_responses[error_operation_index] error_operation = batch_operations[error_operation_index] print("\nError operation: {}, error operation response: {}\n".format(error_operation, error_operation_response))
- add_note()¶
Exception.add_note(note) – add a note to the exception
- raise_with_traceback() None ¶
Raise the exception with the existing traceback.
Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args¶
- exception azure.cosmos.exceptions.CosmosClientTimeoutError(**kwargs)[source]¶
An operation failed to complete within the specified timeout.
- add_note()¶
Exception.add_note(note) – add a note to the exception
- raise_with_traceback() None ¶
Raise the exception with the existing traceback.
Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args¶
- exception azure.cosmos.exceptions.CosmosHttpResponseError(status_code=None, message=None, response=None, **kwargs)[source]¶
An HTTP request to the Azure Cosmos database service has failed.
- add_note()¶
Exception.add_note(note) – add a note to the exception
- raise_with_traceback() None ¶
Raise the exception with the existing traceback.
Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args¶
- exception azure.cosmos.exceptions.CosmosResourceExistsError(status_code=None, message=None, response=None, **kwargs)[source]¶
An HTTP error response with status code 409.
- add_note()¶
Exception.add_note(note) – add a note to the exception
- raise_with_traceback() None ¶
Raise the exception with the existing traceback.
Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args¶
- exc_value: BaseException | None¶
- inner_exception: BaseException | None¶
- exception azure.cosmos.exceptions.CosmosResourceNotFoundError(status_code=None, message=None, response=None, **kwargs)[source]¶
An HTTP error response with status code 404.
- add_note()¶
Exception.add_note(note) – add a note to the exception
- raise_with_traceback() None ¶
Raise the exception with the existing traceback.
Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args¶
- exc_value: BaseException | None¶
- inner_exception: BaseException | None¶
azure.cosmos.http_constants module¶
HTTP Constants in the Azure Cosmos database service.
- class azure.cosmos.http_constants.CookieHeaders[source]¶
Constants of cookie headers.
- SessionToken = 'x-ms-session-token'¶
- class azure.cosmos.http_constants.Delimiters[source]¶
Constants of delimiters.
- ClientContinuationDelimiter = '!!'¶
- ClientContinuationFormat = '{0}!!{1}'¶
- class azure.cosmos.http_constants.HttpContextProperties[source]¶
Constants of http context properties.
- SubscriptionId = 'SubscriptionId'¶
- class azure.cosmos.http_constants.HttpHeaderPreferenceTokens[source]¶
Constants of http header preference tokens.
- PreferUnfilteredQueryResponse = 'PreferUnfilteredQueryResponse'¶
- class azure.cosmos.http_constants.HttpHeaders[source]¶
Constants of http headers.
- AIM = 'A-IM'¶
- Accept = 'Accept'¶
- AcceptCharset = 'Accept-Charset'¶
- AcceptEncoding = 'Accept-Encoding'¶
- AcceptLanguage = 'Accept-Language'¶
- AcceptRanges = 'Accept-Ranges'¶
- AccessControlAllowHeaders = 'Access-Control-Allow-Headers'¶
- AccessControlAllowOrigin = 'Access-Control-Allow-Origin'¶
- ActivityId = 'x-ms-activity-id'¶
- AllowTentativeWrites = 'x-ms-cosmos-allow-tentative-writes'¶
- AlternateContentPath = 'x-ms-alt-content-path'¶
- Authorization = 'authorization'¶
- AutoscaleSettings = 'x-ms-cosmos-offer-autopilot-settings'¶
- CacheControl = 'Cache-Control'¶
- CharacterSet = 'CharacterSet'¶
- CollectionCurrentUsageInMb = 'x-ms-collection-usage-mb'¶
- CollectionPartitionInfo = 'x-ms-collection-partition-info'¶
- CollectionQuotaInMb = 'x-ms-collection-quota-mb'¶
- CollectionServiceInfo = 'x-ms-collection-service-info'¶
- ConsistencyLevel = 'x-ms-consistency-level'¶
- ContentEncoding = 'Content-Encoding'¶
- ContentLanguage = 'Content-Language'¶
- ContentLength = 'Content-Length'¶
- ContentLocation = 'Content-Location'¶
- ContentMd5 = 'Content-Md5'¶
- ContentPath = 'x-ms-content-path'¶
- ContentRange = 'Content-Range'¶
- ContentType = 'Content-Type'¶
- Continuation = 'x-ms-continuation'¶
- CosmosLsn = 'x-ms-cosmos-llsn'¶
- CosmosQuorumAckedLsn = 'x-ms-cosmos-quorum-acked-llsn'¶
- CurrentEntityCount = 'x-ms-root-entity-current-count'¶
- CurrentMediaStorageUsageInMB = 'x-ms-media-storage-usage-mb'¶
- CurrentReplicaSetSize = 'x-ms-current-replica-set-size'¶
- CurrentWriteQuorum = 'x-ms-current-write-quorum'¶
- DedicatedGatewayCacheStaleness = 'x-ms-dedicatedgateway-max-age'¶
- DisableRUPerMinuteUsage = 'x-ms-documentdb-disable-ru-per-minute-usage'¶
- ETag = 'etag'¶
- EmitVerboseTracesInQuery = 'x-ms-documentdb-query-emit-traces'¶
- EnableCrossPartitionQuery = 'x-ms-documentdb-query-enablecrosspartition'¶
- EnableScanInQuery = 'x-ms-documentdb-query-enable-scan'¶
- EnableScriptLogging = 'x-ms-documentdb-script-enable-logging'¶
- EndEpkString = 'x-ms-end-epk'¶
- ForceRefresh = 'x-ms-force-refresh'¶
- FullUpgrade = 'x-ms-force-full-upgrade'¶
- GatewayVersion = 'x-ms-gatewayversion'¶
- GlobalCommittedLsn = 'x-ms-global-committed-lsn'¶
- Host = 'Host'¶
- HttpDate = 'date'¶
- IfMatch = 'If-Match'¶
- IfModified_since = 'If-Modified-Since'¶
- IfNoneMatch = 'If-None-Match'¶
- IfRange = 'If-Range'¶
- IfUnmodifiedSince = 'If-Unmodified-Since'¶
- IgnoreInProgressUpgrade = 'x-ms-ignore-inprogress-upgrade'¶
- IncrementalFeedHeaderValue = 'Incremental feed'¶
- IndexTransformationProgress = 'x-ms-documentdb-collection-index-transformation-progress'¶
- IndexUtilization = 'x-ms-cosmos-index-utilization'¶
- IndexingDirective = 'x-ms-indexing-directive'¶
- IntegratedCacheHit = 'x-ms-cosmos-cachehit'¶
- IsBatchAtomic = 'x-ms-cosmos-batch-atomic'¶
- IsBatchRequest = 'x-ms-cosmos-is-batch-request'¶
- IsCanary = 'x-ms-iscanary'¶
- IsContinuationExpected = 'x-ms-documentdb-query-iscontinuationexpected'¶
- IsFeedUnfiltered = 'x-ms-is-feed-unfiltered'¶
- IsQuery = 'x-ms-documentdb-isquery'¶
- IsQueryPlanRequest = 'x-ms-cosmos-is-query-plan-request'¶
- IsRUPerMinuteUsed = 'x-ms-documentdb-is-ru-per-minute-used'¶
- IsUpsert = 'x-ms-documentdb-is-upsert'¶
- ItemCount = 'x-ms-item-count'¶
- KeepAlive = 'Keep-Alive'¶
- KeyValueEncodingFormat = 'application/x-www-form-urlencoded'¶
- LSN = 'lsn'¶
- LastModified = 'Last-Modified'¶
- LastStateChangeUtc = 'x-ms-last-state-change-utc'¶
- LazyIndexingProgress = 'x-ms-documentdb-collection-lazy-indexing-progress'¶
- Location = 'Location'¶
- MaxEntityCount = 'x-ms-root-entity-max-count'¶
- MaxForwards = 'Max-Forwards'¶
- MaxMediaStorageUsageInMB = 'x-ms-max-media-storage-usage-mb'¶
- MethodOverride = 'X-HTTP-Method'¶
- NewResourceId = 'x-ms-new-resource-id'¶
- NumberOfReadRegions = 'x-ms-number-of-read-regions'¶
- OcpResourceProviderRegisteredUri = 'ocp-resourceprovider-registered-uri'¶
- OfferIsRUPerMinuteThroughputEnabled = 'x-ms-offer-is-ru-per-minute-throughput-enabled'¶
- OfferThroughput = 'x-ms-offer-throughput'¶
- OfferType = 'x-ms-offer-type'¶
- OnlyUpgradeNonSystemApplications = 'x-ms-only-upgrade-non-system-applications'¶
- OnlyUpgradeSystemApplications = 'x-ms-only-upgrade-system-applications'¶
- Origin = 'Origin'¶
- PageSize = 'x-ms-max-item-count'¶
- PartitionKey = 'x-ms-documentdb-partitionkey'¶
- PartitionKeyDeletePending = 'x-ms-cosmos-is-partition-key-delete-pending'¶
- PartitionKeyRangeID = 'x-ms-documentdb-partitionkeyrangeid'¶
- PopulateIndexMetrics = 'x-ms-cosmos-populateindexmetrics'¶
- PopulatePartitionKeyRangeStatistics = 'x-ms-documentdb-populatepartitionstatistics'¶
- PopulateQueryMetrics = 'x-ms-documentdb-populatequerymetrics'¶
- PopulateQuotaInfo = 'x-ms-documentdb-populatequotainfo'¶
- PostTriggerExclude = 'x-ms-documentdb-post-trigger-exclude'¶
- PostTriggerInclude = 'x-ms-documentdb-post-trigger-include'¶
- Pragma = 'Pragma'¶
- PreTriggerExclude = 'x-ms-documentdb-pre-trigger-exclude'¶
- PreTriggerInclude = 'x-ms-documentdb-pre-trigger-include'¶
- Prefer = 'Prefer'¶
- PriorityLevel = 'x-ms-cosmos-priority-level'¶
- ProxyAuthenticate = 'Proxy-Authenticate'¶
- ProxyAuthorization = 'Proxy-Authorization'¶
- Query = 'x-ms-documentdb-query'¶
- QueryExecutionInfo = 'x-ms-cosmos-query-execution-info'¶
- QueryMetrics = 'x-ms-documentdb-query-metrics'¶
- QueryVersion = 'x-ms-cosmos-query-version'¶
- QuorumAckedLsn = 'x-ms-quorum-acked-lsn'¶
- ReadFeedKeyType = 'x-ms-read-key-type'¶
- Referer = 'referer'¶
- RequestCharge = 'x-ms-request-charge'¶
- RequestDurationMs = 'x-ms-request-duration-ms'¶
- RequestId = 'x-ms-request-id'¶
- ResourceQuota = 'x-ms-resource-quota'¶
- ResourceTokenExpiry = 'x-ms-documentdb-expiry-seconds'¶
- ResourceUsage = 'x-ms-resource-usage'¶
- ResponseContinuationTokenLimitInKb = 'x-ms-documentdb-responsecontinuationtokenlimitinkb'¶
- RetryAfter = 'Retry-After'¶
- RetryAfterInMilliseconds = 'x-ms-retry-after-ms'¶
- SDKSupportedCapabilities = 'x-ms-cosmos-sdk-supportedcapabilities'¶
- SchemaVersion = 'x-ms-schemaversion'¶
- ScriptLogResults = 'x-ms-documentdb-script-log-results'¶
- Server = 'Server'¶
- ServiceVersion = 'x-ms-serviceversion'¶
- SessionToken = 'x-ms-session-token'¶
- SetCookie = 'Set-Cookie'¶
- ShouldBatchContinueOnError = 'x-ms-cosmos-batch-continue-on-error'¶
- SimpleToken = 'SWT'¶
- Slug = 'Slug'¶
- StartEpkString = 'x-ms-start-epk'¶
- StrictTransportSecurity = 'Strict-Transport-Security'¶
- SubStatus = 'x-ms-substatus'¶
- SupportedQueryFeatures = 'x-ms-cosmos-supported-query-features'¶
- ThrottleRetryCount = 'x-ms-throttle-retry-count'¶
- ThrottleRetryWaitTimeInMs = 'x-ms-throttle-retry-wait-time-ms'¶
- TransferEncoding = 'Transfer-Encoding'¶
- TransportRequestId = 'x-ms-transport-request-id'¶
- UpgradeFabricRingCodeAndConfig = 'x-ms-upgrade-fabric-code-config'¶
- UpgradeVerificationKind = 'x-ms-upgrade-verification-kind'¶
- UseMasterCollectionResolver = 'x-ms-use-master-collection-resolver'¶
- UserAgent = 'User-Agent'¶
- Version = 'x-ms-version'¶
- WrapAssertion = 'wrap_assertion'¶
- WrapAssertionFormat = 'wrap_assertion_format'¶
- WrapScope = 'wrap_scope'¶
- WwwAuthenticate = 'Www-Authenticate'¶
- XDate = 'x-ms-date'¶
- XpRole = 'x-ms-xp-role'¶
- class azure.cosmos.http_constants.HttpListenerErrorCodes[source]¶
Constants of http listener error codes.
- ERROR_CONNECTION_INVALID = 1229¶
- ERROR_OPERATION_ABORTED = 995¶
- class azure.cosmos.http_constants.HttpMethods[source]¶
Constants of http methods.
- Delete = 'DELETE'¶
- Get = 'GET'¶
- Head = 'HEAD'¶
- Options = 'OPTIONS'¶
- Post = 'POST'¶
- Put = 'PUT'¶
- class azure.cosmos.http_constants.HttpStatusDescriptions[source]¶
Constants of http status descriptions.
- Accepted = 'Accepted'¶
- BadGateway = 'Bad Gateway'¶
- BadRequest = 'Bad Request'¶
- Conflict = 'Conflict'¶
- Created = 'Created'¶
- Forbidden = 'Forbidden'¶
- GatewayTimeout = 'Gateway timed out'¶
- Gone = 'Gone'¶
- InternalServerError = 'Internal Server Error'¶
- LengthRequired = 'Length Required'¶
- MethodNotAllowed = 'MethodNotAllowed'¶
- NoContent = 'No Content'¶
- NotAcceptable = 'Not Acceptable'¶
- NotFound = 'Not Found'¶
- NotModified = 'Not Modified'¶
- OK = 'Ok'¶
- PreconditionFailed = 'Precondition Failed'¶
- RequestEntityTooLarge = 'Request Entity Too Large'¶
- RequestTimeout = 'Request timed out'¶
- RetryWith = 'Retry the request'¶
- TooManyRequests = 'Too Many Requests'¶
- Unauthorized = 'Unauthorized'¶
- UnsupportedMediaType = 'Unsupported Media Type'¶
- class azure.cosmos.http_constants.QueryStrings[source]¶
Constants of query strings.
- ContentView = 'contentview'¶
- Filter = '$filter'¶
- GenerateId = '$generateFor'¶
- GenerateIdBatchSize = '$batchSize'¶
- Generic = 'generic'¶
- GetChildResourcePartitions = '$getChildResourcePartitions'¶
- Query = 'query'¶
- RootIndex = '$rootIndex'¶
- SQLQueryType = 'sql'¶
- Url = '$resolveFor'¶
- class azure.cosmos.http_constants.ResourceType[source]¶
Types of resources in Azure Cosmos
- Attachment = 'attachments'¶
- Collection = 'colls'¶
- Conflict = 'conflicts'¶
- Database = 'dbs'¶
- DatabaseAccount = 'databaseaccount'¶
- Document = 'docs'¶
- Offer = 'offers'¶
- PartitionKey = 'partitionkey'¶
- PartitionKeyRange = 'pkranges'¶
- Permission = 'permissions'¶
- Schema = 'schemas'¶
- StoredProcedure = 'sprocs'¶
- Topology = 'topology'¶
- Trigger = 'triggers'¶
- User = 'users'¶
- UserDefinedFunction = 'udfs'¶
- class azure.cosmos.http_constants.StatusCodes[source]¶
HTTP status codes returned by the REST operations
- ACCEPTED = 202¶
- BAD_REQUEST = 400¶
- CONFLICT = 409¶
- CREATED = 201¶
- FAILED_DEPENDENCY = 424¶
- FORBIDDEN = 403¶
- GONE = 410¶
- INTERNAL_SERVER_ERROR = 500¶
- METHOD_NOT_ALLOWED = 405¶
- NOT_FOUND = 404¶
- NOT_MODIFIED = 304¶
- NO_CONTENT = 204¶
- OK = 200¶
- OPERATION_CANCELLED = 1201¶
- OPERATION_PAUSED = 1200¶
- PRECONDITION_FAILED = 412¶
- REQUEST_ENTITY_TOO_LARGE = 413¶
- REQUEST_TIMEOUT = 408¶
- RETRY_WITH = 449¶
- SERVICE_UNAVAILABLE = 503¶
- TOO_MANY_REQUESTS = 429¶
- UNAUTHORIZED = 401¶
- class azure.cosmos.http_constants.SubStatusCodes[source]¶
Sub status codes returned by the REST operations specifying the details of the operation
- AAD_REQUEST_NOT_AUTHORIZED = 5300¶
- COMPLETING_PARTITION_MIGRATION = 1008¶
- COMPLETING_SPLIT = 1007¶
- CONFLICT_WITH_CONTROL_PLANE = 1006¶
- CROSS_PARTITION_QUERY_NOT_SERVABLE = 1004¶
- DATABASE_ACCOUNT_NOT_FOUND = 1008¶
- INSUFFICIENT_BINDABLE_PARTITIONS = 1007¶
- NAME_CACHE_IS_STALE = 1000¶
- OWNER_RESOURCE_NOT_FOUND = 1003¶
- PARTITION_KEY_MISMATCH = 1001¶
- PARTITION_KEY_RANGE_GONE = 1002¶
- PROVISION_LIMIT_REACHED = 1005¶
- READ_SESSION_NOTAVAILABLE = 1002¶
- REDUNDANT_COLLECTION_PUT = 1009¶
- SHARED_THROUGHPUT_DATABASE_QUOTA_EXCEEDED = 1010¶
- SHARED_THROUGHPUT_OFFER_GROW_NOT_NEEDED = 1011¶
- UNKNOWN = 0¶
- WRITE_FORBIDDEN = 3¶
azure.cosmos.offer module¶
Create throughput properties in the Azure Cosmos DB SQL API service.
- azure.cosmos.offer.Offer¶
alias of
ThroughputProperties
- class azure.cosmos.offer.ThroughputProperties(*args, **kwargs)[source]¶
Represents the throughput properties in an Azure Cosmos DB SQL API container.
To read and update throughput properties, use the associated methods on the
Container
. If configuring auto-scale, auto_scale_max_throughput needs to be set and auto_scale_increment_percent can also be set in conjunction with it. The value of offer_throughput will not be allowed to be set in conjunction with the auto-scale settings.- Keyword Arguments:
offer_throughput (int) – The provisioned throughput in request units per second as a number.
auto_scale_max_throughput (int) – The max auto-scale throughput. It should have a valid throughput value between 1000 and 1000000 inclusive, in increments of 1000.
auto_scale_increment_percent (int) – is the % from the base selected RU it increases at a given time, the increment percent should be greater than or equal to zero.
azure.cosmos.partition_key module¶
Create partition keys in the Azure Cosmos DB SQL API service.
- class azure.cosmos.partition_key.NonePartitionKeyValue[source]¶
Represents None value for partitionKey when it’s missing in a container.
- class azure.cosmos.partition_key.PartitionKey(path: List[str], *, kind: Literal['MultiHash'] = 'MultiHash', version: int = 2)[source]¶
- class azure.cosmos.partition_key.PartitionKey(path: str, *, kind: Literal['Hash'] = 'Hash', version: int = 2)
Key used to partition a container into logical partitions.
See https://docs.microsoft.com/azure/cosmos-db/partitioning-overview#choose-partitionkey for information on how to choose partition keys.
- Variables:
- clear() None. Remove all items from D. ¶
- copy() a shallow copy of D ¶
- fromkeys(value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, /)¶
Return the value for key if key is in the dictionary, else default.
- items() a set-like object providing a view on D's items ¶
- keys() a set-like object providing a view on D's keys ¶
- pop(k[, d]) v, remove specified key and return the corresponding value. ¶
If the key is not found, return the default if given; otherwise, raise a KeyError.
- popitem()¶
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- setdefault(key, default=None, /)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- update([E, ]**F) None. Update D from dict/iterable E and F. ¶
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- values() an object providing a view on D's values ¶
azure.cosmos.permission module¶
Create permissions in the Azure Cosmos DB SQL API service.
azure.cosmos.scripts module¶
Create, read, update and delete and execute scripts in the Azure Cosmos DB SQL API service.
- class azure.cosmos.scripts.ScriptType[source]¶
- StoredProcedure = 'sprocs'¶
- Trigger = 'triggers'¶
- UserDefinedFunction = 'udfs'¶
- class azure.cosmos.scripts.ScriptsProxy(client_connection: CosmosClientConnection, container_link: str, is_system_key: bool)[source]¶
An interface to interact with stored procedures.
This class should not be instantiated directly. Instead, use the
ContainerProxy.scripts()
attribute.- 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 sproc, use the
Container.scripts.replace_stored_procedure()
method.- Parameters:
body (Dict[str, Any]) – A dict-like object representing the sproc to create.
- Returns:
A dict representing the new stored procedure.
- Raises:
CosmosHttpResponseError – If the given stored procedure couldn’t be created.
- Return type:
Dict[str, Any]
- 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.
- Returns:
A dict representing the new trigger.
- Raises:
CosmosHttpResponseError – If the given trigger couldn’t be created.
- Return type:
Dict[str, Any]
- 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 UDF, use the
ContainerProxy.scripts.replace_user_defined_function()
method.- Parameters:
body (Dict[str, Any]) – A dict-like object representing the udf to create.
- Returns:
A dict representing the new user-defined function.
- Raises:
CosmosHttpResponseError – If the user-defined function couldn’t be created.
- Return type:
Dict[str, Any]
- 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:
CosmosHttpResponseError – The sproc wasn’t deleted successfully.
CosmosResourceNotFoundError – The sproc does not exist in the container.
- Return type:
None
- 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:
CosmosHttpResponseError – The trigger wasn’t deleted successfully.
CosmosResourceNotFoundError – The trigger does not exist in the container.
- Return type:
None
- delete_user_defined_function(udf: str | Mapping[str, Any], **kwargs: Any) None [source]¶
Delete a specified user-defined function from the container.
If the UDF 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:
CosmosHttpResponseError – The udf wasn’t deleted successfully.
CosmosResourceNotFoundError – The UDF does not exist in the container.
- Return type:
None
- execute_stored_procedure(sproc: str | Mapping[str, Any], partition_key: str | int | float | bool | Sequence[str | int | float | bool | None] | Type[NonePartitionKeyValue] | None = None, params: 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 stored procedure to be executed.
partition_key (Union[str, int, float, bool]) – Specifies the partition key to indicate which partition the sproc should execute on.
params (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.
- Returns:
Result of the executed stored procedure for the given parameters.
- Raises:
CosmosHttpResponseError – If the stored procedure execution failed or if the stored procedure with given id does not exist in the container.
- Return type:
Dict[str, Any]
- get_stored_procedure(sproc: str | Mapping[str, Any], **kwargs: Any) Dict[str, Any] [source]¶
Get the stored procedure identified by id.
- Parameters:
sproc (Union[str, Dict[str, Any]]) – The ID (name) or dict representing stored procedure to retrieve.
- Returns:
A dict representing the retrieved stored procedure.
- Raises:
CosmosHttpResponseError – If the given stored procedure couldn’t be retrieved.
- Return type:
Dict[str, Any]
- 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.
- Returns:
A dict representing the retrieved trigger.
- Raises:
CosmosHttpResponseError – If the given trigger couldn’t be retrieved.
- Return type:
Dict[str, Any]
- get_user_defined_function(udf: str | Mapping[str, Any], **kwargs: Any) Dict[str, Any] [source]¶
Get a user-defined functions identified by id.
- Parameters:
udf (Union[str, Dict[str, Any]]) – The ID (name) or dict representing udf to retrieve.
- Returns:
A dict representing the retrieved user-defined function.
- Raises:
CosmosHttpResponseError – If the user-defined function couldn’t be retrieved.
- Return type:
Iterable[Dict[str, Any]]
- list_stored_procedures(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all stored procedures in the container.
- list_triggers(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all triggers in the container.
- list_user_defined_functions(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all the user-defined functions in the container.
- query_stored_procedures(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Return all stored procedures matching the given query.
- Parameters:
- Returns:
An Iterable of stored procedures (dicts).
- Return type:
Iterable[Dict[str, Any]]
- query_triggers(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Return all triggers matching the given query.
- Parameters:
- Returns:
An Iterable of triggers (dicts).
- Return type:
- query_user_defined_functions(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Return user-defined functions matching a given query.
- Parameters:
- Returns:
An Iterable of user-defined functions (dicts).
- Return type:
Iterable[Dict[str, Any]]
- 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:
- Returns:
A dict representing the stored procedure after replace went through.
- Raises:
CosmosHttpResponseError – If the replace operation failed or the stored procedure with given id does not exist.
- Return type:
Dict[str, Any]
- 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:
- Returns:
A dict representing the trigger after replace went through.
- Raises:
CosmosHttpResponseError – If the replace operation failed or the trigger with given id does not exist.
- Return type:
Dict[str, Any]
- 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 UDF does not already exist in the container, an exception is raised.
- Parameters:
- Returns:
A dict representing the user-defined function after replace went through.
- Raises:
CosmosHttpResponseError – If the replace operation failed or the user-defined function with the given id does not exist.
- Return type:
Dict[str, Any]
azure.cosmos.user module¶
Create, read, update and delete users in the Azure Cosmos DB SQL API service.
- class azure.cosmos.user.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.- create_permission(body: Dict[str, Any], **kwargs: Any) Permission [source]¶
Create a permission for the user.
To update or replace an existing permision, 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) – A callable invoked with the response metadata.
- Returns:
A dict representing the new permission.
- Raises:
CosmosHttpResponseError – If the given permission couldn’t be created.
- Return type:
Dict[str, Any]
- delete_permission(permission: str | Permission | Mapping[str, Any], **kwargs) None [source]¶
Delete the specified permission from the user.
If the permission does not already exist, an exception is raised.
- Parameters:
permission (Union[str, Permission, Dict[str, Any]]) – The ID (name), dict representing the properties or
Permission
instance of the permission to be replaced.- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Raises:
CosmosHttpResponseError – The permission wasn’t deleted successfully.
CosmosResourceNotFoundError – The permission does not exist for the user.
- Return type:
None
- get_permission(permission: str | Permission | Mapping[str, Any], **kwargs: Any) Permission [source]¶
Get the permission identified by id.
- Parameters:
permission (Union[str, Permission, Dict[str, Any]]) – The ID (name), dict representing the properties or
Permission
instance of the permission to be retrieved.- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
A dict representing the retrieved permission.
- Raises:
CosmosHttpResponseError – If the given permission couldn’t be retrieved.
- Return type:
Dict[str, Any]
- list_permissions(max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
List all permission for the user.
- query_permissions(query: str, parameters: List[Dict[str, Any]] | None = None, max_item_count: int | None = None, **kwargs: Any) ItemPaged[Dict[str, Any]] [source]¶
Return all permissions matching the given query.
- Parameters:
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
An Iterable of permissions (dicts).
- Return type:
Iterable[Dict[str, Any]]
- read(**kwargs: Any) Dict[str, Any] [source]¶
Read user properties.
- Keyword Arguments:
response_hook (Callable) – A callable invoked with the response metadata.
- Returns:
A dictionary of the retrieved user properties.
- Raises:
CosmosHttpResponseError – If the given user couldn’t be retrieved.
- Return type:
- replace_permission(permission: str | Permission | Mapping[str, Any], body: Dict[str, Any], **kwargs) 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, Permission, Dict[str, Any]]) – 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) – A callable invoked with the response metadata.
- Returns:
A dict representing the permission after replace went through.
- Raises:
CosmosHttpResponseError – If the replace operation failed or the permission with given id does not exist.
- Return type:
Dict[str, Any]
- 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) – A callable invoked with the response metadata.
- Returns:
A dict representing the upserted permission.
- Raises:
CosmosHttpResponseError – If the given permission could not be upserted.
- Return type:
Dict[str, Any]