Skip to content

prefect_azure.cosmos_db

Tasks for interacting with Azure Cosmos DB

cosmos_db_create_item async

Create an item in the container.

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

Parameters:

Name Type Description Default
body Dict[str, Any]

A dict-like object representing the item to create.

required
container Union[str, ContainerProxy, Dict[str, Any]]

The ID (name) of the container, a ContainerProxy instance, or a dict representing the properties of the container to be retrieved.

required
database Union[str, DatabaseProxy, Dict[str, Any]]

The ID (name), dict representing the properties or DatabaseProxy instance of the database to read.

required
cosmos_db_credentials AzureCosmosDbCredentials

Credentials to use for authentication with Azure.

required
**kwargs Any

Additional keyword arguments to pass.

{}

Returns:

Type Description
Dict[str, Any]

A dict representing the new item.

Example

Create an item in the container.

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

import uuid

from prefect import flow

from prefect_azure import AzureCosmosDbCredentials
from prefect_azure.cosmos_db import cosmos_db_create_item

@flow
def example_cosmos_db_create_item_flow():
    connection_string = "connection_string"
    cosmos_db_credentials = AzureCosmosDbCredentials(connection_string)

    body = {
        "firstname": "Olivia",
        "age": 3,
        "id": str(uuid.uuid4())
    }
    container = "Persons"
    database = "SampleDB"

    result = cosmos_db_create_item(
        body,
        container,
        database,
        cosmos_db_credentials
    )
    return result

example_cosmos_db_create_item_flow()

Source code in prefect_azure/cosmos_db.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
@task
async def cosmos_db_create_item(
    body: Dict[str, Any],
    container: Union[str, "ContainerProxy", Dict[str, Any]],
    database: Union[str, "DatabaseProxy", Dict[str, Any]],
    cosmos_db_credentials: AzureCosmosDbCredentials,
    **kwargs: Any,
) -> Dict[str, Any]:
    """
    Create an item in the container.

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

    Args:
        body: A dict-like object representing the item to create.
        container: The ID (name) of the container, a ContainerProxy instance,
            or a dict representing the properties of the container to be retrieved.
        database: The ID (name), dict representing the properties
            or DatabaseProxy instance of the database to read.
        cosmos_db_credentials: Credentials to use for authentication with Azure.
        **kwargs: Additional keyword arguments to pass.

    Returns:
        A dict representing the new item.

    Example:
        Create an item in the container.

        To update or replace an existing item, use the upsert_item method.
        ```python
        import uuid

        from prefect import flow

        from prefect_azure import AzureCosmosDbCredentials
        from prefect_azure.cosmos_db import cosmos_db_create_item

        @flow
        def example_cosmos_db_create_item_flow():
            connection_string = "connection_string"
            cosmos_db_credentials = AzureCosmosDbCredentials(connection_string)

            body = {
                "firstname": "Olivia",
                "age": 3,
                "id": str(uuid.uuid4())
            }
            container = "Persons"
            database = "SampleDB"

            result = cosmos_db_create_item(
                body,
                container,
                database,
                cosmos_db_credentials
            )
            return result

        example_cosmos_db_create_item_flow()
        ```
    """
    logger = get_run_logger()
    logger.info(
        "Creating the item within container %s under %s database",
        container,
        database,
    )

    container_client = cosmos_db_credentials.get_container_client(container, database)
    create_item = partial(container_client.create_item, body, **kwargs)
    result = await to_thread.run_sync(create_item)
    return result

cosmos_db_query_items async

Return all results matching the given query.

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

Parameters:

Name Type Description Default
query str

The Azure Cosmos DB SQL query to execute.

required
container Union[str, ContainerProxy, Dict[str, Any]]

The ID (name) of the container, a ContainerProxy instance, or a dict representing the properties of the container to be retrieved.

required
database Union[str, DatabaseProxy, Dict[str, Any]]

The ID (name), dict representing the properties or DatabaseProxy instance of the database to read.

required
cosmos_db_credentials AzureCosmosDbCredentials

Credentials to use for authentication with Azure.

required
parameters Optional[List[Dict[str, object]]]

Optional array of parameters to the query. Each parameter is a dict() with 'name' and 'value' keys.

None
partition_key Optional[Any]

Partition key for the item to retrieve.

None
**kwargs Any

Additional keyword arguments to pass.

{}

Returns:

Type Description
List[Union[str, dict]]

An list of results.

Example

Query SampleDB Persons container where age >= 44

from prefect import flow

from prefect_azure import AzureCosmosDbCredentials
from prefect_azure.cosmos_db import cosmos_db_query_items

@flow
def example_cosmos_db_query_items_flow():
    connection_string = "connection_string"
    cosmos_db_credentials = AzureCosmosDbCredentials(connection_string)

    query = "SELECT * FROM c where c.age >= @age"
    container = "Persons"
    database = "SampleDB"
    parameters = [dict(name="@age", value=44)]

    results = cosmos_db_query_items(
        query,
        container,
        database,
        cosmos_db_credentials,
        parameters=parameters,
        enable_cross_partition_query=True,
    )
    return results

example_cosmos_db_query_items_flow()

Source code in prefect_azure/cosmos_db.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
@task
async def cosmos_db_query_items(
    query: str,
    container: Union[str, "ContainerProxy", Dict[str, Any]],
    database: Union[str, "DatabaseProxy", Dict[str, Any]],
    cosmos_db_credentials: AzureCosmosDbCredentials,
    parameters: Optional[List[Dict[str, object]]] = None,
    partition_key: Optional[Any] = None,
    **kwargs: Any,
) -> List[Union[str, dict]]:
    """
    Return all results matching the given query.

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

    Args:
        query: The Azure Cosmos DB SQL query to execute.
        container: The ID (name) of the container, a ContainerProxy instance,
            or a dict representing the properties of the container to be retrieved.
        database: The ID (name), dict representing the properties
            or DatabaseProxy instance of the database to read.
        cosmos_db_credentials: Credentials to use for authentication with Azure.
        parameters: Optional array of parameters to the query.
            Each parameter is a dict() with 'name' and 'value' keys.
        partition_key: Partition key for the item to retrieve.
        **kwargs: Additional keyword arguments to pass.

    Returns:
        An `list` of results.

    Example:
        Query SampleDB Persons container where age >= 44
        ```python
        from prefect import flow

        from prefect_azure import AzureCosmosDbCredentials
        from prefect_azure.cosmos_db import cosmos_db_query_items

        @flow
        def example_cosmos_db_query_items_flow():
            connection_string = "connection_string"
            cosmos_db_credentials = AzureCosmosDbCredentials(connection_string)

            query = "SELECT * FROM c where c.age >= @age"
            container = "Persons"
            database = "SampleDB"
            parameters = [dict(name="@age", value=44)]

            results = cosmos_db_query_items(
                query,
                container,
                database,
                cosmos_db_credentials,
                parameters=parameters,
                enable_cross_partition_query=True,
            )
            return results

        example_cosmos_db_query_items_flow()
        ```
    """
    logger = get_run_logger()
    logger.info("Running query from container %s in %s database", container, database)

    container_client = cosmos_db_credentials.get_container_client(container, database)
    partial_query_items = partial(
        container_client.query_items,
        query,
        parameters=parameters,
        partition_key=partition_key,
        **kwargs,
    )
    results = await to_thread.run_sync(partial_query_items)
    return results

cosmos_db_read_item async

Get the item identified by item.

Parameters:

Name Type Description Default
item Union[str, Dict[str, Any]]

The ID (name) or dict representing item to retrieve.

required
partition_key Any

Partition key for the item to retrieve.

required
container Union[str, ContainerProxy, Dict[str, Any]]

The ID (name) of the container, a ContainerProxy instance, or a dict representing the properties of the container to be retrieved.

required
database Union[str, DatabaseProxy, Dict[str, Any]]

The ID (name), dict representing the properties or DatabaseProxy instance of the database to read.

required
cosmos_db_credentials AzureCosmosDbCredentials

Credentials to use for authentication with Azure.

required
**kwargs Any

Additional keyword arguments to pass.

{}

Returns:

Type Description
List[Union[str, dict]]

Dict representing the item to be retrieved.

Example

Read an item using a partition key from Cosmos DB.

from prefect import flow

from prefect_azure import AzureCosmosDbCredentials
from prefect_azure.cosmos_db import cosmos_db_read_item

@flow
def example_cosmos_db_read_item_flow():
    connection_string = "connection_string"
    cosmos_db_credentials = AzureCosmosDbCredentials(connection_string)

    item = "item"
    partition_key = "partition_key"
    container = "container"
    database = "database"

    result = cosmos_db_read_item(
        item,
        partition_key,
        container,
        database,
        cosmos_db_credentials
    )
    return result

example_cosmos_db_read_item_flow()

Source code in prefect_azure/cosmos_db.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@task
async def cosmos_db_read_item(
    item: Union[str, Dict[str, Any]],
    partition_key: Any,
    container: Union[str, "ContainerProxy", Dict[str, Any]],
    database: Union[str, "DatabaseProxy", Dict[str, Any]],
    cosmos_db_credentials: AzureCosmosDbCredentials,
    **kwargs: Any,
) -> List[Union[str, dict]]:
    """
    Get the item identified by item.

    Args:
        item: The ID (name) or dict representing item to retrieve.
        partition_key: Partition key for the item to retrieve.
        container: The ID (name) of the container, a ContainerProxy instance,
            or a dict representing the properties of the container to be retrieved.
        database: The ID (name), dict representing the properties
            or DatabaseProxy instance of the database to read.
        cosmos_db_credentials: Credentials to use for authentication with Azure.
        **kwargs: Additional keyword arguments to pass.

    Returns:
        Dict representing the item to be retrieved.

    Example:
        Read an item using a partition key from Cosmos DB.
        ```python
        from prefect import flow

        from prefect_azure import AzureCosmosDbCredentials
        from prefect_azure.cosmos_db import cosmos_db_read_item

        @flow
        def example_cosmos_db_read_item_flow():
            connection_string = "connection_string"
            cosmos_db_credentials = AzureCosmosDbCredentials(connection_string)

            item = "item"
            partition_key = "partition_key"
            container = "container"
            database = "database"

            result = cosmos_db_read_item(
                item,
                partition_key,
                container,
                database,
                cosmos_db_credentials
            )
            return result

        example_cosmos_db_read_item_flow()
        ```
    """
    logger = get_run_logger()
    logger.info(
        "Reading item %s with partition_key %s from container %s in %s database",
        item,
        partition_key,
        container,
        database,
    )

    container_client = cosmos_db_credentials.get_container_client(container, database)
    read_item = partial(container_client.read_item, item, partition_key, **kwargs)
    result = await to_thread.run_sync(read_item)
    return result