Create a database in Azure Cosmos DB for NoSQL using Python
APPLIES TO: NoSQL
Databases in Azure Cosmos DB are units of management for one or more containers. Before you can create or manage containers, you must first create a database.
Name a database
In Azure Cosmos DB, a database is analogous to a namespace. When you create a database, the database name forms a segment of the URI used to access the database resource and any child resources.
Once created, the URI for a database is in this format:
https://<cosmos-account-name>.documents.azure.cn/dbs/<database-name>
Create a database
To create a database, call one of the following methods:
Create a database
The following example creates a database with the CosmosClient.create_database
method. This method throws an exception if a database with the same name exists.
"""Sample showing how to connect with endpoint and key."""
import os
from azure.cosmos import CosmosClient
from azure.cosmos.exceptions import CosmosResourceExistsError
DATABASE_ID = "cosmicworks-1"
CONTAINER_ID = "products"
ENDPOINT = os.environ["COSMOS_ENDPOINT"]
KEY = os.environ["COSMOS_KEY"]
client = CosmosClient(url=ENDPOINT, credential=KEY)
def main():
"""How to CosmosDB and NoSQL samples."""
# <create_database>
try:
database = client.create_database(id=DATABASE_ID)
print(f"Database created: {database.id}")
except CosmosResourceExistsError:
print("Database already exists.")
# </create_database>
if __name__ == "__main__":
main()
Create a database if it doesn't already exist
The following example creates a database with the CosmosClient.create_database_if_not_exists
method. If the database exists, this method returns the database settings. Compared to the previous create method, this method doesn't throw an exception if the database already exists. This method is useful for avoiding errors if you run the same code multiple times.
"""Sample showing how to connect with endpoint and key."""
import os
from azure.cosmos import CosmosClient
from azure.cosmos.exceptions import CosmosHttpResponseError
DATABASE_ID = "cosmicworks-1"
CONTAINER_ID = "products"
ENDPOINT = os.environ["COSMOS_ENDPOINT"]
KEY = os.environ["COSMOS_KEY"]
client = CosmosClient(url=ENDPOINT, credential=KEY)
def main():
"""How to CosmosDB and NoSQL samples."""
# <create_database>
try:
database = client.create_database_if_not_exists(id=DATABASE_ID)
print(f"Database created or returned: {database.id}")
except CosmosHttpResponseError:
print("Request to the Azure Cosmos database service failed.")
# </create_database>
try:
# <parse_response>
database = client.create_database_if_not_exists(id=DATABASE_ID)
for container in database.list_containers():
print(f'Container name: {container["id"]}')
# </parse_response>
except CosmosHttpResponseError:
print("Request to the Azure Cosmos database service failed.")
if __name__ == "__main__":
main()
Create a database asynchronously
You can also create a database asynchronously using similar object and methods in the azure.cosmos.aio namespace. For example, use the CosmosClient.create_database
method or the 'CosmoClient.create_database_if_not_exists method.
Working asynchronously is useful when you want to perform multiple operations in parallel. For more information, see Using the asynchronous client.
Parsing the response
In the examples above, the response from the requests is a DatabaseProxy
, which is an interface to interact with a specific database. From the proxy, you can access methods to perform operations on the database.
The following example shows the create_database_if_not_exists method returning a database object.
"""Sample showing how to connect with endpoint and key."""
import os
from azure.cosmos import CosmosClient
from azure.cosmos.exceptions import CosmosHttpResponseError
DATABASE_ID = "cosmicworks-1"
CONTAINER_ID = "products"
ENDPOINT = os.environ["COSMOS_ENDPOINT"]
KEY = os.environ["COSMOS_KEY"]
client = CosmosClient(url=ENDPOINT, credential=KEY)
def main():
"""How to CosmosDB and NoSQL samples."""
# <create_database>
try:
database = client.create_database_if_not_exists(id=DATABASE_ID)
print(f"Database created or returned: {database.id}")
except CosmosHttpResponseError:
print("Request to the Azure Cosmos database service failed.")
# </create_database>
try:
# <parse_response>
database = client.create_database_if_not_exists(id=DATABASE_ID)
for container in database.list_containers():
print(f'Container name: {container["id"]}')
# </parse_response>
except CosmosHttpResponseError:
print("Request to the Azure Cosmos database service failed.")
if __name__ == "__main__":
main()
Next steps
Now that you've created a database, use the next guide to create containers.