astrapy

DataAPIClient Collection AsyncCollection AsyncDatabase __version__ AstraDBAdmin DataAPIDatabaseAdmin Database AstraDBDatabaseAdmin


AO

AO = TypeVar('AO', bound='BaseAPIOptions')


A description of the options about how to interact with the Data API.

BaseAPIOptions

a default timeout, in millisecond, for the duration of each
operation on the collection. Individual timeouts can be provided to
each collection method call and will take precedence, with this value
being an overall default.
Note that for some methods involving multiple API calls (such as
`find`, `delete_many`, `insert_many` and so on), it is strongly suggested
to provide a specific timeout as the default one likely wouldn't make
much sense.


Return a new instance created by completing this instance with a default
API options object.

In other words, `optA.with_default(optB)` will take fields from optA
when possible and draw defaults from optB when optA has them set to anything
evaluating to False. (This relies on the __bool__ definition of the values,
such as that of the EmbeddingHeadersTokenProvider instances)

default

an API options instance to draw defaults from.

a new instance of this class obtained by merging this one and the default.


Return a new instance created by overriding the members of this instance
with those taken from a supplied "override" API options object.

In other words, `optA.with_default(optB)` will take fields from optB
when possible and fall back to optA when optB has them set to anything
evaluating to False. (This relies on the __bool__ definition of the values,
such as that of the EmbeddingHeadersTokenProvider instances)

override

an API options instance to preferentially draw fields from.

a new instance of this class obtained by merging the override and this one.


A description of the options about how to interact with the Data API
regarding a collection.
Developers should not instantiate this class directly.

CollectionAPIOptions

an `astrapy.authentication.EmbeddingHeadersProvider`
object, encoding embedding-related API keys that will be passed
as headers when interacting with the collection (on each Data API request).
The default value is `EmbeddingAPIKeyHeaderProvider(None)`, i.e.
no embedding-specific headers, whereas if the collection is configured
with an embedding service other choices for this parameter can be
meaningfully supplied. is configured for the collection,


embedding_api_key: EmbeddingHeadersProvider = field(default_factory=lambda: EmbeddingAPIKeyHeaderProvider(None))


Class that represents the generic result of a single mutation operation.

OperationResult

response/responses from the Data API call.
Depending on the exact delete method being used, this
list of raw responses can contain exactly one or a number of items.


Class that represents the result of delete operations.

DeleteResult

number of deleted documents


Class that represents the result of insert_one operations.

InsertOneResult

one-item list with the response from the Data API call

the ID of the inserted document


Class that represents the result of insert_many operations.

InsertManyResult

responses from the Data API calls

list of the IDs of the inserted documents


Class that represents the result of any update operation.

UpdateResult

responses from the Data API calls

a dictionary reporting about the update

the "update_info" field has the following fields: "n" (int),
"updatedExisting" (bool), "ok" (float), "nModified" (int)
and optionally "upserted" containing the ID of an upserted document.


Class that represents the result of a bulk write operations.

Indices in the maps below refer to the position of each write operation
in the list of operations passed to the bulk_write command.

The numeric counts refer to the whole of the bulk write.

BulkWriteResult

a map from indices to the corresponding raw responses

number of deleted documents

number of inserted documents

number of matched documents

number of modified documents

number of upserted documents

a (sparse) map from indices to ID of the upserted document


bulk_api_results: dict[int, list[dict[str, Any]]]


Return an empty BulkWriteResult, for use in no-ops and list reductions.


A Data API database. This is the object for doing database-level
DML, such as creating/deleting collections, and for obtaining Collection
objects themselves. This class has a synchronous interface.

The usual way of obtaining one Database is through the `get_database`
method of a `DataAPIClient`.

On Astra DB, a Database comes with an "API Endpoint", which implies
a Database object instance reaches a specific region (relevant point in
case of multi-region databases).

Database

the full "API Endpoint" string used to reach the Data API.
Example: "https://<database_id>-<region>.apps.astra.datastax.com"

token

an Access Token to the database. Example: "AstraCS:xyz..."
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

keyspace

this is the keyspace all method calls will target, unless
one is explicitly specified in the call. If no keyspace is supplied
when creating a Database, on Astra DB the name "default_keyspace" is set,
while on other environments the keyspace is left unspecified: in this case,
most operations are unavailable until a keyspace is set (through an explicit
`use_keyspace` invocation or equivalent).

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

callers

a list of caller identities, i.e. applications, or frameworks,
on behalf of which the Data API calls are performed. These end up
in the request user-agent.
Each caller identity is a ("caller_name", "caller_version") pair.

*DEPRECATED*, use `callers`. Removal 2.0. Name of the
application, or framework, on behalf of which the Data API calls
are performed. This ends up in the request user-agent.

version of the caller. *DEPRECATED*, use `callers`. Removal 2.0.

environment

a string representing the target Data API environment.
It can be left unspecified for the default value of `Environment.PROD`;
other values include `Environment.OTHER`, `Environment.DSE`.

path to append to the API Endpoint. In typical usage, this
should be left to its default (sensibly chosen based on the environment).

version specifier to append to the API path. In typical
usage, this should be left to its default of "v1".

>>> from astrapy import DataAPIClient
>>> my_client = astrapy.DataAPIClient("AstraCS:...")
>>> my_db = my_client.get_database(
...    "https://01234567-....apps.astra.datastax.com"
... )

creating an instance of Database does not trigger actual creation
of the database itself, which should exist beforehand. To create databases,
see the AstraDBAdmin class.


environment

environment = environment or Environment.PROD.lower()


Create a clone of this database with some changed attributes.

keyspace

this is the keyspace all method calls will target, unless
one is explicitly specified in the call. If no keyspace is supplied
when creating a Database, the name "default_keyspace" is set.

version of the caller. *DEPRECATED*, use `callers`.
Removal 2.0.

a new `Database` instance.

>>> my_db_2 = my_db.with_options(
...     keyspace="the_other_keyspace",
...     callers=[("the_caller", "0.1.0")],
... )


Create an AsyncDatabase from this one. Save for the arguments
explicitly provided as overrides, everything else is kept identical
to this database in the copy.

environment

a string representing the target Data API environment.
Values are, for example, `Environment.PROD`, `Environment.OTHER`,
or `Environment.DSE`.

path to append to the API Endpoint. In typical usage, this
should be left to its default of "/api/json".

the new copy, an `AsyncDatabase` instance.

>>> my_async_db = my_db.to_async()
>>> asyncio.run(my_async_db.list_collection_names())


Set a new identity for the application/framework on behalf of which
the Data API calls are performed (the "caller").

name of the application, or framework, on behalf of which
the Data API calls are performed. This ends up in the request user-agent.

version of the caller.


Switch to a new working namespace for this database.
This method changes (mutates) the Database instance.

*DEPRECATED* (removal in 2.0). Switch to the "use_keyspace" method.**

Note that this method does not create the namespace, which should exist
already (created for instance with a `DatabaseAdmin.create_namespace` call).

namespace

the new namespace to use as the database working namespace.

None.

>>> my_db.list_collection_names()
['coll_1', 'coll_2']
>>> my_db.use_namespace("an_empty_namespace")
>>> my_db.list_collection_names()
[]


Switch to a new working keyspace for this database.
This method changes (mutates) the Database instance.

Note that this method does not create the keyspace, which should exist
already (created for instance with a `DatabaseAdmin.create_keyspace` call).

keyspace

the new keyspace to use as the database working keyspace.

None.

>>> my_db.list_collection_names()
['coll_1', 'coll_2']
>>> my_db.use_keyspace("an_empty_keyspace")
>>> my_db.list_collection_names()
[]


Additional information on the database as a DatabaseInfo instance.

Some of the returned properties are dynamic throughout the lifetime
of the database (such as raw_info["keyspaces"]). For this reason,
each invocation of this method triggers a new request to the DevOps API.

info

>>> my_db.info().region
'eu-west-1'

>>> my_db.info().raw_info['datacenters'][0]['dateCreated']
'2023-01-30T12:34:56Z'

see the DatabaseInfo documentation for a caveat about the difference
between the `region` and the `raw_info["region"]` attributes.


The ID of this database.


The name of this database. Note that this bears no unicity guarantees.

Calling this method the first time involves a request
to the DevOps API (the resulting database name is then cached).
See the `info()` method for more details.


The namespace this database uses as target for all commands when
no method-call-specific namespace is specified.

*DEPRECATED* (removal in 2.0). Switch to the "keyspace" property.**

namespace

the working namespace (a string), or None if not set.


The keyspace this database uses as target for all commands when
no method-call-specific keyspace is specified.

keyspace

the working keyspace (a string), or None if not set.


Spawn a `Collection` object instance representing a collection
on this database.

Creating a `Collection` instance does not have any effect on the
actual state of the database: in other words, for the created
`Collection` instance to be used meaningfully, the collection
must exist already (for instance, it should have been created
previously by calling the `create_collection` method).

name

the name of the collection.

keyspace

the keyspace containing the collection. If no keyspace
is specified, the general setting for this database is used.

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

optional API key(s) for interacting with the collection.
If an embedding service is configured, and this parameter is not None,
each Data API call will include the necessary embedding-related headers
as specified by this parameter. If a string is passed, it translates
into the one "embedding api key" header
(i.e. `astrapy.authentication.EmbeddingAPIKeyHeaderProvider`).
For some vectorize providers/models, if using header-based
authentication, specialized subclasses of
`astrapy.authentication.EmbeddingHeadersProvider` should be supplied.

a default timeout, in millisecond, for the duration
of each operation on the collection. Individual timeouts can be
provided to each collection method call and will take precedence, with
this value being an overall default.
Note that for some methods involving multiple API calls (such as `find`,
`delete_many`, `insert_many` and so on), it is strongly suggested
to provide a specific timeout as the default one likely wouldn't make
much sense.

a `Collection` instance, representing the desired collection
(but without any form of validation).

>>> my_col = my_db.get_collection("my_collection")
>>> my_col.count_documents({}, upper_bound=100)
41

The attribute and indexing syntax forms achieve the same effect
as this method. In other words, the following are equivalent:
    my_db.get_collection("coll_name")
    my_db.coll_name
    my_db["coll_name"]


Creates a collection on the database and return the Collection
instance that represents it.

This is a blocking operation: the method returns when the collection
is ready to be used. As opposed to the `get_collection` instance,
this method triggers causes the collection to be actually created on DB.

name

the name of the collection.

keyspace

the keyspace where the collection is to be created.
If not specified, the general setting for this database is used.

dimension

for vector collections, the dimension of the vectors
(i.e. the number of their components).

metric

the similarity metric used for vector searches.
Allowed values are `VectorMetric.DOT_PRODUCT`, `VectorMetric.EUCLIDEAN`
or `VectorMetric.COSINE` (default).

service

CollectionVectorServiceOptions | dict[str, Any] | None

a dictionary describing a service for
embedding computation, e.g. `{"provider": "ab", "modelName": "xy"}`.
Alternatively, a CollectionVectorServiceOptions object to the same effect.

indexing

optional specification of the indexing options for
the collection, in the form of a dictionary such as
    {"deny": [...]}
or
    {"allow": [...]}

this sets what type of IDs the API server will
generate when inserting documents that do not specify their
`_id` field explicitly. Can be set to any of the values
`DefaultIdType.UUID`, `DefaultIdType.OBJECTID`,
`DefaultIdType.UUIDV6`, `DefaultIdType.UUIDV7`,
`DefaultIdType.DEFAULT`.

any further set of key-value pairs that will
be added to the "options" part of the payload when sending
the Data API command to create a collection.

whether to run an existence check for the collection
name before attempting to create the collection:
If check_exists is True, an error is raised when creating
an existing collection.
If it is False, the creation is attempted. In this case, for
preexisting collections, the command will succeed or fail
depending on whether the options match or not.

a timeout, in milliseconds, for the underlying HTTP request.

optional API key(s) for interacting with the collection.
If an embedding service is configured, and this parameter is not None,
each Data API call will include the necessary embedding-related headers
as specified by this parameter. If a string is passed, it translates
into the one "embedding api key" header
(i.e. `astrapy.authentication.EmbeddingAPIKeyHeaderProvider`).
For some vectorize providers/models, if using header-based authentication,
specialized subclasses of `astrapy.authentication.EmbeddingHeadersProvider`
should be supplied.

a default timeout, in millisecond, for the duration of each
operation on the collection. Individual timeouts can be provided to
each collection method call and will take precedence, with this value
being an overall default.
Note that for some methods involving multiple API calls (such as
`find`, `delete_many`, `insert_many` and so on), it is strongly suggested
to provide a specific timeout as the default one likely wouldn't make
much sense.

a (synchronous) `Collection` instance, representing the

newly-created collection.

>>> new_col = my_db.create_collection("my_v_col", dimension=3)
>>> new_col.insert_one({"name": "the_row", "$vector": [0.4, 0.5, 0.7]})
InsertOneResult(raw_results=..., inserted_id='e22dd65e-...-...-...')

A collection is considered a vector collection if at least one of
`dimension` or `service` are provided and not null. In that case,
and only in that case, is `metric` an accepted parameter.
Note, moreover, that if passing both these parameters, then
the dimension must be compatible with the chosen service.


Drop a collection from the database, along with all documents therein.

either the name of a collection or
a `Collection` instance.

a dictionary in the form {"ok": 1} if the command succeeds.

>>> my_db.list_collection_names()
['a_collection', 'my_v_col', 'another_col']
>>> my_db.drop_collection("my_v_col")
{'ok': 1}
>>> my_db.list_collection_names()
['a_collection', 'another_col']

when providing a collection name, it is assumed that the collection
is to be found in the keyspace that was set at database instance level.


List all collections in a given keyspace for this database.

keyspace

the keyspace to be inspected. If not specified,
the general setting for this database is assumed.

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

a `CommandCursor` to iterate over CollectionDescriptor instances,

each corresponding to a collection.

>>> ccur = my_db.list_collections()
>>> ccur
<astrapy.cursors.CommandCursor object at ...>
>>> list(ccur)
[CollectionDescriptor(name='my_v_col', options=CollectionOptions())]
>>> for coll_dict in my_db.list_collections():
...     print(coll_dict)
...
CollectionDescriptor(name='my_v_col', options=CollectionOptions())


List the names of all collections in a given keyspace of this database.

a list of the collection names as strings, in no particular order.

>>> my_db.list_collection_names()
['a_collection', 'another_col']


Send a POST request to the Data API for this database with
an arbitrary, caller-provided payload.

command

body

a JSON-serializable dictionary, the payload of the request.

keyspace

the keyspace to use. Requests always target a keyspace:
if not specified, the general setting for this database is assumed.

if provided, the collection name is appended at the end
of the endpoint. In this way, this method allows collection-level
arbitrary POST requests as well.

if True, responses with a nonempty 'errors' field
result in an astrapy exception being raised.

a dictionary with the response of the HTTP request.

>>> my_db.command({"findCollections": {}})
{'status': {'collections': ['my_coll']}}
>>> my_db.command({"countDocuments": {}}, collection_name="my_coll")
{'status': {'count': 123}}


Return a DatabaseAdmin object corresponding to this database, for
use in admin tasks such as managing keyspaces.

This method, depending on the environment where the database resides,
returns an appropriate subclass of DatabaseAdmin.

token

an access token with enough permission on the database to
perform the desired tasks. If omitted (as it can generally be done),
the token of this Database is used.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

in case of custom deployments, this can be used to specify
the URL to the DevOps API, such as "https://api.astra.datastax.com".
Generally it can be omitted. The environment (prod/dev/...) is
determined from the API Endpoint.
Note that this parameter is allowed only for Astra DB environments.

this can specify a custom version of the DevOps API
(such as "v2"). Generally not needed.
Note that this parameter is allowed only for Astra DB environments.

A DatabaseAdmin instance targeting this database. More precisely,

for Astra DB an instance of `AstraDBDatabaseAdmin` is returned;

for other environments, an instance of `DataAPIDatabaseAdmin` is returned.

>>> my_db_admin = my_db.get_database_admin()
>>> if "new_keyspace" not in my_db_admin.list_keyspaces():
...     my_db_admin.create_keyspace("new_keyspace")
>>> my_db_admin.list_keyspaces()
['default_keyspace', 'new_keyspace']


A Data API database. This is the object for doing database-level
DML, such as creating/deleting collections, and for obtaining Collection
objects themselves. This class has an asynchronous interface.

The usual way of obtaining one AsyncDatabase is through the `get_async_database`
method of a `DataAPIClient`.

On Astra DB, an AsyncDatabase comes with an "API Endpoint", which implies
an AsyncDatabase object instance reaches a specific region (relevant point in
case of multi-region databases).

AsyncDatabase

the full "API Endpoint" string used to reach the Data API.
Example: "https://<database_id>-<region>.apps.astra.datastax.com"

an Access Token to the database. Example: "AstraCS:xyz..."
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

keyspace

this is the keyspace all method calls will target, unless
one is explicitly specified in the call. If no keyspace is supplied
when creating a Database, on Astra DB the name "default_keyspace" is set,
while on other environments the keyspace is left unspecified: in this case,
most operations are unavailable until a keyspace is set (through an explicit
`use_keyspace` invocation or equivalent).

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

callers

a list of caller identities, i.e. applications, or frameworks,
on behalf of which the Data API calls are performed. These end up
in the request user-agent.
Each caller identity is a ("caller_name", "caller_version") pair.

*DEPRECATED*, use `callers`. Removal 2.0. Name of the
application, or framework, on behalf of which the Data API calls
are performed. This ends up in the request user-agent.

version of the caller. *DEPRECATED*, use `callers`. Removal 2.0.

environment

a string representing the target Data API environment.
It can be left unspecified for the default value of `Environment.PROD`;
other values include `Environment.OTHER`, `Environment.DSE`.

path to append to the API Endpoint. In typical usage, this
should be left to its default (sensibly chosen based on the environment).

version specifier to append to the API path. In typical
usage, this should be left to its default of "v1".

>>> from astrapy import DataAPIClient
>>> my_client = astrapy.DataAPIClient("AstraCS:...")
>>> my_db = my_client.get_async_database(
...    "https://01234567-....apps.astra.datastax.com"
... )

creating an instance of AsyncDatabase does not trigger actual creation
of the database itself, which should exist beforehand. To create databases,
see the AstraDBAdmin class.


Create a clone of this database with some changed attributes.

keyspace

this is the keyspace all method calls will target, unless
one is explicitly specified in the call. If no keyspace is supplied
when creating a Database, the name "default_keyspace" is set.

version of the caller. *DEPRECATED*, use `callers`.
Removal 2.0.

a new `AsyncDatabase` instance.

>>> my_async_db_2 = my_async_db.with_options(
...     keyspace="the_other_keyspace",
...     callers=[("the_caller", "0.1.0")],
... )


Create a (synchronous) Database from this one. Save for the arguments
explicitly provided as overrides, everything else is kept identical
to this database in the copy.

environment

a string representing the target Data API environment.
Values are, for example, `Environment.PROD`, `Environment.OTHER`,
or `Environment.DSE`.

path to append to the API Endpoint. In typical usage, this
should be left to its default of "/api/json".

the new copy, a `Database` instance.

>>> my_sync_db = my_async_db.to_sync()
>>> my_sync_db.list_collection_names()
['a_collection', 'another_collection']


Set a new identity for the application/framework on behalf of which
the Data API calls are performed (the "caller").

name of the application, or framework, on behalf of which
the Data API calls are performed. This ends up in the request user-agent.

version of the caller.


Switch to a new working namespace for this database.
This method changes (mutates) the AsyncDatabase instance.

*DEPRECATED* (removal in 2.0). Switch to the "use_keyspace" method.**

Note that this method does not create the namespace, which should exist
already (created for instance with a `DatabaseAdmin.async_create_namespace` call).

namespace

the new namespace to use as the database working namespace.

None.

>>> asyncio.run(my_async_db.list_collection_names())
['coll_1', 'coll_2']
>>> my_async_db.use_namespace("an_empty_namespace")
>>> asyncio.run(my_async_db.list_collection_names())
[]


Switch to a new working keyspace for this database.
This method changes (mutates) the AsyncDatabase instance.

Note that this method does not create the keyspace, which should exist
already (created for instance with a `DatabaseAdmin.async_create_keyspace` call).

keyspace

the new keyspace to use as the database working keyspace.

None.

>>> asyncio.run(my_async_db.list_collection_names())
['coll_1', 'coll_2']
>>> my_async_db.use_keyspace("an_empty_keyspace")
>>> asyncio.run(my_async_db.list_collection_names())
[]


Additional information on the database as a DatabaseInfo instance.

Some of the returned properties are dynamic throughout the lifetime
of the database (such as raw_info["keyspaces"]). For this reason,
each invocation of this method triggers a new request to the DevOps API.

info

>>> my_async_db.info().region
'eu-west-1'

>>> my_async_db.info().raw_info['datacenters'][0]['dateCreated']
'2023-01-30T12:34:56Z'


The ID of this database.


The name of this database. Note that this bears no unicity guarantees.

Calling this method the first time involves a request
to the DevOps API (the resulting database name is then cached).
See the `info()` method for more details.


The namespace this database uses as target for all commands when
no method-call-specific namespace is specified.

*DEPRECATED* (removal in 2.0). Switch to the "keyspace" property.**

namespace

the working namespace (a string), or None if not set.


The keyspace this database uses as target for all commands when
no method-call-specific keyspace is specified.

keyspace

the working keyspace (a string), or None if not set.


Spawn an `AsyncCollection` object instance representing a collection
on this database.

Creating an `AsyncCollection` instance does not have any effect on the
actual state of the database: in other words, for the created
`AsyncCollection` instance to be used meaningfully, the collection
must exist already (for instance, it should have been created
previously by calling the `create_collection` method).

name

the name of the collection.

keyspace

the keyspace containing the collection. If no keyspace
is specified, the setting for this database is used.

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

optional API key(s) for interacting with the collection.
If an embedding service is configured, and this parameter is not None,
each Data API call will include the necessary embedding-related headers
as specified by this parameter. If a string is passed, it translates
into the one "embedding api key" header
(i.e. `astrapy.authentication.EmbeddingAPIKeyHeaderProvider`).
For some vectorize providers/models, if using header-based
authentication, specialized subclasses of
`astrapy.authentication.EmbeddingHeadersProvider` should be supplied.

a default timeout, in millisecond, for the duration
of each operation on the collection. Individual timeouts can be
provided to each collection method call and will take precedence, with
this value being an overall default.
Note that for some methods involving multiple API calls (such as `find`,
`delete_many`, `insert_many` and so on), it is strongly suggested
to provide a specific timeout as the default one likely wouldn't make
much sense.

an `AsyncCollection` instance, representing the desired collection
(but without any form of validation).

>>> async def count_docs(adb: AsyncDatabase, c_name: str) -> int:
...    async_col = await adb.get_collection(c_name)
...    return await async_col.count_documents({}, upper_bound=100)
...
>>> asyncio.run(count_docs(my_async_db, "my_collection"))
45

as this method, returning an AsyncCollection, albeit
in a synchronous way. In other words, the following are equivalent:
    await my_async_db.get_collection("coll_name")
    my_async_db.coll_name
    my_async_db["coll_name"]


Creates a collection on the database and return the AsyncCollection
instance that represents it.

This is a blocking operation: the method returns when the collection
is ready to be used. As opposed to the `get_collection` instance,
this method triggers causes the collection to be actually created on DB.

name

the name of the collection.

keyspace

the keyspace where the collection is to be created.
If not specified, the general setting for this database is used.

dimension

for vector collections, the dimension of the vectors
(i.e. the number of their components).

metric

the similarity metric used for vector searches.
Allowed values are `VectorMetric.DOT_PRODUCT`, `VectorMetric.EUCLIDEAN`
or `VectorMetric.COSINE` (default).

service

a dictionary describing a service for
embedding computation, e.g. `{"provider": "ab", "modelName": "xy"}`.
Alternatively, a CollectionVectorServiceOptions object to the same effect.

indexing

optional specification of the indexing options for
the collection, in the form of a dictionary such as
    {"deny": [...]}
or
    {"allow": [...]}

this sets what type of IDs the API server will
generate when inserting documents that do not specify their
`_id` field explicitly. Can be set to any of the values
`DefaultIdType.UUID`, `DefaultIdType.OBJECTID`,
`DefaultIdType.UUIDV6`, `DefaultIdType.UUIDV7`,
`DefaultIdType.DEFAULT`.

any further set of key-value pairs that will
be added to the "options" part of the payload when sending
the Data API command to create a collection.

whether to run an existence check for the collection
name before attempting to create the collection:
If check_exists is True, an error is raised when creating
an existing collection.
If it is False, the creation is attempted. In this case, for
preexisting collections, the command will succeed or fail
depending on whether the options match or not.

a timeout, in milliseconds, for the underlying HTTP request.

optional API key(s) for interacting with the collection.
If an embedding service is configured, and this parameter is not None,
each Data API call will include the necessary embedding-related headers
as specified by this parameter. If a string is passed, it translates
into the one "embedding api key" header
(i.e. `astrapy.authentication.EmbeddingAPIKeyHeaderProvider`).
For some vectorize providers/models, if using header-based authentication,
specialized subclasses of `astrapy.authentication.EmbeddingHeadersProvider`
should be supplied.

a default timeout, in millisecond, for the duration of each
operation on the collection. Individual timeouts can be provided to
each collection method call and will take precedence, with this value
being an overall default.
Note that for some methods involving multiple API calls (such as
`find`, `delete_many`, `insert_many` and so on), it is strongly suggested
to provide a specific timeout as the default one likely wouldn't make
much sense.

an `AsyncCollection` instance, representing the newly-created collection.

>>> async def create_and_insert(adb: AsyncDatabase) -> Dict[str, Any]:
...     new_a_col = await adb.create_collection("my_v_col", dimension=3)
...     return await new_a_col.insert_one(
...         {"name": "the_row", "$vector": [0.4, 0.5, 0.7]},
...     )
...
>>> asyncio.run(create_and_insert(my_async_db))
InsertOneResult(raw_results=..., inserted_id='08f05ecf-...-...-...')


Drop a collection from the database, along with all documents therein.

either the name of a collection or
an `AsyncCollection` instance.

a dictionary in the form {"ok": 1} if the command succeeds.

>>> asyncio.run(my_async_db.list_collection_names())
['a_collection', 'my_v_col', 'another_col']
>>> asyncio.run(my_async_db.drop_collection("my_v_col"))
{'ok': 1}
>>> asyncio.run(my_async_db.list_collection_names())
['a_collection', 'another_col']


List all collections in a given keyspace for this database.

keyspace

the keyspace to be inspected. If not specified,
the general setting for this database is assumed.

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

an `AsyncCommandCursor` to iterate over CollectionDescriptor instances,

each corresponding to a collection.

>>> async def a_list_colls(adb: AsyncDatabase) -> None:
...     a_ccur = adb.list_collections()
...     print("* a_ccur:", a_ccur)
...     print("* list:", [coll async for coll in a_ccur])
...     async for coll in adb.list_collections():
...         print("* coll:", coll)
...
>>> asyncio.run(a_list_colls(my_async_db))
* a_ccur: <astrapy.cursors.AsyncCommandCursor object at ...>
* list: [CollectionDescriptor(name='my_v_col', options=CollectionOptions())]
* coll: CollectionDescriptor(name='my_v_col', options=CollectionOptions())


List the names of all collections in a given keyspace of this database.

a list of the collection names as strings, in no particular order.

>>> asyncio.run(my_async_db.list_collection_names())
['a_collection', 'another_col']


Send a POST request to the Data API for this database with
an arbitrary, caller-provided payload.

command

body

a JSON-serializable dictionary, the payload of the request.

keyspace

the keyspace to use. Requests always target a keyspace:
if not specified, the general setting for this database is assumed.

if provided, the collection name is appended at the end
of the endpoint. In this way, this method allows collection-level
arbitrary POST requests as well.

if True, responses with a nonempty 'errors' field
result in an astrapy exception being raised.

a dictionary with the response of the HTTP request.

>>> asyncio.run(my_async_db.command({"findCollections": {}}))
{'status': {'collections': ['my_coll']}}
>>> asyncio.run(my_async_db.command(
...     {"countDocuments": {}},
...     collection_name="my_coll",
... )
{'status': {'count': 123}}


Return a DatabaseAdmin object corresponding to this database, for
use in admin tasks such as managing keyspaces.

This method, depending on the environment where the database resides,
returns an appropriate subclass of DatabaseAdmin.

token

an access token with enough permission on the database to
perform the desired tasks. If omitted (as it can generally be done),
the token of this Database is used.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

in case of custom deployments, this can be used to specify
the URL to the DevOps API, such as "https://api.astra.datastax.com".
Generally it can be omitted. The environment (prod/dev/...) is
determined from the API Endpoint.
Note that this parameter is allowed only for Astra DB environments.

this can specify a custom version of the DevOps API
(such as "v2"). Generally not needed.
Note that this parameter is allowed only for Astra DB environments.

A DatabaseAdmin instance targeting this database. More precisely,

for Astra DB an instance of `AstraDBDatabaseAdmin` is returned;

for other environments, an instance of `DataAPIDatabaseAdmin` is returned.

>>> my_db_admin = my_async_db.get_database_admin()
>>> if "new_keyspace" not in my_db_admin.list_keyspaces():
...     my_db_admin.create_keyspace("new_keyspace")
>>> my_db_admin.list_keyspaces()
['default_keyspace', 'new_keyspace']


A client for using the Data API. This is the main entry point and sits
at the top of the conceptual "client -> database -> collection" hierarchy.

A client is created first, optionally passing it a suitable Access Token.
Starting from the client, then:
    - databases (Database and AsyncDatabase) are created for working with data
    - AstraDBAdmin objects can be created for admin-level work

DataAPIClient

an Access Token to the database. Example: `"AstraCS:xyz..."`.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

environment

a string representing the target Data API environment.
It can be left unspecified for the default value of `Environment.PROD`;
other values include `Environment.OTHER`, `Environment.DSE`.

callers

a list of caller identities, i.e. applications, or frameworks,
on behalf of which Data API and DevOps API calls are performed.
These end up in the request user-agent.
Each caller identity is a ("caller_name", "caller_version") pair.

*DEPRECATED*, use `callers`. Removal 2.0. Name of the
application, or framework, on behalf of which the Data API and
DevOps API calls are performed. This ends up in the request user-agent.

version of the caller. *DEPRECATED*, use `callers`.
Removal 2.0.

>>> from astrapy import DataAPIClient
>>> my_client = DataAPIClient("AstraCS:...")
>>> my_db0 = my_client.get_database(
...     "https://01234567-....apps.astra.datastax.com"
... )
>>> my_coll = my_db0.create_collection("movies", dimension=2)
>>> my_coll.insert_one({"title": "The Title", "$vector": [0.1, 0.3]})
>>> my_db1 = my_client.get_database("01234567-...")
>>> my_db2 = my_client.get_database("01234567-...", region="us-east1")
>>> my_adm0 = my_client.get_admin()
>>> my_adm1 = my_client.get_admin(token=more_powerful_token_override)
>>> database_list = my_adm0.list_databases()


Create a clone of this DataAPIClient with some changed attributes.

a new DataAPIClient instance.

>>> another_client = my_client.with_options(
...     callers=[("caller_identity", "1.2.0")],
... )


Set a new identity for the application/framework on behalf of which
the API calls will be performed (the "caller").

New objects spawned from this client afterwards will inherit the new settings.

name of the application, or framework, on behalf of which
the API API calls are performed. This ends up in the request user-agent.

version of the caller.


Get a Database object from this client, for doing data-related work.

positional parameter that can stand for both
`api_endpoint` and `id`. Passing them together is an error.

the API Endpoint for the target database
(e.g. `https://<ID>-<REGION>.apps.astra.datastax.com`).
The database must exist already for the resulting object
to be effectively used; in other words, this invocation
does not create the database, just the object instance.
Actual admin work can be achieved by using the AstraDBAdmin object.

token

if supplied, is passed to the Database instead of the client token.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

keyspace

if provided, it is passed to the Database; otherwise
the Database class will apply an environment-specific default.

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

id

the target database ID. This is alternative to using the API Endpoint.

region

the region to use for connecting to the database. The
database must be located in that region. This parameter can be used
only if the database is specified by its ID (instead of API Endpoint).
If this parameter is not passed, and cannot be inferred
from the API endpoint, an additional DevOps API request is made
to determine the default region and use it subsequently.

path to append to the API Endpoint. In typical usage, this
should be left to its default of "/api/json".

version specifier to append to the API path. In typical
usage, this should be left to its default of "v1".

a timeout, in milliseconds, for the DevOps API
HTTP request should it be necessary (see the `region` argument).

a Database object with which to work on Data API collections.

>>> my_db0 = my_client.get_database("01234567-...")
>>> my_db1 = my_client.get_database(
...     "https://01234567-...us-west1.apps.astra.datastax.com",
... )
>>> my_db2 = my_client.get_database("01234567-...", token="AstraCS:...")
>>> my_db3 = my_client.get_database("01234567-...", region="us-west1")
>>> my_coll = my_db0.create_collection("movies", dimension=2)
>>> my_coll.insert_one({"title": "The Title", "$vector": [0.3, 0.4]})

This method does not perform any admin-level operation through
the DevOps API. For actual creation of a database, see the
`create_database` method of class AstraDBAdmin.


Get an AsyncDatabase object from this client, for doing data-related work.

>>> async def create_use_db(cl: DataAPIClient, api_ep: str) -> None:
...     async_db = cl.get_async_database(api_ep)
...     my_a_coll = await async_db.create_collection("movies", dimension=2)
...     await my_a_coll.insert_one({"title": "The Title", "$vector": [0.3, 0.4]})
...
>>> asyncio.run(
...   create_use_db(
...       my_client,
...       "https://01234567-...us-west1.apps.astra.datastax.com",
...   )
... )


Get a Database object from this client, for doing data-related work.
The Database is specified by an API Endpoint instead of the ID and a region.

Note that using this method is generally equivalent to passing
an API Endpoint as parameter to the `get_database` method (see).

the full "API Endpoint" string used to reach the Data API.
Example: "https://DATABASE_ID-REGION.apps.astra.datastax.com"

>>> my_db0 = my_client.get_database_by_api_endpoint("01234567-...")
>>> my_db1 = my_client.get_database_by_api_endpoint(
...     "https://01234567-....apps.astra.datastax.com",
...     token="AstraCS:...",
... )
>>> my_db2 = my_client.get_database_by_api_endpoint(
...     "https://01234567-....apps.astra.datastax.com",
...     keyspace="the_other_keyspace",
... )
>>> my_coll = my_db0.create_collection("movies", dimension=2)
>>> my_coll.insert_one({"title": "The Title", "$vector": [0.5, 0.6]})


Get an AsyncDatabase object from this client, for doing data-related work.
The Database is specified by an API Endpoint instead of the ID and a region.

Note that using this method is generally equivalent to passing
an API Endpoint as parameter to the `get_async_database` method (see).

This method has identical behavior and signature as the sync
counterpart `get_database_by_api_endpoint`: please see that one
for more details.


Get an AstraDBAdmin instance corresponding to this client, for
admin work such as managing databases.

token

if supplied, is passed to the Astra DB Admin instead of the
client token. This may be useful when switching to a more powerful,
admin-capable permission set.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

in case of custom deployments, this can be used to specify
the URL to the DevOps API, such as "https://api.astra.datastax.com".
Generally it can be omitted. The environment (prod/dev/...) is
determined from the API Endpoint.

this can specify a custom version of the DevOps API
(such as "v2"). Generally not needed.

An AstraDBAdmin instance, wich which to perform management at the

database level.

>>> my_adm0 = my_client.get_admin()
>>> my_adm1 = my_client.get_admin(token=more_powerful_token_override)
>>> database_list = my_adm0.list_databases()
>>> my_db_admin = my_adm0.create_database(
...     "the_other_database",
...     cloud_provider="AWS",
...     region="eu-west-1",
... )
>>> my_db_admin.list_keyspaces()
['default_keyspace', 'that_other_one']


IndexPairType

IndexPairType = Tuple[str, Optional[int]]


preread_item: DocumentType | None = None


Represents a generic Cursor over query results, regardless of whether
synchronous or asynchronous. It cannot be instantiated.

See classes Cursor and AsyncCursor for more information.


The current state of this cursor, which can be one of
the astrapy.cursors.CursorState enum.


The API endpoint used by this cursor when issuing
requests to the database.


Whether the cursor has the potential to yield more data.


Clone the cursor into a new, fresh one.

clone

a copy of this cursor, reset to its pristine state,

i.e. fully un-consumed.


Stop/kill the cursor, regardless of its status.


An integer uniquely identifying this cursor.


Set a new `limit` value for this cursor.

limit

the new value to set

this cursor itself.


Set a new `include_similarity` value for this cursor.

the new value to set

this cursor itself.


Set a new `include_sort_vector` value for this cursor.

the new value to set

this cursor itself.


The number of documents consumed so far (by the code consuming the cursor).


Reset the cursor to its pristine state, i.e. fully unconsumed.

rewind

this cursor itself.


Set a new `skip` value for this cursor.

skip

the new value to set

this cursor itself.

This parameter can be used only in conjunction with an explicit
`sort` criterion of the ascending/descending type (i.e. it cannot
be used when not sorting, nor with vector-based ANN search).


Set a new `sort` value for this cursor.

sort

the new sorting prescription to set

this cursor itself.

Some combinations of arguments impose an implicit upper bound on the
number of documents that are returned by the Data API. More specifically:
(a) Vector ANN searches cannot return more than a number of documents
that at the time of writing is set to 1000 items.
(b) When using a sort criterion of the ascending/descending type,
the Data API will return a smaller number of documents, set to 20
at the time of writing, and stop there. The returned documents are
the top results across the whole collection according to the requested
criterion.
These provisions should be kept in mind even when subsequently running
a command such as `.distinct()` on a cursor.


Represents a (synchronous) cursor over documents in a collection.
A cursor is iterated over, e.g. with a for loop, and keeps track of
its progress.

Generally cursors are not supposed to be instantiated directly,
rather they are obtained by invoking the `find` method on a collection.

Cursor

collection

the collection to find documents in
filter: a predicate expressed as a dictionary according to the
    Data API filter syntax. Examples are:
        {}
        {"name": "John"}
        {"price": {"$le": 100}}
        {"$and": [{"name": "John"}, {"price": {"$le": 100}}]}
    See the Data API documentation for the full set of operators.
projection: used to select a subset of fields in the document being
    returned. The projection can be: an iterable over the field names
    to return; a dictionary {field_name: True} to positively select
    certain fields; or a dictionary {field_name: False} if one wants
    to discard some fields from the response.
    The default is to return the whole documents.
max_time_ms: a timeout, in milliseconds, for each single one
    of the underlying HTTP requests used to fetch documents as the
    cursor is iterated over.

When not specifying sorting criteria at all (by vector or otherwise),
the cursor can scroll through an arbitrary number of documents as
the Data API and the client periodically exchange new chunks of documents.
It should be noted that the behavior of the cursor in the case documents
have been added/removed after the cursor was started depends on database
internals and it is not guaranteed, nor excluded, that such "real-time"
changes in the data would be picked up by the cursor.


Return the vector used in this ANN search, if applicable.
If this is not an ANN search, or it was invoked without the
`include_sort_vector` parameter, return None.

Invoking this method on a pristine cursor will trigger an API call
to get the first page of results.


The (synchronous) collection this cursor is targeting.


Compute a list of unique values for a specific field across all
documents the cursor iterates through.

Invoking this method has no effect on the cursor state, i.e.
the position of the cursor is unchanged.

distinct

key

the name of the field whose value is inspected across documents.
Keys can use dot-notation to descend to deeper document levels.
Example of acceptable `key` values:
    "field"
    "field.subfield"
    "field.3"
    "field.3.subfield"
if lists are encountered and no numeric index is specified,
all items in the list are visited.

a timeout, in milliseconds, for the operation.

this operation works at client-side by scrolling through all
documents matching the cursor parameters (such as `filter`).
Please be aware of this fact, especially for a very large
amount of documents, for this may have implications on latency,
network traffic and possibly billing.


Represents a (asynchronous) cursor over documents in a collection.
An asynchronous cursor is iterated over, e.g. with a for loop,
and keeps track of its progress.

Generally cursors are not supposed to be instantiated directly,
rather they are obtained by invoking the `find` method on a collection.


The (asynchronous) collection this cursor is targeting.


A (synchronous) cursor over the results of a Data API command
(as opposed to a cursor over data as one would get with a `find` method).

Command cursors are iterated over, e.g. with a for loop.

Generally command cursors are not supposed to be instantiated directly,
rather they are obtained by invoking methods on a collection/database
(such as the database `list_collections` method).


The current state of this cursor, which can be:
    - "alive": the cursor has still the potential to return items.
    - "exhausted": the cursor has finished and won't return documents


The API endpoint used by this cursor when issuing
requests to the database.


Whether the cursor has the potential to yield more data.


Stop/kill the cursor, regardless of its status.


A (asynchronous) cursor over the results of a Data API command
(as opposed to a cursor over data as one would get with a `find` method).

Asynchronous command cursors are iterated over, e.g. with an async for loop.

Generally command cursors are not supposed to be instantiated directly,
rather they are obtained by invoking methods on a collection/database
(such as the database `list_collections` method).


An integer uniquely identifying this cursor.


ProjectionType

ProjectionType = Union[Iterable[str], Dict[str, Union[bool, Dict[str, Union[int, Iterable[int]]]]]]


CallerType

CallerType = Tuple[Union[str, None], Union[str, None]]


dict[str, bool | dict[str, int | Iterable[int]]] | None


Admitted values for the `return_document` parameter in
`find_one_and_replace` and `find_one_and_update` collection
methods.


Admitted values for the `sort` parameter in the find collection methods,
e.g. `sort={"field": SortDocuments.ASCENDING}`.


Admitted values for the "metric" parameter when creating vector collections
through the database `create_collection` method.


Admitted values for the "default_id_type" parameter when creating collections
through the database `create_collection` method.


Admitted values for `environment` property,
denoting the targeted API deployment type.


values

values = {PROD, DEV, TEST, DSE, HCD, CASSANDRA, OTHER}


Reduce a list of bulk write results into a single one.

results

a list of BulkWriteResult instances.

A new BulkWRiteResult object which summarized the whole input list.


Base class for all operations amenable to be used
in bulk writes on (sync) collections.


Represents an `insert_one` operation on a (sync) collection.
See the documentation on the collection method for more information.

InsertOne

document

the document to insert.

vector

an optional suitable vector to enrich the document at insertion.
*DEPRECATED* (removal in 2.0). Use a `$vector` key in the document instead.

vectorize

a string to be made into a vector, with the same result as the
`vector` attribute, through an embedding service, assuming one is
configured for the collection.
*DEPRECATED* (removal in 2.0). Use a `$vectorize` key in the documents instead.


Execute this operation against a collection as part of a bulk write.

execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents an `insert_many` operation on a (sync) collection.
See the documentation on the collection method for more information.

InsertMany

documents

the list document to insert.

vectors

an optional list of vectors to enrich the documents at insertion.
*DEPRECATED* (removal in 2.0). Use a `$vector` key in the documents instead.

vectorize

an optional list of texts achieving the same effect as `vectors`
except through an embedding service, if one is configured for the collection.
*DEPRECATED* (removal in 2.0). Use a `$vectorize` key in the documents instead.

ordered

whether the inserts should be done in sequence.

how many documents to include in a single API request.
Exceeding the server maximum allowed value results in an error.
Leave it unspecified (recommended) to use the system default.

concurrency

maximum number of concurrent requests to the API at
a given time. It cannot be more than one for ordered insertions.


documents

documents: Iterable[DocumentType] = documents


vectors

vectors: Iterable[VectorType | None] | None = vectors


vectorize

vectorize: Iterable[str | None] | None = vectorize


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents an `update_one` operation on a (sync) collection.
See the documentation on the collection method for more information.

UpdateOne

filter

a filter condition to select a target document.

update

an update prescription to apply to the document.

vector

a vector of numbers to use for ANN (vector-search) sorting.
*DEPRECATED* (removal in 2.0). Use a `$vector` key in the
sort clause dict instead.

vectorize

a string to be made into a vector, with the same result as the
`vector` attribute, through an embedding service, assuming one is
configured for the collection.
*DEPRECATED* (removal in 2.0). Use a `$vectorize` key in the
sort clause dict instead.

sort

controls ordering of results, hence which document is affected.

upsert

controls what to do when no documents are found.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents an `update_many` operation on a (sync) collection.
See the documentation on the collection method for more information.

UpdateMany

filter

a filter condition to select target documents.

update

an update prescription to apply to the documents.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents a `replace_one` operation on a (sync) collection.
See the documentation on the collection method for more information.

ReplaceOne

replacement

the replacement document.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents a `delete_one` operation on a (sync) collection.
See the documentation on the collection method for more information.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents a `delete_many` operation on a (sync) collection.
See the documentation on the collection method for more information.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Base class for all operations amenable to be used
in bulk writes on (async) collections.


Represents an `insert_one` operation on a (async) collection.
See the documentation on the collection method for more information.

AsyncInsertOne

document

the document to insert.

vectorize

a string to be made into a vector, with the same result as the
`vector` attribute, through an embedding service, assuming one is
configured for the collection.
*DEPRECATED* (removal in 2.0). Use a `$vectorize` key in the document instead.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents an `insert_many` operation on a (async) collection.
See the documentation on the collection method for more information.

AsyncInsertMany

documents

the list document to insert.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents an `update_one` operation on a (async) collection.
See the documentation on the collection method for more information.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents an `update_many` operation on a (async) collection.
See the documentation on the collection method for more information.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents a `replace_one` operation on a (async) collection.
See the documentation on the collection method for more information.

AsyncReplaceOne

replacement

the replacement document.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents a `delete_one` operation on a (async) collection.
See the documentation on the collection method for more information.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


Represents a `delete_many` operation on a (async) collection.
See the documentation on the collection method for more information.


execute

collection

the collection this write targets.

the index in the list of bulkoperations


api_endpoint_description = 'https://<db uuid, 8-4-4-4-12 hex format>-<db region>.apps.astra.datastax.com'


generic_api_url_descriptor = 'http[s]://<domain name or IP>[:port]'


The results of successfully parsing an Astra DB API endpoint, for internal
by database metadata-related functions.

ParsedAPIEndpoint

e. g. "01234567-89ab-cdef-0123-456789abcdef".

region

a region ID, such as "us-west1".

environment

a label, whose value is one of Environment.PROD,
Environment.DEV or Environment.TEST.


Parse an API Endpoint into a ParsedAPIEndpoint structure.

a full API endpoint for the Data API.

The parsed ParsedAPIEndpoint. If parsing fails, return None.


Format an error message with a suggestion for the expected url format.


Validate a generic API Endpoint string,
such as `http://10.1.1.1:123` or `https://my.domain`.

a string supposedly expressing a valid API Endpoint

a normalized (stripped) version of the endpoint if valid. If invalid,

return None.


Build the API Endpoint full strings from database parameters.

environment

a label, whose value can be Environment.PROD
or another of Environment.* for which this operation makes sense.

region

a region ID, such as "us-west1".

the endpoint string, such as "https://01234567-...-eu-west1.apps.datastax.com"


Utility function helping with the transition to endpoint-first constructors,
with ID being the other possibility.

It is called with the positional argument, the api_endpoint and id kwargs: it
then verifies legitimacy and returns a normalized (endpoint, id) "either" value.

Note: this uses the ID regexp to recognize IDs. Crucially, no endpoint regexp
here, since even non-Astra endpoints must be properly processed by this validator.


Fetch database information through the DevOps API and return it in
full, exactly like the API gives it back.

token

a valid token to access the database information.

environment

a string representing the target Data API environment.
It can be left unspecified for the default value of `Environment.PROD`.
Only Astra DB environments can be meaningfully supplied.

a timeout, in milliseconds, for waiting on a response.

The full response from the DevOps API about the database.


Fetch database information through the DevOps API and return it in
full, exactly like the API gives it back.
Async version of the function, for use in an asyncio context.


Fetch database information through the DevOps API.

a full API endpoint for the Data API.

keyspace

the desired keyspace that will be used in the result.
If not specified, the resulting database info will show it as None.

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

A DatabaseInfo object.

If the API endpoint fails to be parsed, None is returned.

For valid-looking endpoints, if something goes wrong an exception is raised.


Fetch database information through the DevOps API.
Async version of the function, for use in an asyncio context.

a full API endpoint for the Data API.

A DatabaseInfo object.


An "admin" object, able to perform administrative tasks at the databases
level, such as creating, listing or dropping databases.

AstraDBAdmin

token

an access token with enough permission to perform admin tasks.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

environment

a label, whose value is one of Environment.PROD (default),
Environment.DEV or Environment.TEST.

callers

a list of caller identities, i.e. applications, or frameworks,
on behalf of which DevOps API calls are performed. These end up in
the request user-agent.
Each caller identity is a ("caller_name", "caller_version") pair.

*DEPRECATED*, use `callers`. Removal 2.0. Name of the
application, or framework, on behalf of which the DevOps API calls
are performed. This ends up in the request user-agent.

version of the caller. *DEPRECATED*, use `callers`. Removal 2.0.

in case of custom deployments, this can be used to specify
the URL to the DevOps API, such as "https://api.astra.datastax.com".
Generally it can be omitted. The environment (prod/dev/...) is
determined from the API Endpoint.

this can specify a custom version of the DevOps API
(such as "v2"). Generally not needed.

>>> from astrapy import DataAPIClient
>>> my_client = DataAPIClient("AstraCS:...")
>>> my_astra_db_admin = my_client.get_admin()
>>> database_list = my_astra_db_admin.list_databases()
>>> len(database_list)
3
>>> database_list[2].id
'01234567-...'
>>> my_db_admin = my_astra_db_admin.get_database_admin("01234567-...")
>>> my_db_admin.list_keyspaces()
['default_keyspace', 'staging_keyspace']


Create a clone of this AstraDBAdmin with some changed attributes.

token

an Access Token to the database. Example: `"AstraCS:xyz..."`.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

version of the caller. *DEPRECATED*, use `callers`.
Removal 2.0.

a new AstraDBAdmin instance.

>>> another_astra_db_admin = my_astra_db_admin.with_options(
...     callers=[("caller_identity", "1.2.0")],
... )


Set a new identity for the application/framework on behalf of which
the DevOps API calls will be performed (the "caller").

New objects spawned from this client afterwards will inherit the new settings.

name of the application, or framework, on behalf of which
the DevOps API calls are performed. This ends up in the request user-agent.

version of the caller.

>>> my_astra_db_admin.set_caller(
...     callers=[("the_caller", "0.1.0")],
... )


Get the list of databases, as obtained with a request to the DevOps API.

include

a filter on what databases are to be returned. As per
DevOps API, defaults to "nonterminated". Pass "all" to include
the already terminated databases.

provider

a filter on the cloud provider for the databases.
As per DevOps API, defaults to "ALL". Pass e.g. "AWS" to
restrict the results.

number of results per page from the DevOps API. Optional.

a timeout, in milliseconds, for the API request.

A CommandCursor to iterate over the detected databases,

represented as AdminDatabaseInfo objects.

>>> database_cursor = my_astra_db_admin.list_databases()
>>> database_list = list(database_cursor)
>>> len(database_list)
3
>>> database_list[2].id
'01234567-...'
>>> database_list[2].status
'ACTIVE'
>>> database_list[2].info.region
'eu-west-1'


Get the list of databases, as obtained with a request to the DevOps API.
Async version of the method, for use in an asyncio context.

Note that the return type is not an awaitable, rather

a regular iterable, e.g. for use in ordinary "for" loops.

>>> async def check_if_db_exists(db_id: str) -> bool:
...     db_cursor = await my_astra_db_admin.async_list_databases()
...     db_list = list(dd_cursor)
...     return db_id in db_list
...
>>> asyncio.run(check_if_db_exists("xyz"))
True
>>> asyncio.run(check_if_db_exists("01234567-..."))
False


Get the full information on a given database, through a request to the DevOps API.

id

the ID of the target database, e. g.
"01234567-89ab-cdef-0123-456789abcdef".

An AdminDatabaseInfo object.

>>> details_of_my_db = my_astra_db_admin.database_info("01234567-...")
>>> details_of_my_db.id
'01234567-...'
>>> details_of_my_db.status
'ACTIVE'
>>> details_of_my_db.info.region
'eu-west-1'


Get the full information on a given database, through a request to the DevOps API.
This is an awaitable method suitable for use within an asyncio event loop.

An AdminDatabaseInfo object.

>>> async def check_if_db_active(db_id: str) -> bool:
...     db_info = await my_astra_db_admin.async_database_info(db_id)
...     return db_info.status == "ACTIVE"
...
>>> asyncio.run(check_if_db_active("01234567-..."))
True


Create a database as requested, optionally waiting for it to be ready.

name

the desired name for the database.

one of 'aws', 'gcp' or 'azure'.

region

any of the available cloud regions.

keyspace

name for the one keyspace the database starts with.
If omitted, DevOps API will use its default.

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

if True (default), the method returns only after
the newly-created database is in ACTIVE state (a few minutes,
usually). If False, it will return right after issuing the
creation request to the DevOps API, and it will be responsibility
of the caller to check the database status before working with it.

a timeout, in milliseconds, for the whole requested
operation to complete.
Note that a timeout is no guarantee that the creation request
has not reached the API server.

An AstraDBDatabaseAdmin instance.

>>> my_new_db_admin = my_astra_db_admin.create_database(
...     "new_database",
...     cloud_provider="aws",
...     region="ap-south-1",
... )
>>> my_new_db = my_new_db_admin.get_database()
>>> my_coll = my_new_db.create_collection("movies", dimension=2)
>>> my_coll.insert_one({"title": "The Title", "$vector": [0.1, 0.2]})


Create a database as requested, optionally waiting for it to be ready.
This is an awaitable method suitable for use within an asyncio event loop.

name

the desired name for the database.

one of 'aws', 'gcp' or 'azure'.

region

any of the available cloud regions.

An AstraDBDatabaseAdmin instance.

>>> asyncio.run(
...     my_astra_db_admin.async_create_database(
...         "new_database",
...         cloud_provider="aws",
...         region="ap-south-1",
....    )
... )
AstraDBDatabaseAdmin(id=...)


Drop a database, i.e. delete it completely and permanently with all its data.

id

The ID of the database to drop, e. g.
"01234567-89ab-cdef-0123-456789abcdef".

if True (default), the method returns only after
the database has actually been deleted (generally a few minutes).
If False, it will return right after issuing the
drop request to the DevOps API, and it will be responsibility
of the caller to check the database status/availability
after that, if desired.

a timeout, in milliseconds, for the whole requested
operation to complete.
Note that a timeout is no guarantee that the deletion request
has not reached the API server.

A dictionary of the form {"ok": 1} in case of success.

Otherwise, an exception is raised.

>>> database_list_pre = my_astra_db_admin.list_databases()
>>> len(database_list_pre)
3
>>> my_astra_db_admin.drop_database("01234567-...")
{'ok': 1}
>>> database_list_post = my_astra_db_admin.list_databases()
>>> len(database_list_post)
2


Drop a database, i.e. delete it completely and permanently with all its data.
Async version of the method, for use in an asyncio context.

Otherwise, an exception is raised.

>>> asyncio.run(
...     my_astra_db_admin.async_drop_database("01234567-...")
... )
{'ok': 1}


Create an AstraDBDatabaseAdmin object for admin work within a certain database.

positional parameter that can stand for both
`api_endpoint` and `id`. Passing them together is an error.

the API Endpoint for the target database
(e.g. `https://<ID>-<REGION>.apps.astra.datastax.com`).
The database must exist already for the resulting object
to be effectively used; in other words, this invocation
does not create the database, just the object instance.

the target database ID. This is alternative to using the API Endpoint.

region

the region to use for connecting to the database. The
database must be located in that region. This parameter can be used
only if the database is specified by its ID (instead of API Endpoint).
If this parameter is not passed, and cannot be inferred
from the API endpoint, an additional DevOps API request is made
to determine the default region and use it subsequently.

a timeout, in milliseconds, for the DevOps API
HTTP request should it be necessary (see the `region` argument).

An AstraDBDatabaseAdmin instance representing the requested database.

>>> my_db_admin = my_astra_db_admin.get_database_admin("01234567-...")
>>> my_db_admin.list_keyspaces()
['default_keyspace']
>>> my_db_admin.create_keyspace("that_other_one")
{'ok': 1}
>>> my_db_admin.list_keyspaces()
['default_keyspace', 'that_other_one']

This method does not perform any admin-level operation through
the DevOps API. For actual creation of a database, see the
`create_database` method.


Create a Database instance for a specific database, to be used
when doing data-level work (such as creating/managing collections).

token

if supplied, is passed to the Database instead of
the one set for this object.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

keyspace

used to specify a certain keyspace the resulting
Database will primarily work on. If not specified, an additional
DevOps API call reveals the default keyspace for the target database.

path to append to the API Endpoint. In typical usage, this
should be left to its default of "/api/json".

version specifier to append to the API path. In typical
usage, this should be left to its default of "v1".

A Database object ready to be used.

>>> my_db = my_astra_db_admin.get_database(
...     "https://<ID>-<REGION>.apps.astra.datastax.com",
...     keyspace="my_prod_keyspace",
... )
>>> coll = my_db.create_collection("movies", dimension=2)
>>> my_coll.insert_one({"title": "The Title", "$vector": [0.3, 0.4]})


Create an AsyncDatabase instance for a specific database, to be used
when doing data-level work (such as creating/managing collections).

used to specify a certain keyspace the resulting
AsyncDatabase will primarily work on. If not specified, an additional
DevOps API call reveals the default keyspace for the target database.

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

An AsyncDatabase object ready to be used.

>>> async def create_use_collection(
...     admin: AstraDBAdmin,
...     api_endpoint: str,
...     keyspace: str,
... ) -> None:
...     my_async_db = admin.get_async_database(
...         api_endpoint,
...         keyspace=keyspace,
...     )
...     a_coll = await my_async_db.create_collection("movies", dimension=2)
...     await a_coll.insert_one(
...         {"title": "The Title", "$vector": [0.3, 0.4]}
...     )
...
>>> asyncio.run(create_use_collection(
...     my_admin,
...     "https://<ID>-<REGION>.apps.astra.datastax.com",
...     "default_keyspace",
... ))
>>>


An abstract class defining the interface for a database admin object.
This supports generic keyspace crud, as well as spawning databases,
without committing to a specific database architecture (e.g. Astra DB).


spawner_database: Database | AsyncDatabase


Get a list of namespaces for the database.


Get a list of keyspaces for the database.


Create a namespace in the database, returning {'ok': 1} if successful.


Create a keyspace in the database, returning {'ok': 1} if successful.


Drop (delete) a namespace from the database, returning {'ok': 1} if successful.


Drop (delete) a keyspace from the database, returning {'ok': 1} if successful.


Get a list of namespaces for the database.
(Async version of the method.)


Get a list of keyspaces for the database.
(Async version of the method.)


Create a namespace in the database, returning {'ok': 1} if successful.
(Async version of the method.)


Create a keyspace in the database, returning {'ok': 1} if successful.
(Async version of the method.)


Drop (delete) a namespace from the database, returning {'ok': 1} if successful.
(Async version of the method.)


Drop (delete) a keyspace from the database, returning {'ok': 1} if successful.
(Async version of the method.)


Get a Database object from this database admin.


Get an AsyncDatabase object from this database admin.


Query the Data API for the available embedding providers.


Query the Data API for the available embedding providers.
(Async version of the method.)


An "admin" object, able to perform administrative tasks at the keyspaces level
(i.e. within a certain database), such as creating/listing/dropping keyspaces.

This is one layer below the AstraDBAdmin concept, in that it is tied to
a single database and enables admin work within it. As such, it is generally
created by a method call on an AstraDBAdmin.

AstraDBDatabaseAdmin

token

an access token with enough permission to perform admin tasks.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

environment

a label, whose value is one of Environment.PROD (default),
Environment.DEV or Environment.TEST.

callers

a list of caller identities, i.e. applications, or frameworks,
on behalf of which Data API and DevOps API calls are performed.
These end up in the request user-agent.
Each caller identity is a ("caller_name", "caller_version") pair.

*DEPRECATED*, use `callers`. Removal 2.0. Name of the
application, or framework, on behalf of which the Data API and
DevOps API calls are performed. This ends up in the request user-agent.

version of the caller. *DEPRECATED*, use `callers`. Removal 2.0.

in case of custom deployments, this can be used to specify
the URL to the DevOps API, such as "https://api.astra.datastax.com".
Generally it can be omitted. The environment (prod/dev/...) is
determined from the API Endpoint.

this can specify a custom version of the DevOps API
(such as "v2"). Generally not needed.

path to append to the API Endpoint. In typical usage, this
class is created by a method such as `Database.get_database_admin()`,
which passes the matching value. Generally to be left to its Astra DB
default of "/api/json".

version specifier to append to the API path. In typical
usage, this class is created by a method such as
`Database.get_database_admin()`, which passes the matching value.
Generally to be left to its Astra DB default of "/v1".

either a Database or an AsyncDatabase instance. This represents
the database class which spawns this admin object, so that, if required,
a keyspace creation can retroactively "use" the new keyspace in the spawner.
Used to enable the Async/Database.get_admin_database().create_keyspace() pattern.

a timeout, in milliseconds, for the DevOps API
HTTP request should it be necessary (see the `region` argument).

>>> from astrapy import DataAPIClient
>>> my_client = DataAPIClient("AstraCS:...")
>>> admin_for_my_db = my_client.get_admin().get_database_admin(
...     "https://<ID>-<REGION>.apps.astra.datastax.com"
... )
>>> admin_for_my_db.list_keyspaces()
['default_keyspace', 'staging_keyspace']
>>> admin_for_my_db.info().status
'ACTIVE'

creating an instance of AstraDBDatabaseAdmin does not trigger actual creation
of the database itself, which should exist beforehand. To create databases,
see the AstraDBAdmin class.


api_path = api_path if api_path is not None else API_PATH_ENV_MAP[self.environment]


api_version = api_version if api_version is not None else API_VERSION_ENV_MAP[self.environment]


dev_ops_url = dev_ops_url if dev_ops_url is not None else DEV_OPS_URL_ENV_MAP[self.environment].rstrip('/')


dev_ops_api_version = dev_ops_api_version if dev_ops_api_version is not None else DEV_OPS_VERSION_ENV_MAP[self.environment].strip('/')


Create a clone of this AstraDBDatabaseAdmin with some changed attributes.

the API Endpoint for the target database
(e.g. `https://<ID>-<REGION>.apps.astra.datastax.com`).
The database must exist already for the resulting object
to be effectively used; in other words, this invocation
does not create the database, just the object instance.

token

an Access Token to the database. Example: `"AstraCS:xyz..."`.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

version of the caller. *DEPRECATED*, use `callers`.
Removal 2.0.

a new AstraDBDatabaseAdmin instance.

>>> admin_for_my_other_db = admin_for_my_db.with_options(
...     "https://<ID>-<REGION>.apps.astra.datastax.com",
... )


Set a new identity for the application/framework on behalf of which
the DevOps API calls will be performed (the "caller").

New objects spawned from this client afterwards will inherit the new settings.

name of the application, or framework, on behalf of which
the DevOps API calls are performed. This ends up in the request user-agent.

version of the caller.

>>> admin_for_my_db.set_caller(
...     caller_name="the_caller",
...     caller_version="0.1.0",
... )


The ID of this database admin.


The region for this database admin.


Create an AstraDBDatabaseAdmin from an AstraDBAdmin and an API Endpoint.

an AstraDBAdmin object that has visibility over
the target database.

An AstraDBDatabaseAdmin object, for admin work within the database.

>>> from astrapy import DataAPIClient, AstraDBDatabaseAdmin
>>> admin_for_my_db = AstraDBDatabaseAdmin.from_astra_db_admin(
...     "https://<ID>-<REGION>.apps.astra.datastax.com",
...     astra_db_admin=DataAPIClient("AstraCS:...").get_admin(),
... )
>>> admin_for_my_db.list_keyspaces()
['default_keyspace', 'staging_keyspace']
>>> admin_for_my_db.info().status
'ACTIVE'

Creating an instance of AstraDBDatabaseAdmin does not trigger actual creation
of the database itself, which should exist beforehand. To create databases,
see the AstraDBAdmin class.


Create an AstraDBDatabaseAdmin from an API Endpoint and optionally a token.

an access token with enough permissions to do admin work.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

>>> from astrapy import AstraDBDatabaseAdmin
>>> admin_for_my_db = AstraDBDatabaseAdmin.from_api_endpoint(
...     api_endpoint="https://01234567-....apps.astra.datastax.com",
...     token="AstraCS:...",
... )
>>> admin_for_my_db.list_keyspaces()
['default_keyspace', 'another_keyspace']
>>> admin_for_my_db.info().status
'ACTIVE'


Query the DevOps API for the full info on this database.

info

a timeout, in milliseconds, for the DevOps API request.

An AdminDatabaseInfo object.

>>> my_db_info = admin_for_my_db.info()
>>> my_db_info.status
'ACTIVE'
>>> my_db_info.info.region
'us-east1'


Query the DevOps API for the full info on this database.
Async version of the method, for use in an asyncio context.

An AdminDatabaseInfo object.

>>> async def wait_until_active(db_admin: AstraDBDatabaseAdmin) -> None:
...     while True:
...         info = await db_admin.async_info()
...         if info.status == "ACTIVE":
...             return
...
>>> asyncio.run(wait_until_active(admin_for_my_db))


Query the DevOps API for a list of the namespaces in the database.

*DEPRECATED* (removal in 2.0). Switch to the "list_keyspaces" method.**

A list of the namespaces, each a string, in no particular order.

>>> admin_for_my_db.list_namespaces()
['default_keyspace', 'staging_namespace']


Query the DevOps API for a list of the keyspaces in the database.

A list of the keyspaces, each a string, in no particular order.

>>> admin_for_my_db.list_keyspaces()
['default_keyspace', 'staging_keyspace']


Query the DevOps API for a list of the namespaces in the database.
Async version of the method, for use in an asyncio context.

*DEPRECATED* (removal in 2.0). Switch to the "keyspace" property.**

>>> async def check_if_ns_exists(
...     db_admin: AstraDBDatabaseAdmin, namespace: str
... ) -> bool:
...     ns_list = await db_admin.async_list_namespaces()
...     return namespace in ns_list
...
>>> asyncio.run(check_if_ns_exists(admin_for_my_db, "dragons"))
False
>>> asyncio.run(check_if_db_exists(admin_for_my_db, "app_namespace"))
True


Query the DevOps API for a list of the keyspaces in the database.
Async version of the method, for use in an asyncio context.

>>> async def check_if_ks_exists(
...     db_admin: AstraDBDatabaseAdmin, keyspace: str
... ) -> bool:
...     ks_list = await db_admin.async_list_keyspaces()
...     return keyspace in ks_list
...
>>> asyncio.run(check_if_ks_exists(admin_for_my_db, "dragons"))
False
>>> asyncio.run(check_if_db_exists(admin_for_my_db, "app_keyspace"))
True


Create a namespace in this database as requested,
optionally waiting for it to be ready.

*DEPRECATED* (removal in 2.0). Switch to the "keyspace" property.**

name

the namespace name. If supplying a namespace that exists
already, the method call proceeds as usual, no errors are
raised, and the whole invocation is a no-op.

if True (default), the method returns only after
the target database is in ACTIVE state again (a few
seconds, usually). If False, it will return right after issuing the
creation request to the DevOps API, and it will be responsibility
of the caller to check the database status/namespace availability
before working with it.

if True, the `Database` or `AsyncDatabase` class
that spawned this DatabaseAdmin, if any, gets updated to work on
the newly-created keyspace starting when this method returns.

an alias for update_db_keyspace.
*DEPRECATED* as of v1.5.0, removal in v2.0.0.

a timeout, in milliseconds, for the whole requested
operation to complete.
Note that a timeout is no guarantee that the creation request
has not reached the API server.

A dictionary of the form {"ok": 1} in case of success.

Otherwise, an exception is raised.

>>> my_db_admin.list_namespaces()
['default_keyspace']
>>> my_db_admin.create_namespace("that_other_one")
{'ok': 1}
>>> my_db_admin.list_namespaces()
['default_keyspace', 'that_other_one']


Create a keyspace in this database as requested,
optionally waiting for it to be ready.

the keyspace name. If supplying a keyspace that exists
already, the method call proceeds as usual, no errors are
raised, and the whole invocation is a no-op.

if True (default), the method returns only after
the target database is in ACTIVE state again (a few
seconds, usually). If False, it will return right after issuing the
creation request to the DevOps API, and it will be responsibility
of the caller to check the database status/keyspace availability
before working with it.

Otherwise, an exception is raised.

>>> my_db_admin.keyspaces()
['default_keyspace']
>>> my_db_admin.create_keyspace("that_other_one")
{'ok': 1}
>>> my_db_admin.list_keyspaces()
['default_keyspace', 'that_other_one']


Create a namespace in this database as requested,
optionally waiting for it to be ready.
Async version of the method, for use in an asyncio context.

*DEPRECATED* (removal in 2.0). Switch to the "async_create_keyspace" method.**

Otherwise, an exception is raised.

>>> asyncio.run(
...     my_db_admin.async_create_namespace("app_namespace")
... )
{'ok': 1}


Create a keyspace in this database as requested,
optionally waiting for it to be ready.
Async version of the method, for use in an asyncio context.

Otherwise, an exception is raised.

>>> asyncio.run(
...     my_db_admin.async_create_keyspace("app_keyspace")
... )
{'ok': 1}


Delete a namespace from the database, optionally waiting for the database
to become active again.

*DEPRECATED* (removal in 2.0). Switch to the "drop_keyspace" method.**

the namespace to delete. If it does not exist in this database,
an error is raised.

if True (default), the method returns only after
the target database is in ACTIVE state again (a few
seconds, usually). If False, it will return right after issuing the
deletion request to the DevOps API, and it will be responsibility
of the caller to check the database status/namespace availability
before working with it.

a timeout, in milliseconds, for the whole requested
operation to complete.
Note that a timeout is no guarantee that the deletion request
has not reached the API server.

Otherwise, an exception is raised.

>>> my_db_admin.list_namespaces()
['default_keyspace', 'that_other_one']
>>> my_db_admin.drop_namespace("that_other_one")
{'ok': 1}
>>> my_db_admin.list_namespaces()
['default_keyspace']


Delete a keyspace from the database, optionally waiting for the database
to become active again.

the keyspace to delete. If it does not exist in this database,
an error is raised.

if True (default), the method returns only after
the target database is in ACTIVE state again (a few
seconds, usually). If False, it will return right after issuing the
deletion request to the DevOps API, and it will be responsibility
of the caller to check the database status/keyspace availability
before working with it.

Otherwise, an exception is raised.

>>> my_db_admin.list_keyspaces()
['default_keyspace', 'that_other_one']
>>> my_db_admin.drop_keyspace("that_other_one")
{'ok': 1}
>>> my_db_admin.list_keyspaces()
['default_keyspace']


Delete a namespace from the database, optionally waiting for the database
to become active again.
Async version of the method, for use in an asyncio context.

*DEPRECATED* (removal in 2.0). Switch to the "async_drop_namespace" method.**

Otherwise, an exception is raised.

>>> asyncio.run(
...     my_db_admin.async_drop_namespace("app_namespace")
... )
{'ok': 1}


Delete a keyspace from the database, optionally waiting for the database
to become active again.
Async version of the method, for use in an asyncio context.

Otherwise, an exception is raised.

>>> asyncio.run(
...     my_db_admin.async_drop_keyspace("app_keyspace")
... )
{'ok': 1}


Drop this database, i.e. delete it completely and permanently with all its data.

This method wraps the `drop_database` method of the AstraDBAdmin class,
where more information may be found.

drop

if True (default), the method returns only after
the database has actually been deleted (generally a few minutes).
If False, it will return right after issuing the
drop request to the DevOps API, and it will be responsibility
of the caller to check the database status/availability
after that, if desired.

Otherwise, an exception is raised.

>>> my_db_admin.list_keyspaces()
['default_keyspace', 'that_other_one']
>>> my_db_admin.drop()
{'ok': 1}
>>> my_db_admin.list_keyspaces()  # raises a 404 Not Found http error

Once the method succeeds, methods on this object -- such as `info()`,
or `list_keyspaces()` -- can still be invoked: however, this hardly
makes sense as the underlying actual database is no more.
It is responsibility of the developer to design a correct flow
which avoids using a deceased database any further.


Drop this database, i.e. delete it completely and permanently with all its data.
Async version of the method, for use in an asyncio context.

This method wraps the `drop_database` method of the AstraDBAdmin class,
where more information may be found.

Otherwise, an exception is raised.

>>> asyncio.run(my_db_admin.async_drop())
{'ok': 1}


Create a Database instance from this database admin, for data-related tasks.

token

if supplied, is passed to the Database instead of
the one set for this object. Useful if one wants to work in
a least-privilege manner, limiting the permissions for non-admin work.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

keyspace

an optional keyspace to set in the resulting Database.
The same default logic as for `AstraDBAdmin.get_database` applies.

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

region

*This parameter is deprecated and should not be used.*
Ignored in the method.

path to append to the API Endpoint. In typical usage, this
should be left to its default of "/api/json".

version specifier to append to the API path. In typical
usage, this should be left to its default of "v1".

A Database object, ready to be used for working with data and collections.

>>> my_db = my_db_admin.get_database()
>>> my_db.list_collection_names()
['movies', 'another_collection']


Create an AsyncDatabase instance out of this class for working
with the data in it.

This method has identical behavior and signature as the sync
counterpart `get_database`: please see that one for more details.


Example (output abridged and indented for clarity):
    >>> admin_for_my_db.find_embedding_providers()
    FindEmbeddingProvidersResult(embedding_providers=..., openai, ...)
    >>> admin_for_my_db.find_embedding_providers().embedding_providers
    {
        'openai': EmbeddingProvider(
            display_name='OpenAI',
            models=[
                EmbeddingProviderModel(name='text-embedding-3-small'),
                ...
            ]
        ),
        ...
    }

a timeout, in milliseconds, for the DevOps API request.

A `FindEmbeddingProvidersResult` object with the complete information

returned by the API about available embedding providers


An "admin" object for non-Astra Data API environments, to perform administrative
tasks at the keyspaces level such as creating/listing/dropping keyspaces.

Conforming to the architecture of non-Astra deployments of the Data API,
this object works within the one existing database. It is within that database
that the keyspace CRUD operations (and possibly other admin operations)
are performed. Since non-Astra environment lack the concept of an overall
admin (such as the all-databases AstraDBAdmin class), a `DataAPIDatabaseAdmin`
is generally created by invoking the `get_database_admin` method of the
corresponding `Database` object (which in turn is spawned by a DataAPIClient).

DataAPIDatabaseAdmin

the full URI to access the Data API,
e.g. "http://localhost:8181".

token

an access token with enough permission to perform admin tasks.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

environment

a label, whose value is one of Environment.OTHER (default)
or other non-Astra environment values in the `Environment` enum.

path to append to the API Endpoint. In typical usage, this
class is created by a method such as `Database.get_database_admin()`,
which passes the matching value. Defaults to this portion of the path
being absent.

version specifier to append to the API path. In typical
usage, this class is created by a method such as
`Database.get_database_admin()`, which passes the matching value.
Defaults to this portion of the path being absent.

callers

a list of caller identities, i.e. applications, or frameworks,
on behalf of which Data API calls are performed. These end up in the
request user-agent.
Each caller identity is a ("caller_name", "caller_version") pair.

*DEPRECATED*, use `callers`. Removal 2.0. Name of the
application, or framework, on behalf of which the Data API calls
are performed. This ends up in the request user-agent.

version of the caller. *DEPRECATED*, use `callers`. Removal 2.0.

either a Database or an AsyncDatabase instance.
This represents the database class which spawns this admin object, so that,
if required, a keyspace creation can retroactively "use" the new keyspace
in the spawner. Used to enable the
Async/Database.get_admin_database().create_keyspace() pattern.

>>> from astrapy import DataAPIClient
>>> from astrapy.constants import Environment
>>> from astrapy.authentication import UsernamePasswordTokenProvider
>>>
>>> token_provider = UsernamePasswordTokenProvider("username", "password")
>>> endpoint = "http://localhost:8181"
>>>
>>> client = DataAPIClient(
>>>     token=token_provider,
>>>     environment=Environment.OTHER,
>>> )
>>> database = client.get_database(endpoint)
>>> admin_for_my_db = database.get_database_admin()
>>>
>>> admin_for_my_db.list_keyspaces()
['keyspace1', 'keyspace2']


environment

environment = environment or Environment.OTHER.lower()


api_path = api_path if api_path is not None else ''


api_version = api_version if api_version is not None else ''


Create a clone of this DataAPIDatabaseAdmin with some changed attributes.

version of the caller. *DEPRECATED*, use `callers`.
Removal 2.0.

a new DataAPIDatabaseAdmin instance.

>>> admin_for_my_other_db = admin_for_my_db.with_options(
...     api_endpoint="http://10.1.1.5:8181",
... )


Set a new identity for the application/framework on behalf of which
the DevOps API calls will be performed (the "caller").

New objects spawned from this client afterwards will inherit the new settings.

name of the application, or framework, on behalf of which
the DevOps API calls are performed. This ends up in the request user-agent.

version of the caller.

>>> admin_for_my_db.set_caller(
...     caller_name="the_caller",
...     caller_version="0.1.0",
... )


Query the API for a list of the namespaces in the database.

*DEPRECATED* (removal in 2.0). Switch to the "list_keyspaces" method.**

A list of the namespaces, each a string, in no particular order.

>>> admin_for_my_db.list_namespaces()
['default_keyspace', 'staging_namespace']


Query the API for a list of the keyspaces in the database.

A list of the keyspaces, each a string, in no particular order.

>>> admin_for_my_db.list_keyspaces()
['default_keyspace', 'staging_keyspace']


Create a namespace in the database, returning {'ok': 1} if successful.

*DEPRECATED* (removal in 2.0). Switch to the "create_keyspace" method.**

name

the namespace name. If supplying a namespace that exists
already, the method call proceeds as usual, no errors are
raised, and the whole invocation is a no-op.

this dictionary can specify the options about
replication of the namespace (across database nodes). If provided,
it must have a structure similar to:
`{"class": "SimpleStrategy", "replication_factor": 1}`.

if True, the `Database` or `AsyncDatabase` class
that spawned this DatabaseAdmin, if any, gets updated to work on
the newly-created keyspace starting when this method returns.

an alias for update_db_keyspace.
*DEPRECATED* as of v1.5.0, removal in v2.0.0.

a timeout, in milliseconds, for the whole requested
operation to complete.
Note that a timeout is no guarantee that the creation request
has not reached the API server.

A dictionary of the form {"ok": 1} in case of success.

Otherwise, an exception is raised.

>>> admin_for_my_db.list_namespaces()
['default_keyspace']
>>> admin_for_my_db.create_namespace("that_other_one")
{'ok': 1}
>>> admin_for_my_db.list_namespaces()
['default_keyspace', 'that_other_one']


Create a keyspace in the database, returning {'ok': 1} if successful.

the keyspace name. If supplying a keyspace that exists
already, the method call proceeds as usual, no errors are
raised, and the whole invocation is a no-op.

this dictionary can specify the options about
replication of the keyspace (across database nodes). If provided,
it must have a structure similar to:
`{"class": "SimpleStrategy", "replication_factor": 1}`.

Otherwise, an exception is raised.

>>> admin_for_my_db.list_keyspaces()
['default_keyspace']
>>> admin_for_my_db.create_keyspace("that_other_one")
{'ok': 1}
>>> admin_for_my_db.list_keyspaces()
['default_keyspace', 'that_other_one']


Drop (delete) a namespace from the database.

*DEPRECATED* (removal in 2.0). Switch to the "drop_namespace" method.**

the namespace to delete. If it does not exist in this database,
an error is raised.

a timeout, in milliseconds, for the whole requested
operation to complete.
Note that a timeout is no guarantee that the deletion request
has not reached the API server.

Otherwise, an exception is raised.

>>> admin_for_my_db.list_namespaces()
['default_keyspace', 'that_other_one']
>>> admin_for_my_db.drop_namespace("that_other_one")
{'ok': 1}
>>> admin_for_my_db.list_namespaces()
['default_keyspace']


Drop (delete) a keyspace from the database.

the keyspace to delete. If it does not exist in this database,
an error is raised.

Otherwise, an exception is raised.

>>> admin_for_my_db.list_keyspaces()
['default_keyspace', 'that_other_one']
>>> admin_for_my_db.drop_keyspace("that_other_one")
{'ok': 1}
>>> admin_for_my_db.list_keyspaces()
['default_keyspace']


Query the API for a list of the namespaces in the database.
Async version of the method, for use in an asyncio context.

*DEPRECATED* (removal in 2.0). Switch to the "async_list_keyspaces" method.**

a timeout, in milliseconds, for the DevOps API request.

>>> asyncio.run(admin_for_my_db.async_list_namespaces())
['default_keyspace', 'staging_namespace']


Query the API for a list of the keyspaces in the database.
Async version of the method, for use in an asyncio context.

>>> asyncio.run(admin_for_my_db.async_list_keyspaces())
['default_keyspace', 'staging_keyspace']


Create a namespace in the database, returning {'ok': 1} if successful.
Async version of the method, for use in an asyncio context.

*DEPRECATED* (removal in 2.0). Switch to the "async_create_keyspace" method.**

Otherwise, an exception is raised.

>>> admin_for_my_db.list_namespaces()
['default_keyspace']
>>> asyncio.run(admin_for_my_db.async_create_namespace(
...     "that_other_one"
... ))
{'ok': 1}
>>> admin_for_my_db.list_namespaces()
['default_keyspace', 'that_other_one']


Create a keyspace in the database, returning {'ok': 1} if successful.
Async version of the method, for use in an asyncio context.

Otherwise, an exception is raised.

>>> admin_for_my_db.list_keyspaces()
['default_keyspace']
>>> asyncio.run(admin_for_my_db.async_create_keyspace(
...     "that_other_one"
... ))
{'ok': 1}
>>> admin_for_my_db.list_leyspaces()
['default_keyspace', 'that_other_one']


Drop (delete) a namespace from the database.
Async version of the method, for use in an asyncio context.

*DEPRECATED* (removal in 2.0). Switch to the "async_drop_keyspace" method.**

Otherwise, an exception is raised.

>>> admin_for_my_db.list_namespaces()
['that_other_one', 'default_keyspace']
>>> asyncio.run(admin_for_my_db.async_drop_namespace(
...     "that_other_one"
... ))
{'ok': 1}
>>> admin_for_my_db.list_namespaces()
['default_keyspace']


Drop (delete) a keyspace from the database.
Async version of the method, for use in an asyncio context.

Otherwise, an exception is raised.

>>> admin_for_my_db.list_keyspaces()
['that_other_one', 'default_keyspace']
>>> asyncio.run(admin_for_my_db.async_drop_keyspace(
...     "that_other_one"
... ))
{'ok': 1}
>>> admin_for_my_db.list_keyspaces()
['default_keyspace']


Create a Database instance out of this class for working with the data in it.

token

if supplied, is passed to the Database instead of
the one set for this object. Useful if one wants to work in
a least-privilege manner, limiting the permissions for non-admin work.
This can be either a literal token string or a subclass of
`astrapy.authentication.TokenProvider`.

keyspace

an optional keyspace to set in the resulting Database.
If not provided, no keyspace is set, limiting what the Database
can do until setting it with e.g. a `use_keyspace` method call.

namespace

an alias for `keyspace`. *DEPRECATED*, removal in 2.0.

path to append to the API Endpoint. In typical usage, this
should be left to its default of "".

version specifier to append to the API path. In typical
usage, this should be left to its default of "v1".

A Database object, ready to be used for working with data and collections.

>>> my_db = admin_for_my_db.get_database()
>>> my_db.list_collection_names()
['movies', 'another_collection']

creating an instance of Database does not trigger actual creation
of the database itself, which should exist beforehand.


Create an AsyncDatabase instance for the database, to be used
when doing data-level work (such as creating/managing collections).

This method has identical behavior and signature as the sync
counterpart `get_database`: please see that one for more details.