azure-cosmos


Nameazure-cosmos JSON
Version 4.6.0 PyPI version JSON
download
home_pagehttps://github.com/Azure/azure-sdk-for-python
SummaryMicrosoft Azure Cosmos Client Library for Python
upload_time2024-03-14 23:08:48
maintainerMicrosoft
docs_urlNone
authorMicrosoft Corporation
requires_python>=3.8
licenseMIT License
keywords azure azure sdk
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            ## _Disclaimer_
_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_

# Azure Cosmos DB SQL API client library for Python

Azure Cosmos DB is a globally distributed, multi-model database service that supports document, key-value, wide-column, and graph databases.

Use the Azure Cosmos DB SQL API SDK for Python to manage databases and the JSON documents they contain in this NoSQL database service. High level capabilities are:

* Create Cosmos DB **databases** and modify their settings
* Create and modify **containers** to store collections of JSON documents
* Create, read, update, and delete the **items** (JSON documents) in your containers
* Query the documents in your database using **SQL-like syntax**

[SDK source code][source_code]
| [Package (PyPI)][cosmos_pypi]
| [Package (Conda)](https://anaconda.org/microsoft/azure-cosmos/)
| [API reference documentation][ref_cosmos_sdk]
| [Product documentation][cosmos_docs]
| [Samples][cosmos_samples]

> This SDK is used for the [SQL API](https://docs.microsoft.com/azure/cosmos-db/sql-query-getting-started). For all other APIs, please check the [Azure Cosmos DB documentation](https://docs.microsoft.com/azure/cosmos-db/introduction) to evaluate the best SDK for your project.

## Getting started

### Important update on Python 2.x Support

New releases of this SDK won't support Python 2.x starting January 1st, 2022. Please check the [CHANGELOG](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cosmos/azure-cosmos/CHANGELOG.md) for more information.

### Prerequisites

* Azure subscription - [Create a free account][azure_sub]
* Azure [Cosmos DB account][cosmos_account] - SQL API
* [Python 3.6+][python]

If you need a Cosmos DB SQL API account, you can create one with this [Azure CLI][azure_cli] command:

```Bash
az cosmosdb create --resource-group <resource-group-name> --name <cosmos-account-name>
```

### Install the package

```bash
pip install azure-cosmos
```

#### Configure a virtual environment (optional)

Although not required, you can keep your base system and Azure SDK environments isolated from one another if you use a virtual environment. Execute the following commands to configure and then enter a virtual environment with [venv][venv]:

```Bash
python3 -m venv azure-cosmosdb-sdk-environment
source azure-cosmosdb-sdk-environment/bin/activate
```

### Authenticate the client

Interaction with Cosmos DB starts with an instance of the [CosmosClient][ref_cosmosclient] class. You need an **account**, its **URI**, and one of its **account keys** to instantiate the client object.

Use the Azure CLI snippet below to populate two environment variables with the database account URI and its primary master key (you can also find these values in the Azure portal). The snippet is formatted for the Bash shell.

```Bash
RES_GROUP=<resource-group-name>
ACCT_NAME=<cosmos-db-account-name>

export ACCOUNT_URI=$(az cosmosdb show --resource-group $RES_GROUP --name $ACCT_NAME --query documentEndpoint --output tsv)
export ACCOUNT_KEY=$(az cosmosdb list-keys --resource-group $RES_GROUP --name $ACCT_NAME --query primaryMasterKey --output tsv)
```

### Create the client

Once you've populated the `ACCOUNT_URI` and `ACCOUNT_KEY` environment variables, you can create the [CosmosClient][ref_cosmosclient].

```python
from azure.cosmos import CosmosClient

import os
URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)
```

### AAD Authentication

You can also authenticate a client utilizing your service principal's AAD credentials and the azure identity package. 
You can directly pass in the credentials information to ClientSecretCredential, or use the DefaultAzureCredential:
```python
from azure.cosmos import CosmosClient
from azure.identity import ClientSecretCredential, DefaultAzureCredential

import os
url = os.environ['ACCOUNT_URI']
tenant_id = os.environ['TENANT_ID']
client_id = os.environ['CLIENT_ID']
client_secret = os.environ['CLIENT_SECRET']

# Using ClientSecretCredential
aad_credentials = ClientSecretCredential(
    tenant_id=tenant_id,
    client_id=client_id,
    client_secret=client_secret)

# Using DefaultAzureCredential (recommended)
aad_credentials = DefaultAzureCredential()

client = CosmosClient(url, aad_credentials)
```
Always ensure that the managed identity you use for AAD authentication has `readMetadata` permissions. <br>
More information on how to set up AAD authentication: [Set up RBAC for AAD authentication](https://docs.microsoft.com/azure/cosmos-db/how-to-setup-rbac) <br>
More information on allowed operations for AAD authenticated clients: [RBAC Permission Model](https://aka.ms/cosmos-native-rbac)

## Key concepts

Once you've initialized a [CosmosClient][ref_cosmosclient], you can interact with the primary resource types in Cosmos DB:

* [Database][ref_database]: A Cosmos DB account can contain multiple databases. When you create a database, you specify the API you'd like to use when interacting with its documents: SQL, MongoDB, Gremlin, Cassandra, or Azure Table. Use the [DatabaseProxy][ref_database] object to manage its containers.

* [Container][ref_container]: A container is a collection of JSON documents. You create (insert), read, update, and delete items in a container by using methods on the [ContainerProxy][ref_container] object.

* Item: An Item is the dictionary-like representation of a JSON document stored in a container. Each Item you add to a container must include an `id` key with a value that uniquely identifies the item within the container.

For more information about these resources, see [Working with Azure Cosmos databases, containers and items][cosmos_resources].


## How to use `enable_cross_partition_query`

The keyword-argument `enable_cross_partition_query` accepts 2 options: `None` (default) or `True`.

## Note on using queries by id

When using queries that try to find items based on an **id** value, always make sure you are passing in a string type variable. Azure Cosmos DB only allows string id values and if you use any other datatype, this SDK will return no results and no error messages.

## Note on client consistency levels

As of release version 4.3.0b3, if a user does not pass in an explicit consistency level to their client initialization,
their client will use their database account's default level. Previously, the default was being set to `Session` consistency.
If for some reason you'd like to keep doing this, you can change your client initialization to include the explicit parameter for this like shown:
```python
from azure.cosmos import CosmosClient

import os
URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY, consistency_level='Session')
```

## Limitations

Currently, the features below are **not supported**. For alternatives options, check the **Workarounds** section below.

### Data Plane Limitations:

* Group By queries
* Queries with COUNT from a DISTINCT subquery: SELECT COUNT (1) FROM (SELECT DISTINCT C.ID FROM C)
* Direct TCP Mode access
* Continuation token support for aggregate cross-partition queries like sorting, counting, and distinct.
Streamable queries like `SELECT * FROM WHERE` *do* support continuation tokens.
* Change Feed: Processor
* Change Feed: Read multiple partitions key values
* Change Feed: Read specific time
* Cross-partition ORDER BY for mixed types
* Enabling diagnostics for async query-type methods

### Control Plane Limitations:

* Get CollectionSizeUsage, DatabaseUsage, and DocumentUsage metrics
* Create Geospatial Index
* Get the connection string
* Get the minimum RU/s of a container

## Workarounds

### Control Plane Limitations Workaround

Typically, you can use [Azure Portal](https://portal.azure.com/), [Azure Cosmos DB Resource Provider REST API](https://docs.microsoft.com/rest/api/cosmos-db-resource-provider), [Azure CLI](https://docs.microsoft.com/cli/azure/azure-cli-reference-for-cosmos-db) or [PowerShell](https://docs.microsoft.com/azure/cosmos-db/manage-with-powershell) for the control plane unsupported limitations.

### Using The Async Client as a Workaround to Bulk
While the SDK supports transactional batch, support for bulk requests is not yet implemented in the Python SDK. You can use the async client along with this [concurrency sample][concurrency_sample] we have developed as a reference for a possible workaround. 
>[WARNING]
> Using the asynchronous client for concurrent operations like shown in this sample will consume a lot of RUs very fast. We **strongly recommend** testing this out against the cosmos emulator first to verify your code works well and avoid incurring charges.



## Boolean Data Type

While the Python language [uses](https://docs.python.org/3/library/stdtypes.html?highlight=boolean#truth-value-testing) "True" and "False" for boolean types, Cosmos DB [accepts](https://docs.microsoft.com/azure/cosmos-db/sql-query-is-bool) "true" and "false" only. In other words, the Python language uses Boolean values with the first uppercase letter and all other lowercase letters, while Cosmos DB and its SQL language use only lowercase letters for those same Boolean values. How to deal with this challenge?

* Your JSON documents created with Python must use "True" and "False", to pass the language validation. The SDK will convert it to "true" and "false" for you. Meaning that "true" and "false" is what will be stored in Cosmos DB.
* If you retrieve those documents with the Cosmos DB Portal's Data Explorer, you will see "true" and "false".
* If you retrieve those documents with this Python SDK, "true" and "false" values will be automatically converted to "True" and "False".

## SQL Queries x FROM Clause Subitems

This SDK uses the [query_items](https://docs.microsoft.com/python/api/azure-cosmos/azure.cosmos.containerproxy?preserve-view=true&view=azure-python#query-items-query--parameters-none--partition-key-none--enable-cross-partition-query-none--max-item-count-none--enable-scan-in-query-none--populate-query-metrics-none----kwargs-) method to submit SQL queries to Azure Cosmos DB.

Cosmos DB SQL language allows you to [get subitems by using the FROM clause](https://docs.microsoft.com/azure/cosmos-db/sql-query-from#get-subitems-by-using-the-from-clause), to reduce the source to a smaller subset. As an example, you can use `select * from Families.children` instead of `select * from Families`. But please note that:

* For SQL queries using the `query_items` method, this SDK demands that you specify the `partition_key` or use the `enable_cross_partition_query` flag.
* If you are getting subitems and specifying the `partition_key`, please make sure that your partition key is included in the subitems, which is not true for most of the cases.

## Max Item Count

This is a parameter of the query_items method, an integer indicating the maximum number of items to be returned per page. The `None` value can be specified to let the service determine the optimal item count. This is the recommended configuration value, and the default behavior of this SDK when it is not set.

## Examples

The following sections provide several code snippets covering some of the most common Cosmos DB tasks, including:

* [Create a database](#create-a-database "Create a database")
* [Create a container](#create-a-container "Create a container")
* [Create an analytical store enabled container](#create-an-analytical-store-enabled-container "Create a container")
* [Get an existing container](#get-an-existing-container "Get an existing container")
* [Insert data](#insert-data "Insert data")
* [Delete data](#delete-data "Delete data")
* [Query the database](#query-the-database "Query the database")
* [Get database properties](#get-database-properties "Get database properties")
* [Get database and container throughputs](#get-database-and-container-throughputs "Get database and container throughputs")
* [Modify container properties](#modify-container-properties "Modify container properties")
* [Using the asynchronous client](#using-the-asynchronous-client "Using the asynchronous client")

### Create a database

After authenticating your [CosmosClient][ref_cosmosclient], you can work with any resource in the account. The code snippet below creates a SQL API database, which is the default when no API is specified when [create_database][ref_cosmosclient_create_database] is invoked.

```python
from azure.cosmos import CosmosClient, exceptions
import os

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)
DATABASE_NAME = 'testDatabase'
try:
    database = client.create_database(DATABASE_NAME)
except exceptions.CosmosResourceExistsError:
    database = client.get_database_client(DATABASE_NAME)
```

### Create a container

This example creates a container with default settings. If a container with the same name already exists in the database (generating a `409 Conflict` error), the existing container is obtained instead.

```python
from azure.cosmos import CosmosClient, PartitionKey, exceptions
import os

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)
DATABASE_NAME = 'testDatabase'
database = client.get_database_client(DATABASE_NAME)
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)
except exceptions.CosmosHttpResponseError:
    raise
```

### Create an analytical store enabled container

This example creates a container with [Analytical Store](https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction) enabled, for reporting, BI, AI, and Advanced Analytics with [Azure Synapse Link](https://docs.microsoft.com/azure/cosmos-db/synapse-link).

The options for analytical_storage_ttl are:

+ 0 or Null or not informed: Not enabled.
+ -1: The data will be stored infinitely.
+ Any other number: the actual ttl, in seconds.


```python
CONTAINER_NAME = 'products'
try:
    container = database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path="/productName"),analytical_storage_ttl=-1)
except exceptions.CosmosResourceExistsError:
    container = database.get_container_client(CONTAINER_NAME)
except exceptions.CosmosHttpResponseError:
    raise
```

The preceding snippets also handle the [CosmosHttpResponseError][ref_httpfailure] exception if the container creation failed. For more information on error handling and troubleshooting, see the [Troubleshooting](#troubleshooting "Troubleshooting") section.

### Get an existing container

Retrieve an existing container from the database:

```python
from azure.cosmos import CosmosClient
import os

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)
DATABASE_NAME = 'testDatabase'
database = client.get_database_client(DATABASE_NAME)
CONTAINER_NAME = 'products'
container = database.get_container_client(CONTAINER_NAME)
```

### Insert data

To insert items into a container, pass a dictionary containing your data to [ContainerProxy.upsert_item][ref_container_upsert_item]. Each item you add to a container must include an `id` key with a value that uniquely identifies the item within the container.

This example inserts several items into the container, each with a unique `id`:

```python
from azure.cosmos import CosmosClient
import os

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)
DATABASE_NAME = 'testDatabase'
database = client.get_database_client(DATABASE_NAME)
CONTAINER_NAME = 'products'
container = database.get_container_client(CONTAINER_NAME)

for i in range(1, 10):
    container.upsert_item({
            'id': 'item{0}'.format(i),
            'productName': 'Widget',
            'productModel': 'Model {0}'.format(i)
        }
    )
```

### Delete data

To delete items from a container, use [ContainerProxy.delete_item][ref_container_delete_item]. The SQL API in Cosmos DB does not support the SQL `DELETE` statement.

```python
from azure.cosmos import CosmosClient
import os

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)
DATABASE_NAME = 'testDatabase'
database = client.get_database_client(DATABASE_NAME)
CONTAINER_NAME = 'products'
container = database.get_container_client(CONTAINER_NAME)

for item in container.query_items(
        query='SELECT * FROM products p WHERE p.productModel = "Model 2"',
        enable_cross_partition_query=True):
    container.delete_item(item, partition_key='Widget')
```

> NOTE: If you are using partitioned collection, the value of the `partitionKey` in the example code above, should be set to the value of the partition key for this particular item, not the name of the partition key column in your collection. This holds true for both point reads and deletes.

### Query the database

A Cosmos DB SQL API database supports querying the items in a container with [ContainerProxy.query_items][ref_container_query_items] using SQL-like syntax.

This example queries a container for items with a specific `id`:

```python
from azure.cosmos import CosmosClient
import os

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)
DATABASE_NAME = 'testDatabase'
database = client.get_database_client(DATABASE_NAME)
CONTAINER_NAME = 'products'
container = database.get_container_client(CONTAINER_NAME)

# Enumerate the returned items
import json
for item in container.query_items(
        query='SELECT * FROM mycontainer r WHERE r.id="item3"',
        enable_cross_partition_query=True):
    print(json.dumps(item, indent=True))
```

> NOTE: Although you can specify any value for the container name in the `FROM` clause, we recommend you use the container name for consistency.

Perform parameterized queries by passing a dictionary containing the parameters and their values to [ContainerProxy.query_items][ref_container_query_items]:

```python
discontinued_items = container.query_items(
    query='SELECT * FROM products p WHERE p.productModel = @model',
    parameters=[
        dict(name='@model', value='Model 7')
    ],
    enable_cross_partition_query=True
)
for item in discontinued_items:
    print(json.dumps(item, indent=True))
```

For more information on querying Cosmos DB databases using the SQL API, see [Query Azure Cosmos DB data with SQL queries][cosmos_sql_queries].

### Get database properties

Get and display the properties of a database:

```python
from azure.cosmos import CosmosClient
import os
import json

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)
DATABASE_NAME = 'testDatabase'
database = client.get_database_client(DATABASE_NAME)
properties = database.read()
print(json.dumps(properties))
```

### Get database and container throughputs

Get and display the throughput values of a database and of a container with dedicated throughput:

```python
from azure.cosmos import CosmosClient
import os
import json

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)

# Database
DATABASE_NAME = 'testDatabase'
database = client.get_database_client(DATABASE_NAME)
db_offer = database.read_offer()
print('Found Offer \'{0}\' for Database \'{1}\' and its throughput is \'{2}\''.format(db_offer.properties['id'], database.id, db_offer.properties['content']['offerThroughput']))

# Container with dedicated throughput only. Will return error "offer not found" for containers without dedicated throughput
CONTAINER_NAME = 'testContainer'
container = database.get_container_client(CONTAINER_NAME)
container_offer = container.read_offer()
print('Found Offer \'{0}\' for Container \'{1}\' and its throughput is \'{2}\''.format(container_offer.properties['id'], container.id, container_offer.properties['content']['offerThroughput']))
```


### Modify container properties

Certain properties of an existing container can be modified. This example sets the default time to live (TTL) for items in the container to 10 seconds:

```python
from azure.cosmos import CosmosClient, PartitionKey
import os
import json

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)
DATABASE_NAME = 'testDatabase'
database = client.get_database_client(DATABASE_NAME)
CONTAINER_NAME = 'products'
container = database.get_container_client(CONTAINER_NAME)

database.replace_container(
    container,
    partition_key=PartitionKey(path="/productName"),
    default_ttl=10,
)
# Display the new TTL setting for the container
container_props = container.read()
print(json.dumps(container_props['defaultTtl']))
```

For more information on TTL, see [Time to Live for Azure Cosmos DB data][cosmos_ttl].

### Using the asynchronous client

The asynchronous cosmos client is a separate client that looks and works in a similar fashion to the existing synchronous client. However, the async client needs to be imported separately and its methods need to be used with the async/await keywords.
The Async client needs to be initialized and closed after usage, which can be done manually or with the use of a context manager. The example below shows how to do so manually. We don't recommend doing it this way, since it requires that you manually call __aenter__() before using the client.

```python
from azure.cosmos.aio import CosmosClient
import os

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
DATABASE_NAME = 'testDatabase'
CONTAINER_NAME = 'products'    

async def create_products():
    client = CosmosClient(URL, credential=KEY)
    await client.__aenter__() # this piece is important for the SDK to cache account information
    database = client.get_database_client(DATABASE_NAME)
    container = database.get_container_client(CONTAINER_NAME)
    for i in range(10):
        await container.upsert_item({
                'id': 'item{0}'.format(i),
                'productName': 'Widget',
                'productModel': 'Model {0}'.format(i)
            }
        )
    await client.close() # the async client must be closed manually if it's not initialized in a with statement
```

Instead of manually opening and closing the client, it is highly recommended to use the `async with` keywords. This creates a context manager that will initialize and later close the client once you're out of the statement, as well as cache important information the SDK needs. The example below shows how to do so.

```python
from azure.cosmos.aio import CosmosClient
import os

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
DATABASE_NAME = 'testDatabase'
CONTAINER_NAME = 'products'

async def create_products():
    async with CosmosClient(URL, credential=KEY) as client: # the with statement will automatically initialize and close the async client
        database = client.get_database_client(DATABASE_NAME)
        container = database.get_container_client(CONTAINER_NAME)
        for i in range(10):
            await container.upsert_item({
                    'id': 'item{0}'.format(i),
                    'productName': 'Widget',
                    'productModel': 'Model {0}'.format(i)
                }
            )
```

### Queries with the asynchronous client

Unlike the synchronous client, the async client does not have an `enable_cross_partition` flag in the request. Queries without a specified partition key value will attempt to do a cross partition query by default. 

Query results can be iterated, but the query's raw output returns an asynchronous iterator. This means that each object from the iterator is an awaitable object, and does not yet contain the true query result. In order to obtain the query results you can use an async for loop, which awaits each result as you iterate on the object, or manually await each query result as you iterate over the asynchronous iterator.

Since the query results are an asynchronous iterator, they can't be cast into lists directly; instead, if you need to create lists from your results, use an async for loop or Python's list comprehension to populate a list:

```python
from azure.cosmos.aio import CosmosClient
import os

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = CosmosClient(URL, credential=KEY)
DATABASE_NAME = 'testDatabase'
database = client.get_database_client(DATABASE_NAME)
CONTAINER_NAME = 'products'
container = database.get_container_client(CONTAINER_NAME)

async def create_lists():
    results = container.query_items(
            query='SELECT * FROM products p WHERE p.productModel = "Model 2"')

    # iterates on "results" iterator to asynchronously create a complete list of the actual query results

    item_list = []
    async for item in results:
        item_list.append(item)

    # Asynchronously creates a complete list of the actual query results. This code performs the same action as the for-loop example above.
    item_list = [item async for item in results]
    await client.close()
```

### Using Integrated Cache
An integrated cache is an in-memory cache that helps you ensure manageable costs and low latency as your request volume grows. The integrated cache has two parts: an item cache for point reads and a query cache for queries. The code snippet below shows you how to use this feature with the point read and query cache methods.

The benefit of using this is that the point reads and queries that hit the integrated cache won't use any RUs. This means you will have a much lower per-operation cost than reads from the backend.

[How to configure the Azure Cosmos DB integrated cache (Preview)][cosmos_configure_integrated_cache]

```python
import azure.cosmos.cosmos_client as cosmos_client
import os

URL = os.environ['ACCOUNT_URI']
KEY = os.environ['ACCOUNT_KEY']
client = cosmos_client.CosmosClient(URL, credential=KEY)
DATABASE_NAME = 'testDatabase'
database = client.get_database_client(DATABASE_NAME)
CONTAINER_NAME = 'testContainer'
container = database.get_container_client(CONTAINER_NAME)

def integrated_cache_snippet():
    item_id = body['id'] 
    query = 'SELECT * FROM c'

    #item cache
    container.read_item(item=item_id, partition_key=item_id, max_integrated_cache_staleness_in_ms=30000)

    #query cache   
    container.query_items(query=query,
         partition_key=item_id, max_integrated_cache_staleness_in_ms=30000)
```
For more information on Integrated Cache, see [Azure Cosmos DB integrated cache - Overview][cosmos_integrated_cache].

### Using Transactional Batch
Transactional batch requests allow you to send several operations to be executed at once within the same partition key.
If all operations succeed in the order they're described within the transactional batch operation, the transaction will be committed.
However, if any operation fails, the entire transaction is rolled back.

Transactional batches have a limit of 100 operations per batch, and a total size limit of 1.2Mb for the
batch operations being passed in.

Transactional Batch operations look very similar to the singular operations apis, and are tuples containing
(`operation_type_string`, `args_tuple`, `batch_operation_kwargs_dictionary`), with the kwargs dictionary being optional:
```python
batch_operations = [
        ("create", (item_body,), kwargs),
        ("replace", (item_id, item_body), kwargs),
        ("read", (item_id,), kwargs),
        ("upsert", (item_body,), kwargs),
        ("patch", (item_id, operations), kwargs),
        ("delete", (item_id,), kwargs),
    ]
batch_results = container.execute_item_batch(batch_operations=batch_operations, partition_key=partition_key)
```
The batch operation kwargs dictionary is limited, and only takes a total of three different key values.
In the case of wanting to use conditional patching within the batch, the use of `filter_predicate` key is available for the
patch operation, or in case of wanting to use etags with any of the operations, the use of the `if_match_etag`/`if_none_match_etag`
keys is available as well.
```python
batch_operations = [
        ("replace", (item_id, item_body), {"if_match_etag": etag}),
        ("patch", (item_id, operations), {"filter_predicate": filter_predicate, "if_none_match_etag": etag}),
    ]
```

We also have some samples showing these transactional batch operations in action with both the [sync][sample_document_mgmt]
and [async][sample_document_mgmt_async] clients.

If there is a failure for an operation within the batch, the SDK will raise a `CosmosBatchOperationError` letting you know which operation failed,
as well as containing the list of failed responses for the failed request.

For more information on Transactional Batch, see [Azure Cosmos DB Transactional Batch][cosmos_transactional_batch].

## Troubleshooting

### General

When you interact with Cosmos DB using the Python SDK, exceptions returned by the service correspond to the same HTTP status codes returned for REST API requests:

[HTTP Status Codes for Azure Cosmos DB][cosmos_http_status_codes]

For example, if you try to create a container using an ID (name) that's already in use in your Cosmos DB database, a `409` error is returned, indicating the conflict. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error.

```python
try:
    database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path="/productName"))
except exceptions.CosmosResourceExistsError:
    print("""Error creating container
HTTP status code 409: The ID (name) provided for the container is already in use.
The container name must be unique within the database.""")

```
### Logging Diagnostics

This library uses the standard
[logging](https://docs.python.org/3.5/library/logging.html) library for logging diagnostics.
Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO
level.

Detailed DEBUG level logging, including request/response bodies and unredacted
headers, can be enabled on a client with the `logging_enable` argument:
```python
import sys
import logging
from azure.cosmos import CosmosClient

# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

# This client will log detailed information about its HTTP sessions, at DEBUG level
client = CosmosClient(URL, credential=KEY, logging_enable=True)
```

Similarly, `logging_enable` can enable detailed logging for a single operation,
even when it isn't enabled for the client:
```python
database = client.create_database(DATABASE_NAME, logging_enable=True)
```
Alternatively, you can log using the CosmosHttpLoggingPolicy, which extends from the azure core HttpLoggingPolicy, by passing in your logger to the `logger` argument.
By default, it will use the behaviour from HttpLoggingPolicy. Passing in the `enable_diagnostics_logging` argument will enable the
CosmosHttpLoggingPolicy, and will have additional information in the response relevant to debugging Cosmos issues.
```python
import logging
from azure.cosmos import CosmosClient

#Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a file output
handler = logging.FileHandler(filename="azure")
logger.addHandler(handler)

# This client will log diagnostic information from the HTTP session by using the CosmosHttpLoggingPolicy.
# Since we passed in the logger to the client, it will log information on every request.
client = CosmosClient(URL, credential=KEY, logger=logger, enable_diagnostics_logging=True)
```
Similarly, logging can be enabled for a single operation by passing in a logger to the singular request.
However, if you desire to use the CosmosHttpLoggingPolicy to obtain additional information, the `enable_diagnostics_logging` argument needs to be passed in at the client constructor.
```python
# This example enables the CosmosHttpLoggingPolicy and uses it with the `logger` passed in to the `create_database` request.
client = CosmosClient(URL, credential=KEY, enable_diagnostics_logging=True)
database = client.create_database(DATABASE_NAME, logger=logger)
```

### Telemetry
Azure Core provides the ability for our Python SDKs to use OpenTelemetry with them. The only packages that need to be installed
to use this functionality are the following:
```bash
pip install azure-core-tracing-opentelemetry
pip install opentelemetry-sdk
```
For more information on this, we recommend taking a look at this [document](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core-tracing-opentelemetry/README.md) 
from Azure Core describing how to set it up. We have also added a [sample file][telemetry_sample] to show how it can
be used with our SDK. This works the same way regardless of the Cosmos client you are using.

## Next steps

For more extensive documentation on the Cosmos DB service, see the [Azure Cosmos DB documentation][cosmos_docs] on docs.microsoft.com.

<!-- LINKS -->
[azure_cli]: https://docs.microsoft.com/cli/azure
[azure_portal]: https://portal.azure.com
[azure_sub]: https://azure.microsoft.com/free/
[cloud_shell]: https://docs.microsoft.com/azure/cloud-shell/overview
[cosmos_account_create]: https://docs.microsoft.com/azure/cosmos-db/how-to-manage-database-account
[cosmos_account]: https://docs.microsoft.com/azure/cosmos-db/account-overview
[cosmos_container]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-containers
[cosmos_database]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-databases
[cosmos_docs]: https://docs.microsoft.com/azure/cosmos-db/
[cosmos_samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples
[cosmos_pypi]: https://pypi.org/project/azure-cosmos/
[cosmos_http_status_codes]: https://docs.microsoft.com/rest/api/cosmos-db/http-status-codes-for-cosmosdb
[cosmos_item]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-items
[cosmos_models]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/azure/cosmos/_models.py
[cosmos_request_units]: https://docs.microsoft.com/azure/cosmos-db/request-units
[cosmos_resources]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items
[cosmos_sql_queries]: https://docs.microsoft.com/azure/cosmos-db/how-to-sql-query
[cosmos_ttl]: https://docs.microsoft.com/azure/cosmos-db/time-to-live
[cosmos_integrated_cache]: https://docs.microsoft.com/azure/cosmos-db/integrated-cache
[cosmos_configure_integrated_cache]: https://docs.microsoft.com/azure/cosmos-db/how-to-configure-integrated-cache
[python]: https://www.python.org/downloads/
[ref_container_delete_item]: https://aka.ms/azsdk-python-cosmos-ref-delete-item
[ref_container_query_items]: https://aka.ms/azsdk-python-cosmos-ref-query-items
[ref_container_upsert_item]: https://aka.ms/azsdk-python-cosmos-ref-upsert-item
[ref_container]: https://aka.ms/azsdk-python-cosmos-ref-container
[ref_cosmos_sdk]: https://aka.ms/azsdk-python-cosmos-ref
[ref_cosmosclient_create_database]: https://aka.ms/azsdk-python-cosmos-ref-create-database
[ref_cosmosclient]: https://aka.ms/azsdk-python-cosmos-ref-cosmos-client
[ref_database]: https://aka.ms/azsdk-python-cosmos-ref-database
[ref_httpfailure]: https://aka.ms/azsdk-python-cosmos-ref-http-failure
[sample_database_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/database_management.py
[sample_document_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/document_management.py
[sample_document_mgmt_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/document_management_async.py
[sample_examples_misc]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/examples.py
[source_code]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos
[venv]: https://docs.python.org/3/library/venv.html
[virtualenv]: https://virtualenv.pypa.io
[telemetry_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/tracing_open_telemetry.py
[timeouts_document]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/docs/TimeoutAndRetriesConfig.md
[cosmos_transactional_batch]: https://learn.microsoft.com/azure/cosmos-db/nosql/transactional-batch
[cosmos_concurrency_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/concurrency_sample.py

## Contributing

This project welcomes contributions and suggestions.  Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

## Release History

### 4.6.0 (2024-03-14)

#### Features Added
* GA release of hierarchical partitioning, index metrics and transactional batch.

#### Bugs Fixed
* Keyword arguments were not being passed down for `create_container_if_not_exists()` methods. See [PR 34286](https://github.com/Azure/azure-sdk-for-python/pull/34286).

#### Other Changes
* Made several updates to the type hints used throughout the SDK for greater detail. See [PR 33269](https://github.com/Azure/azure-sdk-for-python/pull/33269), [PR 33341](https://github.com/Azure/azure-sdk-for-python/pull/33341), [PR 33738](https://github.com/Azure/azure-sdk-for-python/pull/33738).

### 4.5.2b5 (2024-03-02)

#### Bugs Fixed
* Fixed bug with async lock not properly releasing on async global endpoint manager. see [PR 34579](https://github.com/Azure/azure-sdk-for-python/pull/34579).

#### Other Changes
* Marked `computed_properties` keyword as provisional, un-marked `continuation_token_limit` as provisional. See [PR 34207](https://github.com/Azure/azure-sdk-for-python/pull/34207).

### 4.5.2b4 (2024-02-02)
This version and all future versions will require Python 3.8+.

#### Features Added
* Added **preview** support for Computed Properties on Python SDK (Must be enabled on the account level before it can be used). See [PR 33626](https://github.com/Azure/azure-sdk-for-python/pull/33626).

#### Bugs Fixed
* Made use of `response_hook` thread-safe in the sync client. See [PR 33790](https://github.com/Azure/azure-sdk-for-python/pull/33790).
* Fixed bug with the session container not being properly maintained. See [33738](https://github.com/Azure/azure-sdk-for-python/pull/33738).

### 4.5.2b3 (2023-11-10)

#### Features Added
* Added support for capturing Index Metrics in query operations. See [PR 33034](https://github.com/Azure/azure-sdk-for-python/pull/33034).

### 4.5.2b2 (2023-10-31)

#### Features Added
* Added support for Transactional Batch. See [PR 32508](https://github.com/Azure/azure-sdk-for-python/pull/32508).
* Added **preview** support for Priority Based Throttling/Priority Based Execution (Must be enabled at the account level before it can be used). See [PR 32441](https://github.com/Azure/azure-sdk-for-python/pull/32441/).

### 4.5.2b1 (2023-10-17)

#### Features Added
* Added support for Hierarchical Partitioning, also known as Subpartitioning. See [PR 31121](https://github.com/Azure/azure-sdk-for-python/pull/31121).

#### Bugs Fixed
* Small fix to the `offer_throughput` option in the async client's `create_database_if_not_exists` method, which was previously misspelled as `offerThroughput`.
See [PR 32076](https://github.com/Azure/azure-sdk-for-python/pull/32076).

#### Other Changes
* Marked the outdated `diagnostics.py` file for deprecation since we now recommend the use of our `CosmosHttpLoggingPolicy` for diagnostics.
For more on the `CosmosHttpLoggingPolicy` see our [README](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos#logging-diagnostics).

### 4.5.1 (2023-09-12)

#### Bugs Fixed
* Fixed bug when query with DISTINCT + OFFSET/LIMIT operators returns unexpected result. See [PR 31925](https://github.com/Azure/azure-sdk-for-python/pull/31925).

#### Other Changes
* Added additional checks for resource creation using specific characters that cause issues. See [PR 31861](https://github.com/Azure/azure-sdk-for-python/pull/31861).

### 4.5.0 (2023-08-09)

#### Features Added
* Added support for continuation tokens for streamable cross partition queries. See [PR 31189](https://github.com/Azure/azure-sdk-for-python/pull/31189).

#### Bugs Fixed
* Fixed bug with async `create_database_if_not_exists` method not working when passing `offer_throughput` as an option. See [PR 31478](https://github.com/Azure/azure-sdk-for-python/pull/31478).

#### Other Changes
* Renamed `response_continuation_token_limit_in_kb` to `continuation_token_limit` for GA. See [PR 31532](https://github.com/Azure/azure-sdk-for-python/pull/31532).

### 4.4.1b1 (2023-07-25)

#### Features Added
* Added ability to limit continuation token size when querying for items. See [PR 30731](https://github.com/Azure/azure-sdk-for-python/pull/30731)

#### Bugs Fixed
* Fixed bug with async patch_item method. See [PR 30804](https://github.com/Azure/azure-sdk-for-python/pull/30804).

### 4.4.0 (2023-06-09)

#### Features Added
- GA release of Patch API and Delete All Items By Partition Key

### 4.4.0b2 (2023-05-22)

#### Features Added
* Added conditional patching for Patch operations. See [PR 30455](https://github.com/Azure/azure-sdk-for-python/pull/30455).

#### Bugs Fixed
* Fixed bug with non english locales causing an error with the RFC 1123 Date Format. See [PR 30125](https://github.com/Azure/azure-sdk-for-python/pull/30125).

#### Other Changes
* Refactoring of our client `connection_timeout` and `request_timeout` configurations. See [PR 30171](https://github.com/Azure/azure-sdk-for-python/pull/30171).

### 4.4.0b1 (2023-04-11)

#### Features Added
 - Added **preview** delete all items by partition key functionality. See [PR 29186](https://github.com/Azure/azure-sdk-for-python/pull/29186). For more information on Partition Key Delete, please see [Azure Cosmos DB Partition Key Delete](https://learn.microsoft.com/azure/cosmos-db/nosql/how-to-delete-by-partition-key?tabs=python-example).
 - Added **preview** partial document update (Patch API) functionality and container methods for patching items with operations. See [PR 29497](https://github.com/Azure/azure-sdk-for-python/pull/29497). For more information on Patch, please see [Azure Cosmos DB Partial Document Update](https://learn.microsoft.com/azure/cosmos-db/partial-document-update).

#### Bugs Fixed
* Fixed bug in method `create_container_if_not_exists()` of async database client for unexpected kwargs being passed into `read()` method used internally. See [PR 29136](https://github.com/Azure/azure-sdk-for-python/pull/29136).
* Fixed bug with method `query_items()` of our async container class, where partition key and cross partition headers would both be set when using partition keys. See [PR 29366](https://github.com/Azure/azure-sdk-for-python/pull/29366/).
* Fixed bug with client not properly surfacing errors for invalid credentials and identities with insufficient permissions. Users running into 'NoneType has no attribute ConsistencyPolicy' errors when initializing their clients will now see proper authentication exceptions. See [PR 29256](https://github.com/Azure/azure-sdk-for-python/pull/29256).

#### Other Changes
* Removed use of `six` package within the SDK.

### 4.3.1 (2023-02-23)

#### Features Added
 - Added `correlated_activity_id` for query operations.
 - Added cross regional retries for Service Unavailable/Request Timeouts for read/Query Plan operations.
 - GA release of CosmosHttpLoggingPolicy and autoscale feature.

#### Bugs Fixed
- Bug fix to address queries with VALUE MAX (or any other aggregate) that run into an issue if the query is executed on a container with at least one "empty" partition.

### 4.3.1b1 (2022-09-19)

#### Features Added
- GA release of integrated cache functionality. For more information on integrated cache please see [Azure Cosmos DB integrated cache](https://docs.microsoft.com/azure/cosmos-db/integrated-cache).
- Added ability to replace analytical ttl on containers. For more information on analytical ttl please see [Azure Cosmos DB analytical store](https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction).
- Added `CosmosHttpLoggingPolicy` to replace `HttpLoggingPolicy` for logging HTTP sessions.
- Added the ability to create containers and databases with autoscale properties for the sync and async clients.
- Added the ability to update autoscale throughput properties.

#### Bugs Fixed
- Fixed parsing of args for overloaded `container.read()` method.
- Fixed `validate_cache_staleness_value()` method to allow max_integrated_cache_staleness to be an integer greater than or equal to 0.
- Fixed `__aiter__()` method by removing the async keyword.

### 4.3.0 (2022-05-23)
#### Features Added
- GA release of Async I/O APIs, including all changes from 4.3.0b1 to 4.3.0b4.

#### Breaking Changes
- Method signatures have been updated to use keyword arguments instead of positional arguments for most method options in the async client.
- Bugfix: Automatic Id generation for items was turned on for `upsert_items()` method when no 'id' value was present in document body.
Method call will now require an 'id' field to be present in the document body.

#### Other Changes
- Deprecated offer-named methods in favor of their new throughput-named counterparts (`read_offer` -> `get_throughput`).
- Marked the GetAuthorizationHeader method for deprecation since it will no longer be public in a future release.
- Added samples showing how to configure retry options for both the sync and async clients.
- Deprecated the `connection_retry_policy` and `retry_options` options in the sync client.
- Added user warning to non-query methods trying to use `populate_query_metrics` options.

### 4.3.0b4 (2022-04-07)

#### Features Added
- Added support for AAD authentication for the async client.
- Added support for AAD authentication for the sync client.

#### Other Changes
- Changed `_set_partition_key` return typehint in async client.

### 4.3.0b3 (2022-03-10)

>[WARNING]
>The default `Session` consistency bugfix will impact customers whose database accounts have a `Bounded Staleness` or `Strong`
> consistency level, and were previously not sending `Session` as a consistency_level parameter when initializing
> their clients.
> Default consistency level for the sync and async clients is no longer "Session" and will instead be set to the 
  consistency level of the user's cosmos account setting on initialization if not passed during client initialization. 
> Please see [Consistency Levels in Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/consistency-levels) 
> for more details on consistency levels, or the README section on this change [here](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos#note-on-client-consistency-levels).

#### Features Added
- Added new **provisional** `max_integrated_cache_staleness_in_ms` parameter to read item and query items APIs in order
  to make use of the **preview** CosmosDB integrated cache functionality [See PR #22946](https://github.com/Azure/azure-sdk-for-python/pull/22946).
  Please see [Azure Cosmos DB integrated cache](https://docs.microsoft.com/azure/cosmos-db/integrated-cache) for more details.
- Added support for split-proof queries for the async client.

### Bugs fixed
- Default consistency level for the sync and async clients is no longer `Session` and will instead be set to the 
  consistency level of the user's cosmos account setting on initialization if not passed during client initialization. 
  This change will impact client application in terms of RUs and latency. Users relying on default `Session` consistency
  will need to pass it explicitly if their account consistency is different than `Session`.
  Please see [Consistency Levels in Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/consistency-levels) for more details.  
- Fixed invalid request body being sent when passing in `serverScript` body parameter to replace operations for trigger, sproc and udf resources.
- Moved `is_system_key` logic in async client.
- Fixed TypeErrors not being thrown when passing in invalid connection retry policies to the client.

### 4.3.0b2 (2022-01-25)

This version and all future versions will require Python 3.6+. Python 2.7 is no longer supported.
We will also be removing support for Python 3.6 and will only support Python 3.7+ starting December 2022.

#### Features Added
- Added support for split-proof queries for the sync client.

#### Other Changes
- Added async user agent for async client.

### 4.3.0b1 (2021-12-14)

#### Features Added
- Added language native async i/o client.

### 4.2.0 (2020-10-08)

**Bug fixes**
- Fixed bug where continuation token is not honored when query_iterable is used to get results by page. Issue #13265.
- Fixed bug where resource tokens not being honored for document reads and deletes. Issue #13634.

**New features**
- Added support for passing partitionKey while querying changefeed. Issue #11689.

### 4.1.0 (2020-08-10)

- Added deprecation warning for "lazy" indexing mode. The backend no longer allows creating containers with this mode and will set them to consistent instead.

**New features**
- Added the ability to set the analytical storage TTL when creating a new container.

**Bug fixes**
- Fixed support for dicts as inputs for get_client APIs.
- Fixed Python 2/3 compatibility in query iterators.
- Fixed type hint error. Issue #12570 - thanks @sl-sandy.
- Fixed bug where options headers were not added to upsert_item function. Issue #11791 - thank you @aalapatirvbd.
- Fixed error raised when a non string ID is used in an item. It now raises TypeError rather than AttributeError. Issue #11793 - thank you @Rabbit994.


### 4.0.0 (2020-05-20)

- Stable release.
- Added HttpLoggingPolicy to pipeline to enable passing in a custom logger for request and response headers.


## 4.0.0b6

- Fixed bug in synchronized_request for media APIs.
- Removed MediaReadMode and MediaRequestTimeout from ConnectionPolicy as media requests are not supported.


## 4.0.0b5

- azure.cosmos.errors module deprecated and replaced by azure.cosmos.exceptions
- The access condition parameters (`access_condition`, `if_match`, `if_none_match`) have been deprecated in favor of separate `match_condition` and `etag` parameters.
- Fixed bug in routing map provider.
- Added query Distinct, Offset and Limit support.
- Default document query execution context now used for
    - ChangeFeed queries
    - single partition queries (partitionkey, partitionKeyRangeId is present in options)
    - Non document queries
- Errors out for aggregates on multiple partitions, with enable cross partition query set to true, but no "value" keyword present
- Hits query plan endpoint for other scenarios to fetch query plan
- Added `__repr__` support for Cosmos entity objects.
- Updated documentation.


## 4.0.0b4

- Added support for a `timeout` keyword argument to all operations to specify an absolute timeout in seconds
  within which the operation must be completed. If the timeout value is exceeded, a `azure.cosmos.errors.CosmosClientTimeoutError` will be raised.
- Added a new `ConnectionRetryPolicy` to manage retry behaviour during HTTP connection errors.
- Added new constructor and per-operation configuration keyword arguments:
    - `retry_total` - Maximum retry attempts.
    - `retry_backoff_max` - Maximum retry wait time in seconds.
    - `retry_fixed_interval` - Fixed retry interval in milliseconds.
    - `retry_read` - Maximum number of socket read retry attempts.
    - `retry_connect` - Maximum number of connection error retry attempts.
    - `retry_status` - Maximum number of retry attempts on error status codes.
    - `retry_on_status_codes` - A list of specific status codes to retry on.
    - `retry_backoff_factor` - Factor to calculate wait time between retry attempts.

## 4.0.0b3

- Added `create_database_if_not_exists()` and `create_container_if_not_exists` functionalities to CosmosClient and Database respectively.

## 4.0.0b2

Version 4.0.0b2 is the second iteration in our efforts to build a more Pythonic client library.

**Breaking changes**

- The client connection has been adapted to consume the HTTP pipeline defined in `azure.core.pipeline`.
- Interactive objects have now been renamed as proxies. This includes:
    - `Database` -> `DatabaseProxy`
    - `User` -> `UserProxy`
    - `Container` -> `ContainerProxy`
    - `Scripts` -> `ScriptsProxy`
- The constructor of `CosmosClient` has been updated:
    - The `auth` parameter has been renamed to `credential` and will now take an authentication type directly. This means the master key value, a dictionary of resource tokens, or a list of permissions can be passed in. However the old dictionary format is still supported.
    - The `connection_policy` parameter has been made a keyword only parameter, and while it is still supported, each of the individual attributes of the policy can now be passed in as explicit keyword arguments:
        - `request_timeout`
        - `media_request_timeout`
        - `connection_mode`
        - `media_read_mode`
        - `proxy_config`
        - `enable_endpoint_discovery`
        - `preferred_locations`
        - `multiple_write_locations`
- A new classmethod constructor has been added to `CosmosClient` to enable creation via a connection string retrieved from the Azure portal.
- Some `read_all` operations have been renamed to `list` operations:
    - `CosmosClient.read_all_databases` -> `CosmosClient.list_databases`
    - `Container.read_all_conflicts` -> `ContainerProxy.list_conflicts`
    - `Database.read_all_containers` -> `DatabaseProxy.list_containers`
    - `Database.read_all_users` -> `DatabaseProxy.list_users`
    - `User.read_all_permissions` -> `UserProxy.list_permissions`
- All operations that take `request_options` or `feed_options` parameters, these have been moved to keyword only parameters. In addition, while these options dictionaries are still supported, each of the individual options within the dictionary are now supported as explicit keyword arguments.
- The error hierarchy is now inherited from `azure.core.AzureError` instead of `CosmosError` which has been removed.
    - `HTTPFailure` has been renamed to `CosmosHttpResponseError`
    - `JSONParseFailure` has been removed and replaced by `azure.core.DecodeError`
    - Added additional errors for specific response codes:
        - `CosmosResourceNotFoundError` for status 404
        - `CosmosResourceExistsError` for status 409
        - `CosmosAccessConditionFailedError` for status 412
- `CosmosClient` can now be run in a context manager to handle closing the client connection.
- Iterable responses (e.g. query responses and list responses) are now of type `azure.core.paging.ItemPaged`. The method `fetch_next_block` has been replaced by a secondary iterator, accessed by the `by_page` method.

## 4.0.0b1

Version 4.0.0b1 is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Cosmos. For more information about this, and preview releases of other Azure SDK libraries, please visit https://aka.ms/azure-sdk-preview1-python.

**Breaking changes: New API design**

- Operations are now scoped to a particular client:
    - `CosmosClient`: This client handles account-level operations. This includes managing service properties and listing the databases within an account.
    - `Database`: This client handles database-level operations. This includes creating and deleting containers, users and stored procedures. It can be accessed from a `CosmosClient` instance by name.
    - `Container`: This client handles operations for a particular container. This includes querying and inserting items and managing properties.
    - `User`: This client handles operations for a particular user. This includes adding and deleting permissions and managing user properties.
    
    These clients can be accessed by navigating down the client hierarchy using the `get_<child>_client` method. For full details on the new API, please see the [reference documentation](https://aka.ms/azsdk-python-cosmos-ref).
- Clients are accessed by name rather than by Id. No need to concatenate strings to create links.
- No more need to import types and methods from individual modules. The public API surface area is available directly in the `azure.cosmos` package.
- Individual request properties can be provided as keyword arguments rather than constructing a separate `RequestOptions` instance.

## 3.0.2

- Added Support for MultiPolygon Datatype
- Bug Fix in Session Read Retry Policy
- Bug Fix for Incorrect padding issues while decoding base 64 strings

## 3.0.1

- Bug fix in LocationCache
- Bug fix endpoint retry logic
- Fixed documentation

## 3.0.0

- Multi-region write support added
- Naming changes
  - DocumentClient to CosmosClient
  - Collection to Container
  - Document to Item
  - Package name updated to "azure-cosmos"
  - Namespace updated to "azure.cosmos"

## 2.3.3

- Added support for proxy
- Added support for reading change feed
- Added support for collection quota headers
- Bugfix for large session tokens issue
- Bugfix for ReadMedia API
- Bugfix in partition key range cache

## 2.3.2

- Added support for default retries on connection issues.

## 2.3.1

- Updated documentation to reference Azure Cosmos DB instead of Azure DocumentDB.

## 2.3.0

- This SDK version requires the latest version of Azure Cosmos DB Emulator available for download from https://aka.ms/cosmosdb-emulator.

## 2.2.1

- bugfix for aggregate dict
- bugfix for trimming slashes in the resource link
- tests for unicode encoding

## 2.2.0

- Added support for Request Unit per Minute (RU/m) feature.
- Added support for a new consistency level called ConsistentPrefix.

## 2.1.0

- Added support for aggregation queries (COUNT, MIN, MAX, SUM, and AVG).
- Added an option for disabling SSL verification when running against DocumentDB Emulator.
- Removed the restriction of dependent requests module to be exactly 2.10.0.
- Lowered minimum throughput on partitioned collections from 10,100 RU/s to 2500 RU/s.
- Added support for enabling script logging during stored procedure execution.
- REST API version bumped to '2017-01-19' with this release.

## 2.0.1

- Made editorial changes to documentation comments.

## 2.0.0

- Added support for Python 3.5.
- Added support for connection pooling using the requests module.
- Added support for session consistency.
- Added support for TOP/ORDERBY queries for partitioned collections.

## 1.9.0

- Added retry policy support for throttled requests. (Throttled requests receive a request rate too large exception, error code 429.)
  By default, DocumentDB retries nine times for each request when error code 429 is encountered, honoring the retryAfter time in the response header.
  A fixed retry interval time can now be set as part of the RetryOptions property on the ConnectionPolicy object if you want to ignore the retryAfter time returned by server between the retries.
  DocumentDB now waits for a maximum of 30 seconds for each request that is being throttled (irrespective of retry count) and returns the response with error code 429.
  This time can also be overridden in the RetryOptions property on ConnectionPolicy object.

- DocumentDB now returns x-ms-throttle-retry-count and x-ms-throttle-retry-wait-time-ms as the response headers in every request to denote the throttle retry count
  and the cumulative time the request waited between the retries.

- Removed the RetryPolicy class and the corresponding property (retry_policy) exposed on the document_client class and instead introduced a RetryOptions class
  exposing the RetryOptions property on ConnectionPolicy class that can be used to override some of the default retry options.

## 1.8.0

- Added the support for geo-replicated database accounts.
- Test fixes to move the global host and masterKey into the individual test classes.

## 1.7.0

- Added the support for Time To Live(TTL) feature for documents.

## 1.6.1

- Bug fixes related to server side partitioning to allow special characters in partitionkey path.

## 1.6.0

- Added the support for server side partitioned collections feature.

## 1.5.0

- Added Client-side sharding framework to the SDK. Implemented HashPartionResolver and RangePartitionResolver classes.

## 1.4.2

- Implement Upsert. New UpsertXXX methods added to support Upsert feature.
- Implement ID Based Routing. No public API changes, all changes internal.

## 1.3.0

- Release skipped to bring version number in alignment with other SDKs

## 1.2.0

- Supports GeoSpatial index.
- Validates id property for all resources. Ids for resources cannot contain ?, /, #, \\, characters or end with a space.
- Adds new header "index transformation progress" to ResourceResponse.

## 1.1.0

- Implements V2 indexing policy

## 1.0.1

- Supports proxy connection


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Azure/azure-sdk-for-python",
    "name": "azure-cosmos",
    "maintainer": "Microsoft",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "askdocdb@microsoft.com",
    "keywords": "azure,azure sdk",
    "author": "Microsoft Corporation",
    "author_email": "askdocdb@microsoft.com",
    "download_url": "https://files.pythonhosted.org/packages/32/22/06af125a6e05a4f60f3c1bfa79c869ea0dc64be9e7fcadc4c80388cde967/azure-cosmos-4.6.0.tar.gz",
    "platform": null,
    "description": "## _Disclaimer_\n_Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_\n\n# Azure Cosmos DB SQL API client library for Python\n\nAzure Cosmos DB is a globally distributed, multi-model database service that supports document, key-value, wide-column, and graph databases.\n\nUse the Azure Cosmos DB SQL API SDK for Python to manage databases and the JSON documents they contain in this NoSQL database service. High level capabilities are:\n\n* Create Cosmos DB **databases** and modify their settings\n* Create and modify **containers** to store collections of JSON documents\n* Create, read, update, and delete the **items** (JSON documents) in your containers\n* Query the documents in your database using **SQL-like syntax**\n\n[SDK source code][source_code]\n| [Package (PyPI)][cosmos_pypi]\n| [Package (Conda)](https://anaconda.org/microsoft/azure-cosmos/)\n| [API reference documentation][ref_cosmos_sdk]\n| [Product documentation][cosmos_docs]\n| [Samples][cosmos_samples]\n\n> This SDK is used for the [SQL API](https://docs.microsoft.com/azure/cosmos-db/sql-query-getting-started). For all other APIs, please check the [Azure Cosmos DB documentation](https://docs.microsoft.com/azure/cosmos-db/introduction) to evaluate the best SDK for your project.\n\n## Getting started\n\n### Important update on Python 2.x Support\n\nNew releases of this SDK won't support Python 2.x starting January 1st, 2022. Please check the [CHANGELOG](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cosmos/azure-cosmos/CHANGELOG.md) for more information.\n\n### Prerequisites\n\n* Azure subscription - [Create a free account][azure_sub]\n* Azure [Cosmos DB account][cosmos_account] - SQL API\n* [Python 3.6+][python]\n\nIf you need a Cosmos DB SQL API account, you can create one with this [Azure CLI][azure_cli] command:\n\n```Bash\naz cosmosdb create --resource-group <resource-group-name> --name <cosmos-account-name>\n```\n\n### Install the package\n\n```bash\npip install azure-cosmos\n```\n\n#### Configure a virtual environment (optional)\n\nAlthough not required, you can keep your base system and Azure SDK environments isolated from one another if you use a virtual environment. Execute the following commands to configure and then enter a virtual environment with [venv][venv]:\n\n```Bash\npython3 -m venv azure-cosmosdb-sdk-environment\nsource azure-cosmosdb-sdk-environment/bin/activate\n```\n\n### Authenticate the client\n\nInteraction with Cosmos DB starts with an instance of the [CosmosClient][ref_cosmosclient] class. You need an **account**, its **URI**, and one of its **account keys** to instantiate the client object.\n\nUse the Azure CLI snippet below to populate two environment variables with the database account URI and its primary master key (you can also find these values in the Azure portal). The snippet is formatted for the Bash shell.\n\n```Bash\nRES_GROUP=<resource-group-name>\nACCT_NAME=<cosmos-db-account-name>\n\nexport ACCOUNT_URI=$(az cosmosdb show --resource-group $RES_GROUP --name $ACCT_NAME --query documentEndpoint --output tsv)\nexport ACCOUNT_KEY=$(az cosmosdb list-keys --resource-group $RES_GROUP --name $ACCT_NAME --query primaryMasterKey --output tsv)\n```\n\n### Create the client\n\nOnce you've populated the `ACCOUNT_URI` and `ACCOUNT_KEY` environment variables, you can create the [CosmosClient][ref_cosmosclient].\n\n```python\nfrom azure.cosmos import CosmosClient\n\nimport os\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\n```\n\n### AAD Authentication\n\nYou can also authenticate a client utilizing your service principal's AAD credentials and the azure identity package. \nYou can directly pass in the credentials information to ClientSecretCredential, or use the DefaultAzureCredential:\n```python\nfrom azure.cosmos import CosmosClient\nfrom azure.identity import ClientSecretCredential, DefaultAzureCredential\n\nimport os\nurl = os.environ['ACCOUNT_URI']\ntenant_id = os.environ['TENANT_ID']\nclient_id = os.environ['CLIENT_ID']\nclient_secret = os.environ['CLIENT_SECRET']\n\n# Using ClientSecretCredential\naad_credentials = ClientSecretCredential(\n    tenant_id=tenant_id,\n    client_id=client_id,\n    client_secret=client_secret)\n\n# Using DefaultAzureCredential (recommended)\naad_credentials = DefaultAzureCredential()\n\nclient = CosmosClient(url, aad_credentials)\n```\nAlways ensure that the managed identity you use for AAD authentication has `readMetadata` permissions. <br>\nMore information on how to set up AAD authentication: [Set up RBAC for AAD authentication](https://docs.microsoft.com/azure/cosmos-db/how-to-setup-rbac) <br>\nMore information on allowed operations for AAD authenticated clients: [RBAC Permission Model](https://aka.ms/cosmos-native-rbac)\n\n## Key concepts\n\nOnce you've initialized a [CosmosClient][ref_cosmosclient], you can interact with the primary resource types in Cosmos DB:\n\n* [Database][ref_database]: A Cosmos DB account can contain multiple databases. When you create a database, you specify the API you'd like to use when interacting with its documents: SQL, MongoDB, Gremlin, Cassandra, or Azure Table. Use the [DatabaseProxy][ref_database] object to manage its containers.\n\n* [Container][ref_container]: A container is a collection of JSON documents. You create (insert), read, update, and delete items in a container by using methods on the [ContainerProxy][ref_container] object.\n\n* Item: An Item is the dictionary-like representation of a JSON document stored in a container. Each Item you add to a container must include an `id` key with a value that uniquely identifies the item within the container.\n\nFor more information about these resources, see [Working with Azure Cosmos databases, containers and items][cosmos_resources].\n\n\n## How to use `enable_cross_partition_query`\n\nThe keyword-argument `enable_cross_partition_query` accepts 2 options: `None` (default) or `True`.\n\n## Note on using queries by id\n\nWhen using queries that try to find items based on an **id** value, always make sure you are passing in a string type variable. Azure Cosmos DB only allows string id values and if you use any other datatype, this SDK will return no results and no error messages.\n\n## Note on client consistency levels\n\nAs of release version 4.3.0b3, if a user does not pass in an explicit consistency level to their client initialization,\ntheir client will use their database account's default level. Previously, the default was being set to `Session` consistency.\nIf for some reason you'd like to keep doing this, you can change your client initialization to include the explicit parameter for this like shown:\n```python\nfrom azure.cosmos import CosmosClient\n\nimport os\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY, consistency_level='Session')\n```\n\n## Limitations\n\nCurrently, the features below are **not supported**. For alternatives options, check the **Workarounds** section below.\n\n### Data Plane Limitations:\n\n* Group By queries\n* Queries with COUNT from a DISTINCT subquery: SELECT COUNT (1) FROM (SELECT DISTINCT C.ID FROM C)\n* Direct TCP Mode access\n* Continuation token support for aggregate cross-partition queries like sorting, counting, and distinct.\nStreamable queries like `SELECT * FROM WHERE` *do* support continuation tokens.\n* Change Feed: Processor\n* Change Feed: Read multiple partitions key values\n* Change Feed: Read specific time\n* Cross-partition ORDER BY for mixed types\n* Enabling diagnostics for async query-type methods\n\n### Control Plane Limitations:\n\n* Get CollectionSizeUsage, DatabaseUsage, and DocumentUsage metrics\n* Create Geospatial Index\n* Get the connection string\n* Get the minimum RU/s of a container\n\n## Workarounds\n\n### Control Plane Limitations Workaround\n\nTypically, you can use [Azure Portal](https://portal.azure.com/), [Azure Cosmos DB Resource Provider REST API](https://docs.microsoft.com/rest/api/cosmos-db-resource-provider), [Azure CLI](https://docs.microsoft.com/cli/azure/azure-cli-reference-for-cosmos-db) or [PowerShell](https://docs.microsoft.com/azure/cosmos-db/manage-with-powershell) for the control plane unsupported limitations.\n\n### Using The Async Client as a Workaround to Bulk\nWhile the SDK supports transactional batch, support for bulk requests is not yet implemented in the Python SDK. You can use the async client along with this [concurrency sample][concurrency_sample] we have developed as a reference for a possible workaround. \n>[WARNING]\n> Using the asynchronous client for concurrent operations like shown in this sample will consume a lot of RUs very fast. We **strongly recommend** testing this out against the cosmos emulator first to verify your code works well and avoid incurring charges.\n\n\n\n## Boolean Data Type\n\nWhile the Python language [uses](https://docs.python.org/3/library/stdtypes.html?highlight=boolean#truth-value-testing) \"True\" and \"False\" for boolean types, Cosmos DB [accepts](https://docs.microsoft.com/azure/cosmos-db/sql-query-is-bool) \"true\" and \"false\" only. In other words, the Python language uses Boolean values with the first uppercase letter and all other lowercase letters, while Cosmos DB and its SQL language use only lowercase letters for those same Boolean values. How to deal with this challenge?\n\n* Your JSON documents created with Python must use \"True\" and \"False\", to pass the language validation. The SDK will convert it to \"true\" and \"false\" for you. Meaning that \"true\" and \"false\" is what will be stored in Cosmos DB.\n* If you retrieve those documents with the Cosmos DB Portal's Data Explorer, you will see \"true\" and \"false\".\n* If you retrieve those documents with this Python SDK, \"true\" and \"false\" values will be automatically converted to \"True\" and \"False\".\n\n## SQL Queries x FROM Clause Subitems\n\nThis SDK uses the [query_items](https://docs.microsoft.com/python/api/azure-cosmos/azure.cosmos.containerproxy?preserve-view=true&view=azure-python#query-items-query--parameters-none--partition-key-none--enable-cross-partition-query-none--max-item-count-none--enable-scan-in-query-none--populate-query-metrics-none----kwargs-) method to submit SQL queries to Azure Cosmos DB.\n\nCosmos DB SQL language allows you to [get subitems by using the FROM clause](https://docs.microsoft.com/azure/cosmos-db/sql-query-from#get-subitems-by-using-the-from-clause), to reduce the source to a smaller subset. As an example, you can use `select * from Families.children` instead of `select * from Families`. But please note that:\n\n* For SQL queries using the `query_items` method, this SDK demands that you specify the `partition_key` or use the `enable_cross_partition_query` flag.\n* If you are getting subitems and specifying the `partition_key`, please make sure that your partition key is included in the subitems, which is not true for most of the cases.\n\n## Max Item Count\n\nThis is a parameter of the query_items method, an integer indicating the maximum number of items to be returned per page. The `None` value can be specified to let the service determine the optimal item count. This is the recommended configuration value, and the default behavior of this SDK when it is not set.\n\n## Examples\n\nThe following sections provide several code snippets covering some of the most common Cosmos DB tasks, including:\n\n* [Create a database](#create-a-database \"Create a database\")\n* [Create a container](#create-a-container \"Create a container\")\n* [Create an analytical store enabled container](#create-an-analytical-store-enabled-container \"Create a container\")\n* [Get an existing container](#get-an-existing-container \"Get an existing container\")\n* [Insert data](#insert-data \"Insert data\")\n* [Delete data](#delete-data \"Delete data\")\n* [Query the database](#query-the-database \"Query the database\")\n* [Get database properties](#get-database-properties \"Get database properties\")\n* [Get database and container throughputs](#get-database-and-container-throughputs \"Get database and container throughputs\")\n* [Modify container properties](#modify-container-properties \"Modify container properties\")\n* [Using the asynchronous client](#using-the-asynchronous-client \"Using the asynchronous client\")\n\n### Create a database\n\nAfter authenticating your [CosmosClient][ref_cosmosclient], you can work with any resource in the account. The code snippet below creates a SQL API database, which is the default when no API is specified when [create_database][ref_cosmosclient_create_database] is invoked.\n\n```python\nfrom azure.cosmos import CosmosClient, exceptions\nimport os\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\nDATABASE_NAME = 'testDatabase'\ntry:\n    database = client.create_database(DATABASE_NAME)\nexcept exceptions.CosmosResourceExistsError:\n    database = client.get_database_client(DATABASE_NAME)\n```\n\n### Create a container\n\nThis example creates a container with default settings. If a container with the same name already exists in the database (generating a `409 Conflict` error), the existing container is obtained instead.\n\n```python\nfrom azure.cosmos import CosmosClient, PartitionKey, exceptions\nimport os\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\nDATABASE_NAME = 'testDatabase'\ndatabase = client.get_database_client(DATABASE_NAME)\nCONTAINER_NAME = 'products'\n\ntry:\n    container = database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path=\"/productName\"))\nexcept exceptions.CosmosResourceExistsError:\n    container = database.get_container_client(CONTAINER_NAME)\nexcept exceptions.CosmosHttpResponseError:\n    raise\n```\n\n### Create an analytical store enabled container\n\nThis example creates a container with [Analytical Store](https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction) enabled, for reporting, BI, AI, and Advanced Analytics with [Azure Synapse Link](https://docs.microsoft.com/azure/cosmos-db/synapse-link).\n\nThe options for analytical_storage_ttl are:\n\n+ 0 or Null or not informed: Not enabled.\n+ -1: The data will be stored infinitely.\n+ Any other number: the actual ttl, in seconds.\n\n\n```python\nCONTAINER_NAME = 'products'\ntry:\n    container = database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path=\"/productName\"),analytical_storage_ttl=-1)\nexcept exceptions.CosmosResourceExistsError:\n    container = database.get_container_client(CONTAINER_NAME)\nexcept exceptions.CosmosHttpResponseError:\n    raise\n```\n\nThe preceding snippets also handle the [CosmosHttpResponseError][ref_httpfailure] exception if the container creation failed. For more information on error handling and troubleshooting, see the [Troubleshooting](#troubleshooting \"Troubleshooting\") section.\n\n### Get an existing container\n\nRetrieve an existing container from the database:\n\n```python\nfrom azure.cosmos import CosmosClient\nimport os\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\nDATABASE_NAME = 'testDatabase'\ndatabase = client.get_database_client(DATABASE_NAME)\nCONTAINER_NAME = 'products'\ncontainer = database.get_container_client(CONTAINER_NAME)\n```\n\n### Insert data\n\nTo insert items into a container, pass a dictionary containing your data to [ContainerProxy.upsert_item][ref_container_upsert_item]. Each item you add to a container must include an `id` key with a value that uniquely identifies the item within the container.\n\nThis example inserts several items into the container, each with a unique `id`:\n\n```python\nfrom azure.cosmos import CosmosClient\nimport os\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\nDATABASE_NAME = 'testDatabase'\ndatabase = client.get_database_client(DATABASE_NAME)\nCONTAINER_NAME = 'products'\ncontainer = database.get_container_client(CONTAINER_NAME)\n\nfor i in range(1, 10):\n    container.upsert_item({\n            'id': 'item{0}'.format(i),\n            'productName': 'Widget',\n            'productModel': 'Model {0}'.format(i)\n        }\n    )\n```\n\n### Delete data\n\nTo delete items from a container, use [ContainerProxy.delete_item][ref_container_delete_item]. The SQL API in Cosmos DB does not support the SQL `DELETE` statement.\n\n```python\nfrom azure.cosmos import CosmosClient\nimport os\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\nDATABASE_NAME = 'testDatabase'\ndatabase = client.get_database_client(DATABASE_NAME)\nCONTAINER_NAME = 'products'\ncontainer = database.get_container_client(CONTAINER_NAME)\n\nfor item in container.query_items(\n        query='SELECT * FROM products p WHERE p.productModel = \"Model 2\"',\n        enable_cross_partition_query=True):\n    container.delete_item(item, partition_key='Widget')\n```\n\n> NOTE: If you are using partitioned collection, the value of the `partitionKey` in the example code above, should be set to the value of the partition key for this particular item, not the name of the partition key column in your collection. This holds true for both point reads and deletes.\n\n### Query the database\n\nA Cosmos DB SQL API database supports querying the items in a container with [ContainerProxy.query_items][ref_container_query_items] using SQL-like syntax.\n\nThis example queries a container for items with a specific `id`:\n\n```python\nfrom azure.cosmos import CosmosClient\nimport os\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\nDATABASE_NAME = 'testDatabase'\ndatabase = client.get_database_client(DATABASE_NAME)\nCONTAINER_NAME = 'products'\ncontainer = database.get_container_client(CONTAINER_NAME)\n\n# Enumerate the returned items\nimport json\nfor item in container.query_items(\n        query='SELECT * FROM mycontainer r WHERE r.id=\"item3\"',\n        enable_cross_partition_query=True):\n    print(json.dumps(item, indent=True))\n```\n\n> NOTE: Although you can specify any value for the container name in the `FROM` clause, we recommend you use the container name for consistency.\n\nPerform parameterized queries by passing a dictionary containing the parameters and their values to [ContainerProxy.query_items][ref_container_query_items]:\n\n```python\ndiscontinued_items = container.query_items(\n    query='SELECT * FROM products p WHERE p.productModel = @model',\n    parameters=[\n        dict(name='@model', value='Model 7')\n    ],\n    enable_cross_partition_query=True\n)\nfor item in discontinued_items:\n    print(json.dumps(item, indent=True))\n```\n\nFor more information on querying Cosmos DB databases using the SQL API, see [Query Azure Cosmos DB data with SQL queries][cosmos_sql_queries].\n\n### Get database properties\n\nGet and display the properties of a database:\n\n```python\nfrom azure.cosmos import CosmosClient\nimport os\nimport json\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\nDATABASE_NAME = 'testDatabase'\ndatabase = client.get_database_client(DATABASE_NAME)\nproperties = database.read()\nprint(json.dumps(properties))\n```\n\n### Get database and container throughputs\n\nGet and display the throughput values of a database and of a container with dedicated throughput:\n\n```python\nfrom azure.cosmos import CosmosClient\nimport os\nimport json\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\n\n# Database\nDATABASE_NAME = 'testDatabase'\ndatabase = client.get_database_client(DATABASE_NAME)\ndb_offer = database.read_offer()\nprint('Found Offer \\'{0}\\' for Database \\'{1}\\' and its throughput is \\'{2}\\''.format(db_offer.properties['id'], database.id, db_offer.properties['content']['offerThroughput']))\n\n# Container with dedicated throughput only. Will return error \"offer not found\" for containers without dedicated throughput\nCONTAINER_NAME = 'testContainer'\ncontainer = database.get_container_client(CONTAINER_NAME)\ncontainer_offer = container.read_offer()\nprint('Found Offer \\'{0}\\' for Container \\'{1}\\' and its throughput is \\'{2}\\''.format(container_offer.properties['id'], container.id, container_offer.properties['content']['offerThroughput']))\n```\n\n\n### Modify container properties\n\nCertain properties of an existing container can be modified. This example sets the default time to live (TTL) for items in the container to 10 seconds:\n\n```python\nfrom azure.cosmos import CosmosClient, PartitionKey\nimport os\nimport json\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\nDATABASE_NAME = 'testDatabase'\ndatabase = client.get_database_client(DATABASE_NAME)\nCONTAINER_NAME = 'products'\ncontainer = database.get_container_client(CONTAINER_NAME)\n\ndatabase.replace_container(\n    container,\n    partition_key=PartitionKey(path=\"/productName\"),\n    default_ttl=10,\n)\n# Display the new TTL setting for the container\ncontainer_props = container.read()\nprint(json.dumps(container_props['defaultTtl']))\n```\n\nFor more information on TTL, see [Time to Live for Azure Cosmos DB data][cosmos_ttl].\n\n### Using the asynchronous client\n\nThe asynchronous cosmos client is a separate client that looks and works in a similar fashion to the existing synchronous client. However, the async client needs to be imported separately and its methods need to be used with the async/await keywords.\nThe Async client needs to be initialized and closed after usage, which can be done manually or with the use of a context manager. The example below shows how to do so manually. We don't recommend doing it this way, since it requires that you manually call __aenter__() before using the client.\n\n```python\nfrom azure.cosmos.aio import CosmosClient\nimport os\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nDATABASE_NAME = 'testDatabase'\nCONTAINER_NAME = 'products'    \n\nasync def create_products():\n    client = CosmosClient(URL, credential=KEY)\n    await client.__aenter__() # this piece is important for the SDK to cache account information\n    database = client.get_database_client(DATABASE_NAME)\n    container = database.get_container_client(CONTAINER_NAME)\n    for i in range(10):\n        await container.upsert_item({\n                'id': 'item{0}'.format(i),\n                'productName': 'Widget',\n                'productModel': 'Model {0}'.format(i)\n            }\n        )\n    await client.close() # the async client must be closed manually if it's not initialized in a with statement\n```\n\nInstead of manually opening and closing the client, it is highly recommended to use the `async with` keywords. This creates a context manager that will initialize and later close the client once you're out of the statement, as well as cache important information the SDK needs. The example below shows how to do so.\n\n```python\nfrom azure.cosmos.aio import CosmosClient\nimport os\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nDATABASE_NAME = 'testDatabase'\nCONTAINER_NAME = 'products'\n\nasync def create_products():\n    async with CosmosClient(URL, credential=KEY) as client: # the with statement will automatically initialize and close the async client\n        database = client.get_database_client(DATABASE_NAME)\n        container = database.get_container_client(CONTAINER_NAME)\n        for i in range(10):\n            await container.upsert_item({\n                    'id': 'item{0}'.format(i),\n                    'productName': 'Widget',\n                    'productModel': 'Model {0}'.format(i)\n                }\n            )\n```\n\n### Queries with the asynchronous client\n\nUnlike the synchronous client, the async client does not have an `enable_cross_partition` flag in the request. Queries without a specified partition key value will attempt to do a cross partition query by default. \n\nQuery results can be iterated, but the query's raw output returns an asynchronous iterator. This means that each object from the iterator is an awaitable object, and does not yet contain the true query result. In order to obtain the query results you can use an async for loop, which awaits each result as you iterate on the object, or manually await each query result as you iterate over the asynchronous iterator.\n\nSince the query results are an asynchronous iterator, they can't be cast into lists directly; instead, if you need to create lists from your results, use an async for loop or Python's list comprehension to populate a list:\n\n```python\nfrom azure.cosmos.aio import CosmosClient\nimport os\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(URL, credential=KEY)\nDATABASE_NAME = 'testDatabase'\ndatabase = client.get_database_client(DATABASE_NAME)\nCONTAINER_NAME = 'products'\ncontainer = database.get_container_client(CONTAINER_NAME)\n\nasync def create_lists():\n    results = container.query_items(\n            query='SELECT * FROM products p WHERE p.productModel = \"Model 2\"')\n\n    # iterates on \"results\" iterator to asynchronously create a complete list of the actual query results\n\n    item_list = []\n    async for item in results:\n        item_list.append(item)\n\n    # Asynchronously creates a complete list of the actual query results. This code performs the same action as the for-loop example above.\n    item_list = [item async for item in results]\n    await client.close()\n```\n\n### Using Integrated Cache\nAn integrated cache is an in-memory cache that helps you ensure manageable costs and low latency as your request volume grows. The integrated cache has two parts: an item cache for point reads and a query cache for queries. The code snippet below shows you how to use this feature with the point read and query cache methods.\n\nThe benefit of using this is that the point reads and queries that hit the integrated cache won't use any RUs. This means you will have a much lower per-operation cost than reads from the backend.\n\n[How to configure the Azure Cosmos DB integrated cache (Preview)][cosmos_configure_integrated_cache]\n\n```python\nimport azure.cosmos.cosmos_client as cosmos_client\nimport os\n\nURL = os.environ['ACCOUNT_URI']\nKEY = os.environ['ACCOUNT_KEY']\nclient = cosmos_client.CosmosClient(URL, credential=KEY)\nDATABASE_NAME = 'testDatabase'\ndatabase = client.get_database_client(DATABASE_NAME)\nCONTAINER_NAME = 'testContainer'\ncontainer = database.get_container_client(CONTAINER_NAME)\n\ndef integrated_cache_snippet():\n    item_id = body['id'] \n    query = 'SELECT * FROM c'\n\n    #item cache\n    container.read_item(item=item_id, partition_key=item_id, max_integrated_cache_staleness_in_ms=30000)\n\n    #query cache   \n    container.query_items(query=query,\n         partition_key=item_id, max_integrated_cache_staleness_in_ms=30000)\n```\nFor more information on Integrated Cache, see [Azure Cosmos DB integrated cache - Overview][cosmos_integrated_cache].\n\n### Using Transactional Batch\nTransactional batch requests allow you to send several operations to be executed at once within the same partition key.\nIf all operations succeed in the order they're described within the transactional batch operation, the transaction will be committed.\nHowever, if any operation fails, the entire transaction is rolled back.\n\nTransactional batches have a limit of 100 operations per batch, and a total size limit of 1.2Mb for the\nbatch operations being passed in.\n\nTransactional Batch operations look very similar to the singular operations apis, and are tuples containing\n(`operation_type_string`, `args_tuple`, `batch_operation_kwargs_dictionary`), with the kwargs dictionary being optional:\n```python\nbatch_operations = [\n        (\"create\", (item_body,), kwargs),\n        (\"replace\", (item_id, item_body), kwargs),\n        (\"read\", (item_id,), kwargs),\n        (\"upsert\", (item_body,), kwargs),\n        (\"patch\", (item_id, operations), kwargs),\n        (\"delete\", (item_id,), kwargs),\n    ]\nbatch_results = container.execute_item_batch(batch_operations=batch_operations, partition_key=partition_key)\n```\nThe batch operation kwargs dictionary is limited, and only takes a total of three different key values.\nIn the case of wanting to use conditional patching within the batch, the use of `filter_predicate` key is available for the\npatch operation, or in case of wanting to use etags with any of the operations, the use of the `if_match_etag`/`if_none_match_etag`\nkeys is available as well.\n```python\nbatch_operations = [\n        (\"replace\", (item_id, item_body), {\"if_match_etag\": etag}),\n        (\"patch\", (item_id, operations), {\"filter_predicate\": filter_predicate, \"if_none_match_etag\": etag}),\n    ]\n```\n\nWe also have some samples showing these transactional batch operations in action with both the [sync][sample_document_mgmt]\nand [async][sample_document_mgmt_async] clients.\n\nIf there is a failure for an operation within the batch, the SDK will raise a `CosmosBatchOperationError` letting you know which operation failed,\nas well as containing the list of failed responses for the failed request.\n\nFor more information on Transactional Batch, see [Azure Cosmos DB Transactional Batch][cosmos_transactional_batch].\n\n## Troubleshooting\n\n### General\n\nWhen you interact with Cosmos DB using the Python SDK, exceptions returned by the service correspond to the same HTTP status codes returned for REST API requests:\n\n[HTTP Status Codes for Azure Cosmos DB][cosmos_http_status_codes]\n\nFor example, if you try to create a container using an ID (name) that's already in use in your Cosmos DB database, a `409` error is returned, indicating the conflict. In the following snippet, the error is handled gracefully by catching the exception and displaying additional information about the error.\n\n```python\ntry:\n    database.create_container(id=CONTAINER_NAME, partition_key=PartitionKey(path=\"/productName\"))\nexcept exceptions.CosmosResourceExistsError:\n    print(\"\"\"Error creating container\nHTTP status code 409: The ID (name) provided for the container is already in use.\nThe container name must be unique within the database.\"\"\")\n\n```\n### Logging Diagnostics\n\nThis library uses the standard\n[logging](https://docs.python.org/3.5/library/logging.html) library for logging diagnostics.\nBasic information about HTTP sessions (URLs, headers, etc.) is logged at INFO\nlevel.\n\nDetailed DEBUG level logging, including request/response bodies and unredacted\nheaders, can be enabled on a client with the `logging_enable` argument:\n```python\nimport sys\nimport logging\nfrom azure.cosmos import CosmosClient\n\n# Create a logger for the 'azure' SDK\nlogger = logging.getLogger('azure')\nlogger.setLevel(logging.DEBUG)\n\n# Configure a console output\nhandler = logging.StreamHandler(stream=sys.stdout)\nlogger.addHandler(handler)\n\n# This client will log detailed information about its HTTP sessions, at DEBUG level\nclient = CosmosClient(URL, credential=KEY, logging_enable=True)\n```\n\nSimilarly, `logging_enable` can enable detailed logging for a single operation,\neven when it isn't enabled for the client:\n```python\ndatabase = client.create_database(DATABASE_NAME, logging_enable=True)\n```\nAlternatively, you can log using the CosmosHttpLoggingPolicy, which extends from the azure core HttpLoggingPolicy, by passing in your logger to the `logger` argument.\nBy default, it will use the behaviour from HttpLoggingPolicy. Passing in the `enable_diagnostics_logging` argument will enable the\nCosmosHttpLoggingPolicy, and will have additional information in the response relevant to debugging Cosmos issues.\n```python\nimport logging\nfrom azure.cosmos import CosmosClient\n\n#Create a logger for the 'azure' SDK\nlogger = logging.getLogger('azure')\nlogger.setLevel(logging.DEBUG)\n\n# Configure a file output\nhandler = logging.FileHandler(filename=\"azure\")\nlogger.addHandler(handler)\n\n# This client will log diagnostic information from the HTTP session by using the CosmosHttpLoggingPolicy.\n# Since we passed in the logger to the client, it will log information on every request.\nclient = CosmosClient(URL, credential=KEY, logger=logger, enable_diagnostics_logging=True)\n```\nSimilarly, logging can be enabled for a single operation by passing in a logger to the singular request.\nHowever, if you desire to use the CosmosHttpLoggingPolicy to obtain additional information, the `enable_diagnostics_logging` argument needs to be passed in at the client constructor.\n```python\n# This example enables the CosmosHttpLoggingPolicy and uses it with the `logger` passed in to the `create_database` request.\nclient = CosmosClient(URL, credential=KEY, enable_diagnostics_logging=True)\ndatabase = client.create_database(DATABASE_NAME, logger=logger)\n```\n\n### Telemetry\nAzure Core provides the ability for our Python SDKs to use OpenTelemetry with them. The only packages that need to be installed\nto use this functionality are the following:\n```bash\npip install azure-core-tracing-opentelemetry\npip install opentelemetry-sdk\n```\nFor more information on this, we recommend taking a look at this [document](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core-tracing-opentelemetry/README.md) \nfrom Azure Core describing how to set it up. We have also added a [sample file][telemetry_sample] to show how it can\nbe used with our SDK. This works the same way regardless of the Cosmos client you are using.\n\n## Next steps\n\nFor more extensive documentation on the Cosmos DB service, see the [Azure Cosmos DB documentation][cosmos_docs] on docs.microsoft.com.\n\n<!-- LINKS -->\n[azure_cli]: https://docs.microsoft.com/cli/azure\n[azure_portal]: https://portal.azure.com\n[azure_sub]: https://azure.microsoft.com/free/\n[cloud_shell]: https://docs.microsoft.com/azure/cloud-shell/overview\n[cosmos_account_create]: https://docs.microsoft.com/azure/cosmos-db/how-to-manage-database-account\n[cosmos_account]: https://docs.microsoft.com/azure/cosmos-db/account-overview\n[cosmos_container]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-containers\n[cosmos_database]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-databases\n[cosmos_docs]: https://docs.microsoft.com/azure/cosmos-db/\n[cosmos_samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples\n[cosmos_pypi]: https://pypi.org/project/azure-cosmos/\n[cosmos_http_status_codes]: https://docs.microsoft.com/rest/api/cosmos-db/http-status-codes-for-cosmosdb\n[cosmos_item]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items#azure-cosmos-items\n[cosmos_models]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/azure/cosmos/_models.py\n[cosmos_request_units]: https://docs.microsoft.com/azure/cosmos-db/request-units\n[cosmos_resources]: https://docs.microsoft.com/azure/cosmos-db/databases-containers-items\n[cosmos_sql_queries]: https://docs.microsoft.com/azure/cosmos-db/how-to-sql-query\n[cosmos_ttl]: https://docs.microsoft.com/azure/cosmos-db/time-to-live\n[cosmos_integrated_cache]: https://docs.microsoft.com/azure/cosmos-db/integrated-cache\n[cosmos_configure_integrated_cache]: https://docs.microsoft.com/azure/cosmos-db/how-to-configure-integrated-cache\n[python]: https://www.python.org/downloads/\n[ref_container_delete_item]: https://aka.ms/azsdk-python-cosmos-ref-delete-item\n[ref_container_query_items]: https://aka.ms/azsdk-python-cosmos-ref-query-items\n[ref_container_upsert_item]: https://aka.ms/azsdk-python-cosmos-ref-upsert-item\n[ref_container]: https://aka.ms/azsdk-python-cosmos-ref-container\n[ref_cosmos_sdk]: https://aka.ms/azsdk-python-cosmos-ref\n[ref_cosmosclient_create_database]: https://aka.ms/azsdk-python-cosmos-ref-create-database\n[ref_cosmosclient]: https://aka.ms/azsdk-python-cosmos-ref-cosmos-client\n[ref_database]: https://aka.ms/azsdk-python-cosmos-ref-database\n[ref_httpfailure]: https://aka.ms/azsdk-python-cosmos-ref-http-failure\n[sample_database_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/database_management.py\n[sample_document_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/document_management.py\n[sample_document_mgmt_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/document_management_async.py\n[sample_examples_misc]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/examples.py\n[source_code]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos\n[venv]: https://docs.python.org/3/library/venv.html\n[virtualenv]: https://virtualenv.pypa.io\n[telemetry_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/tracing_open_telemetry.py\n[timeouts_document]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/docs/TimeoutAndRetriesConfig.md\n[cosmos_transactional_batch]: https://learn.microsoft.com/azure/cosmos-db/nosql/transactional-batch\n[cosmos_concurrency_sample]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples/concurrency_sample.py\n\n## Contributing\n\nThis project welcomes contributions and suggestions.  Most contributions require you to agree to a\nContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us\nthe rights to use your contribution. For details, visit https://cla.microsoft.com.\n\nWhen you submit a pull request, a CLA-bot will automatically determine whether you need to provide\na CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions\nprovided by the bot. You will only need to do this once across all repos using our CLA.\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\nFor more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or\ncontact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.\n\n## Release History\n\n### 4.6.0 (2024-03-14)\n\n#### Features Added\n* GA release of hierarchical partitioning, index metrics and transactional batch.\n\n#### Bugs Fixed\n* Keyword arguments were not being passed down for `create_container_if_not_exists()` methods. See [PR 34286](https://github.com/Azure/azure-sdk-for-python/pull/34286).\n\n#### Other Changes\n* Made several updates to the type hints used throughout the SDK for greater detail. See [PR 33269](https://github.com/Azure/azure-sdk-for-python/pull/33269), [PR 33341](https://github.com/Azure/azure-sdk-for-python/pull/33341), [PR 33738](https://github.com/Azure/azure-sdk-for-python/pull/33738).\n\n### 4.5.2b5 (2024-03-02)\n\n#### Bugs Fixed\n* Fixed bug with async lock not properly releasing on async global endpoint manager. see [PR 34579](https://github.com/Azure/azure-sdk-for-python/pull/34579).\n\n#### Other Changes\n* Marked `computed_properties` keyword as provisional, un-marked `continuation_token_limit` as provisional. See [PR 34207](https://github.com/Azure/azure-sdk-for-python/pull/34207).\n\n### 4.5.2b4 (2024-02-02)\nThis version and all future versions will require Python 3.8+.\n\n#### Features Added\n* Added **preview** support for Computed Properties on Python SDK (Must be enabled on the account level before it can be used). See [PR 33626](https://github.com/Azure/azure-sdk-for-python/pull/33626).\n\n#### Bugs Fixed\n* Made use of `response_hook` thread-safe in the sync client. See [PR 33790](https://github.com/Azure/azure-sdk-for-python/pull/33790).\n* Fixed bug with the session container not being properly maintained. See [33738](https://github.com/Azure/azure-sdk-for-python/pull/33738).\n\n### 4.5.2b3 (2023-11-10)\n\n#### Features Added\n* Added support for capturing Index Metrics in query operations. See [PR 33034](https://github.com/Azure/azure-sdk-for-python/pull/33034).\n\n### 4.5.2b2 (2023-10-31)\n\n#### Features Added\n* Added support for Transactional Batch. See [PR 32508](https://github.com/Azure/azure-sdk-for-python/pull/32508).\n* Added **preview** support for Priority Based Throttling/Priority Based Execution (Must be enabled at the account level before it can be used). See [PR 32441](https://github.com/Azure/azure-sdk-for-python/pull/32441/).\n\n### 4.5.2b1 (2023-10-17)\n\n#### Features Added\n* Added support for Hierarchical Partitioning, also known as Subpartitioning. See [PR 31121](https://github.com/Azure/azure-sdk-for-python/pull/31121).\n\n#### Bugs Fixed\n* Small fix to the `offer_throughput` option in the async client's `create_database_if_not_exists` method, which was previously misspelled as `offerThroughput`.\nSee [PR 32076](https://github.com/Azure/azure-sdk-for-python/pull/32076).\n\n#### Other Changes\n* Marked the outdated `diagnostics.py` file for deprecation since we now recommend the use of our `CosmosHttpLoggingPolicy` for diagnostics.\nFor more on the `CosmosHttpLoggingPolicy` see our [README](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos#logging-diagnostics).\n\n### 4.5.1 (2023-09-12)\n\n#### Bugs Fixed\n* Fixed bug when query with DISTINCT + OFFSET/LIMIT operators returns unexpected result. See [PR 31925](https://github.com/Azure/azure-sdk-for-python/pull/31925).\n\n#### Other Changes\n* Added additional checks for resource creation using specific characters that cause issues. See [PR 31861](https://github.com/Azure/azure-sdk-for-python/pull/31861).\n\n### 4.5.0 (2023-08-09)\n\n#### Features Added\n* Added support for continuation tokens for streamable cross partition queries. See [PR 31189](https://github.com/Azure/azure-sdk-for-python/pull/31189).\n\n#### Bugs Fixed\n* Fixed bug with async `create_database_if_not_exists` method not working when passing `offer_throughput` as an option. See [PR 31478](https://github.com/Azure/azure-sdk-for-python/pull/31478).\n\n#### Other Changes\n* Renamed `response_continuation_token_limit_in_kb` to `continuation_token_limit` for GA. See [PR 31532](https://github.com/Azure/azure-sdk-for-python/pull/31532).\n\n### 4.4.1b1 (2023-07-25)\n\n#### Features Added\n* Added ability to limit continuation token size when querying for items. See [PR 30731](https://github.com/Azure/azure-sdk-for-python/pull/30731)\n\n#### Bugs Fixed\n* Fixed bug with async patch_item method. See [PR 30804](https://github.com/Azure/azure-sdk-for-python/pull/30804).\n\n### 4.4.0 (2023-06-09)\n\n#### Features Added\n- GA release of Patch API and Delete All Items By Partition Key\n\n### 4.4.0b2 (2023-05-22)\n\n#### Features Added\n* Added conditional patching for Patch operations. See [PR 30455](https://github.com/Azure/azure-sdk-for-python/pull/30455).\n\n#### Bugs Fixed\n* Fixed bug with non english locales causing an error with the RFC 1123 Date Format. See [PR 30125](https://github.com/Azure/azure-sdk-for-python/pull/30125).\n\n#### Other Changes\n* Refactoring of our client `connection_timeout` and `request_timeout` configurations. See [PR 30171](https://github.com/Azure/azure-sdk-for-python/pull/30171).\n\n### 4.4.0b1 (2023-04-11)\n\n#### Features Added\n - Added **preview** delete all items by partition key functionality. See [PR 29186](https://github.com/Azure/azure-sdk-for-python/pull/29186). For more information on Partition Key Delete, please see [Azure Cosmos DB Partition Key Delete](https://learn.microsoft.com/azure/cosmos-db/nosql/how-to-delete-by-partition-key?tabs=python-example).\n - Added **preview** partial document update (Patch API) functionality and container methods for patching items with operations. See [PR 29497](https://github.com/Azure/azure-sdk-for-python/pull/29497). For more information on Patch, please see [Azure Cosmos DB Partial Document Update](https://learn.microsoft.com/azure/cosmos-db/partial-document-update).\n\n#### Bugs Fixed\n* Fixed bug in method `create_container_if_not_exists()` of async database client for unexpected kwargs being passed into `read()` method used internally. See [PR 29136](https://github.com/Azure/azure-sdk-for-python/pull/29136).\n* Fixed bug with method `query_items()` of our async container class, where partition key and cross partition headers would both be set when using partition keys. See [PR 29366](https://github.com/Azure/azure-sdk-for-python/pull/29366/).\n* Fixed bug with client not properly surfacing errors for invalid credentials and identities with insufficient permissions. Users running into 'NoneType has no attribute ConsistencyPolicy' errors when initializing their clients will now see proper authentication exceptions. See [PR 29256](https://github.com/Azure/azure-sdk-for-python/pull/29256).\n\n#### Other Changes\n* Removed use of `six` package within the SDK.\n\n### 4.3.1 (2023-02-23)\n\n#### Features Added\n - Added `correlated_activity_id` for query operations.\n - Added cross regional retries for Service Unavailable/Request Timeouts for read/Query Plan operations.\n - GA release of CosmosHttpLoggingPolicy and autoscale feature.\n\n#### Bugs Fixed\n- Bug fix to address queries with VALUE MAX (or any other aggregate) that run into an issue if the query is executed on a container with at least one \"empty\" partition.\n\n### 4.3.1b1 (2022-09-19)\n\n#### Features Added\n- GA release of integrated cache functionality. For more information on integrated cache please see [Azure Cosmos DB integrated cache](https://docs.microsoft.com/azure/cosmos-db/integrated-cache).\n- Added ability to replace analytical ttl on containers. For more information on analytical ttl please see [Azure Cosmos DB analytical store](https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction).\n- Added `CosmosHttpLoggingPolicy` to replace `HttpLoggingPolicy` for logging HTTP sessions.\n- Added the ability to create containers and databases with autoscale properties for the sync and async clients.\n- Added the ability to update autoscale throughput properties.\n\n#### Bugs Fixed\n- Fixed parsing of args for overloaded `container.read()` method.\n- Fixed `validate_cache_staleness_value()` method to allow max_integrated_cache_staleness to be an integer greater than or equal to 0.\n- Fixed `__aiter__()` method by removing the async keyword.\n\n### 4.3.0 (2022-05-23)\n#### Features Added\n- GA release of Async I/O APIs, including all changes from 4.3.0b1 to 4.3.0b4.\n\n#### Breaking Changes\n- Method signatures have been updated to use keyword arguments instead of positional arguments for most method options in the async client.\n- Bugfix: Automatic Id generation for items was turned on for `upsert_items()` method when no 'id' value was present in document body.\nMethod call will now require an 'id' field to be present in the document body.\n\n#### Other Changes\n- Deprecated offer-named methods in favor of their new throughput-named counterparts (`read_offer` -> `get_throughput`).\n- Marked the GetAuthorizationHeader method for deprecation since it will no longer be public in a future release.\n- Added samples showing how to configure retry options for both the sync and async clients.\n- Deprecated the `connection_retry_policy` and `retry_options` options in the sync client.\n- Added user warning to non-query methods trying to use `populate_query_metrics` options.\n\n### 4.3.0b4 (2022-04-07)\n\n#### Features Added\n- Added support for AAD authentication for the async client.\n- Added support for AAD authentication for the sync client.\n\n#### Other Changes\n- Changed `_set_partition_key` return typehint in async client.\n\n### 4.3.0b3 (2022-03-10)\n\n>[WARNING]\n>The default `Session` consistency bugfix will impact customers whose database accounts have a `Bounded Staleness` or `Strong`\n> consistency level, and were previously not sending `Session` as a consistency_level parameter when initializing\n> their clients.\n> Default consistency level for the sync and async clients is no longer \"Session\" and will instead be set to the \n  consistency level of the user's cosmos account setting on initialization if not passed during client initialization. \n> Please see [Consistency Levels in Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/consistency-levels) \n> for more details on consistency levels, or the README section on this change [here](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos#note-on-client-consistency-levels).\n\n#### Features Added\n- Added new **provisional** `max_integrated_cache_staleness_in_ms` parameter to read item and query items APIs in order\n  to make use of the **preview** CosmosDB integrated cache functionality [See PR #22946](https://github.com/Azure/azure-sdk-for-python/pull/22946).\n  Please see [Azure Cosmos DB integrated cache](https://docs.microsoft.com/azure/cosmos-db/integrated-cache) for more details.\n- Added support for split-proof queries for the async client.\n\n### Bugs fixed\n- Default consistency level for the sync and async clients is no longer `Session` and will instead be set to the \n  consistency level of the user's cosmos account setting on initialization if not passed during client initialization. \n  This change will impact client application in terms of RUs and latency. Users relying on default `Session` consistency\n  will need to pass it explicitly if their account consistency is different than `Session`.\n  Please see [Consistency Levels in Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/consistency-levels) for more details.  \n- Fixed invalid request body being sent when passing in `serverScript` body parameter to replace operations for trigger, sproc and udf resources.\n- Moved `is_system_key` logic in async client.\n- Fixed TypeErrors not being thrown when passing in invalid connection retry policies to the client.\n\n### 4.3.0b2 (2022-01-25)\n\nThis version and all future versions will require Python 3.6+. Python 2.7 is no longer supported.\nWe will also be removing support for Python 3.6 and will only support Python 3.7+ starting December 2022.\n\n#### Features Added\n- Added support for split-proof queries for the sync client.\n\n#### Other Changes\n- Added async user agent for async client.\n\n### 4.3.0b1 (2021-12-14)\n\n#### Features Added\n- Added language native async i/o client.\n\n### 4.2.0 (2020-10-08)\n\n**Bug fixes**\n- Fixed bug where continuation token is not honored when query_iterable is used to get results by page. Issue #13265.\n- Fixed bug where resource tokens not being honored for document reads and deletes. Issue #13634.\n\n**New features**\n- Added support for passing partitionKey while querying changefeed. Issue #11689.\n\n### 4.1.0 (2020-08-10)\n\n- Added deprecation warning for \"lazy\" indexing mode. The backend no longer allows creating containers with this mode and will set them to consistent instead.\n\n**New features**\n- Added the ability to set the analytical storage TTL when creating a new container.\n\n**Bug fixes**\n- Fixed support for dicts as inputs for get_client APIs.\n- Fixed Python 2/3 compatibility in query iterators.\n- Fixed type hint error. Issue #12570 - thanks @sl-sandy.\n- Fixed bug where options headers were not added to upsert_item function. Issue #11791 - thank you @aalapatirvbd.\n- Fixed error raised when a non string ID is used in an item. It now raises TypeError rather than AttributeError. Issue #11793 - thank you @Rabbit994.\n\n\n### 4.0.0 (2020-05-20)\n\n- Stable release.\n- Added HttpLoggingPolicy to pipeline to enable passing in a custom logger for request and response headers.\n\n\n## 4.0.0b6\n\n- Fixed bug in synchronized_request for media APIs.\n- Removed MediaReadMode and MediaRequestTimeout from ConnectionPolicy as media requests are not supported.\n\n\n## 4.0.0b5\n\n- azure.cosmos.errors module deprecated and replaced by azure.cosmos.exceptions\n- The access condition parameters (`access_condition`, `if_match`, `if_none_match`) have been deprecated in favor of separate `match_condition` and `etag` parameters.\n- Fixed bug in routing map provider.\n- Added query Distinct, Offset and Limit support.\n- Default document query execution context now used for\n    - ChangeFeed queries\n    - single partition queries (partitionkey, partitionKeyRangeId is present in options)\n    - Non document queries\n- Errors out for aggregates on multiple partitions, with enable cross partition query set to true, but no \"value\" keyword present\n- Hits query plan endpoint for other scenarios to fetch query plan\n- Added `__repr__` support for Cosmos entity objects.\n- Updated documentation.\n\n\n## 4.0.0b4\n\n- Added support for a `timeout` keyword argument to all operations to specify an absolute timeout in seconds\n  within which the operation must be completed. If the timeout value is exceeded, a `azure.cosmos.errors.CosmosClientTimeoutError` will be raised.\n- Added a new `ConnectionRetryPolicy` to manage retry behaviour during HTTP connection errors.\n- Added new constructor and per-operation configuration keyword arguments:\n    - `retry_total` - Maximum retry attempts.\n    - `retry_backoff_max` - Maximum retry wait time in seconds.\n    - `retry_fixed_interval` - Fixed retry interval in milliseconds.\n    - `retry_read` - Maximum number of socket read retry attempts.\n    - `retry_connect` - Maximum number of connection error retry attempts.\n    - `retry_status` - Maximum number of retry attempts on error status codes.\n    - `retry_on_status_codes` - A list of specific status codes to retry on.\n    - `retry_backoff_factor` - Factor to calculate wait time between retry attempts.\n\n## 4.0.0b3\n\n- Added `create_database_if_not_exists()` and `create_container_if_not_exists` functionalities to CosmosClient and Database respectively.\n\n## 4.0.0b2\n\nVersion 4.0.0b2 is the second iteration in our efforts to build a more Pythonic client library.\n\n**Breaking changes**\n\n- The client connection has been adapted to consume the HTTP pipeline defined in `azure.core.pipeline`.\n- Interactive objects have now been renamed as proxies. This includes:\n    - `Database` -> `DatabaseProxy`\n    - `User` -> `UserProxy`\n    - `Container` -> `ContainerProxy`\n    - `Scripts` -> `ScriptsProxy`\n- The constructor of `CosmosClient` has been updated:\n    - The `auth` parameter has been renamed to `credential` and will now take an authentication type directly. This means the master key value, a dictionary of resource tokens, or a list of permissions can be passed in. However the old dictionary format is still supported.\n    - The `connection_policy` parameter has been made a keyword only parameter, and while it is still supported, each of the individual attributes of the policy can now be passed in as explicit keyword arguments:\n        - `request_timeout`\n        - `media_request_timeout`\n        - `connection_mode`\n        - `media_read_mode`\n        - `proxy_config`\n        - `enable_endpoint_discovery`\n        - `preferred_locations`\n        - `multiple_write_locations`\n- A new classmethod constructor has been added to `CosmosClient` to enable creation via a connection string retrieved from the Azure portal.\n- Some `read_all` operations have been renamed to `list` operations:\n    - `CosmosClient.read_all_databases` -> `CosmosClient.list_databases`\n    - `Container.read_all_conflicts` -> `ContainerProxy.list_conflicts`\n    - `Database.read_all_containers` -> `DatabaseProxy.list_containers`\n    - `Database.read_all_users` -> `DatabaseProxy.list_users`\n    - `User.read_all_permissions` -> `UserProxy.list_permissions`\n- All operations that take `request_options` or `feed_options` parameters, these have been moved to keyword only parameters. In addition, while these options dictionaries are still supported, each of the individual options within the dictionary are now supported as explicit keyword arguments.\n- The error hierarchy is now inherited from `azure.core.AzureError` instead of `CosmosError` which has been removed.\n    - `HTTPFailure` has been renamed to `CosmosHttpResponseError`\n    - `JSONParseFailure` has been removed and replaced by `azure.core.DecodeError`\n    - Added additional errors for specific response codes:\n        - `CosmosResourceNotFoundError` for status 404\n        - `CosmosResourceExistsError` for status 409\n        - `CosmosAccessConditionFailedError` for status 412\n- `CosmosClient` can now be run in a context manager to handle closing the client connection.\n- Iterable responses (e.g. query responses and list responses) are now of type `azure.core.paging.ItemPaged`. The method `fetch_next_block` has been replaced by a secondary iterator, accessed by the `by_page` method.\n\n## 4.0.0b1\n\nVersion 4.0.0b1 is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Cosmos. For more information about this, and preview releases of other Azure SDK libraries, please visit https://aka.ms/azure-sdk-preview1-python.\n\n**Breaking changes: New API design**\n\n- Operations are now scoped to a particular client:\n    - `CosmosClient`: This client handles account-level operations. This includes managing service properties and listing the databases within an account.\n    - `Database`: This client handles database-level operations. This includes creating and deleting containers, users and stored procedures. It can be accessed from a `CosmosClient` instance by name.\n    - `Container`: This client handles operations for a particular container. This includes querying and inserting items and managing properties.\n    - `User`: This client handles operations for a particular user. This includes adding and deleting permissions and managing user properties.\n    \n    These clients can be accessed by navigating down the client hierarchy using the `get_<child>_client` method. For full details on the new API, please see the [reference documentation](https://aka.ms/azsdk-python-cosmos-ref).\n- Clients are accessed by name rather than by Id. No need to concatenate strings to create links.\n- No more need to import types and methods from individual modules. The public API surface area is available directly in the `azure.cosmos` package.\n- Individual request properties can be provided as keyword arguments rather than constructing a separate `RequestOptions` instance.\n\n## 3.0.2\n\n- Added Support for MultiPolygon Datatype\n- Bug Fix in Session Read Retry Policy\n- Bug Fix for Incorrect padding issues while decoding base 64 strings\n\n## 3.0.1\n\n- Bug fix in LocationCache\n- Bug fix endpoint retry logic\n- Fixed documentation\n\n## 3.0.0\n\n- Multi-region write support added\n- Naming changes\n  - DocumentClient to CosmosClient\n  - Collection to Container\n  - Document to Item\n  - Package name updated to \"azure-cosmos\"\n  - Namespace updated to \"azure.cosmos\"\n\n## 2.3.3\n\n- Added support for proxy\n- Added support for reading change feed\n- Added support for collection quota headers\n- Bugfix for large session tokens issue\n- Bugfix for ReadMedia API\n- Bugfix in partition key range cache\n\n## 2.3.2\n\n- Added support for default retries on connection issues.\n\n## 2.3.1\n\n- Updated documentation to reference Azure Cosmos DB instead of Azure DocumentDB.\n\n## 2.3.0\n\n- This SDK version requires the latest version of Azure Cosmos DB Emulator available for download from https://aka.ms/cosmosdb-emulator.\n\n## 2.2.1\n\n- bugfix for aggregate dict\n- bugfix for trimming slashes in the resource link\n- tests for unicode encoding\n\n## 2.2.0\n\n- Added support for Request Unit per Minute (RU/m) feature.\n- Added support for a new consistency level called ConsistentPrefix.\n\n## 2.1.0\n\n- Added support for aggregation queries (COUNT, MIN, MAX, SUM, and AVG).\n- Added an option for disabling SSL verification when running against DocumentDB Emulator.\n- Removed the restriction of dependent requests module to be exactly 2.10.0.\n- Lowered minimum throughput on partitioned collections from 10,100 RU/s to 2500 RU/s.\n- Added support for enabling script logging during stored procedure execution.\n- REST API version bumped to '2017-01-19' with this release.\n\n## 2.0.1\n\n- Made editorial changes to documentation comments.\n\n## 2.0.0\n\n- Added support for Python 3.5.\n- Added support for connection pooling using the requests module.\n- Added support for session consistency.\n- Added support for TOP/ORDERBY queries for partitioned collections.\n\n## 1.9.0\n\n- Added retry policy support for throttled requests. (Throttled requests receive a request rate too large exception, error code 429.)\n  By default, DocumentDB retries nine times for each request when error code 429 is encountered, honoring the retryAfter time in the response header.\n  A fixed retry interval time can now be set as part of the RetryOptions property on the ConnectionPolicy object if you want to ignore the retryAfter time returned by server between the retries.\n  DocumentDB now waits for a maximum of 30 seconds for each request that is being throttled (irrespective of retry count) and returns the response with error code 429.\n  This time can also be overridden in the RetryOptions property on ConnectionPolicy object.\n\n- DocumentDB now returns x-ms-throttle-retry-count and x-ms-throttle-retry-wait-time-ms as the response headers in every request to denote the throttle retry count\n  and the cumulative time the request waited between the retries.\n\n- Removed the RetryPolicy class and the corresponding property (retry_policy) exposed on the document_client class and instead introduced a RetryOptions class\n  exposing the RetryOptions property on ConnectionPolicy class that can be used to override some of the default retry options.\n\n## 1.8.0\n\n- Added the support for geo-replicated database accounts.\n- Test fixes to move the global host and masterKey into the individual test classes.\n\n## 1.7.0\n\n- Added the support for Time To Live(TTL) feature for documents.\n\n## 1.6.1\n\n- Bug fixes related to server side partitioning to allow special characters in partitionkey path.\n\n## 1.6.0\n\n- Added the support for server side partitioned collections feature.\n\n## 1.5.0\n\n- Added Client-side sharding framework to the SDK. Implemented HashPartionResolver and RangePartitionResolver classes.\n\n## 1.4.2\n\n- Implement Upsert. New UpsertXXX methods added to support Upsert feature.\n- Implement ID Based Routing. No public API changes, all changes internal.\n\n## 1.3.0\n\n- Release skipped to bring version number in alignment with other SDKs\n\n## 1.2.0\n\n- Supports GeoSpatial index.\n- Validates id property for all resources. Ids for resources cannot contain ?, /, #, \\\\, characters or end with a space.\n- Adds new header \"index transformation progress\" to ResourceResponse.\n\n## 1.1.0\n\n- Implements V2 indexing policy\n\n## 1.0.1\n\n- Supports proxy connection\n\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "Microsoft Azure Cosmos Client Library for Python",
    "version": "4.6.0",
    "project_urls": {
        "Homepage": "https://github.com/Azure/azure-sdk-for-python"
    },
    "split_keywords": [
        "azure",
        "azure sdk"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f5344b65a9568534b8f31064fe583ba0f2a624e2457ea28940dc2f2000679d28",
                "md5": "194d2bc32fe4987da6b1661bb6fcb335",
                "sha256": "b74c0cce0b9e3c6b0059888ff9ccdd1f3108fc972c0079ebd7430484fe6150d9"
            },
            "downloads": -1,
            "filename": "azure_cosmos-4.6.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "194d2bc32fe4987da6b1661bb6fcb335",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 243050,
            "upload_time": "2024-03-14T23:08:50",
            "upload_time_iso_8601": "2024-03-14T23:08:50.752287Z",
            "url": "https://files.pythonhosted.org/packages/f5/34/4b65a9568534b8f31064fe583ba0f2a624e2457ea28940dc2f2000679d28/azure_cosmos-4.6.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "322206af125a6e05a4f60f3c1bfa79c869ea0dc64be9e7fcadc4c80388cde967",
                "md5": "7d241b18b7b42a6cd9ffc4db887a1831",
                "sha256": "daec6ac201c6473b092b62aee71e381beeb6c3a8dc361249832b7048c4f061e2"
            },
            "downloads": -1,
            "filename": "azure-cosmos-4.6.0.tar.gz",
            "has_sig": false,
            "md5_digest": "7d241b18b7b42a6cd9ffc4db887a1831",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 343329,
            "upload_time": "2024-03-14T23:08:48",
            "upload_time_iso_8601": "2024-03-14T23:08:48.146672Z",
            "url": "https://files.pythonhosted.org/packages/32/22/06af125a6e05a4f60f3c1bfa79c869ea0dc64be9e7fcadc4c80388cde967/azure-cosmos-4.6.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-14 23:08:48",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Azure",
    "github_project": "azure-sdk-for-python",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "azure-cosmos"
}
        
Elapsed time: 0.21949s