Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Get started with the Azure Cosmos DB for Apache Cassandra client library for Python to store, manage, and query unstructured data. Follow the steps in this guide to create a new account, install a Python client library, connect to the account, perform common operations, and query your final sample data.
API reference documentation | Library source code | Package (PyPI)
Prerequisites
An Azure subscription
- If you don't have an Azure subscription, create a free account before you begin.
The latest version of the Azure CLI in Azure Cloud Shell.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
az logincommand.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
- Python 3.12 or later
Setting up
First, set up the account and development environment for this guide. This section walks you through the process of creating an account, getting its credentials, and then preparing your development environment.
Create an account
Start by creating an API for Apache Cassandra account. Once the account is created, create the keyspace and table resources.
If you don't already have a target resource group, use the
az group createcommand to create a new resource group in your subscription.az group create \ --name "<resource-group-name>" \ --location "<location>"Use the
az cosmosdb createcommand to create a new Azure Cosmos DB for Apache Cassandra account with default settings.az cosmosdb create \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --locations "regionName=<location>" \ --capabilities "EnableCassandra"Create a new keyspace using
az cosmosdb cassandra keyspace createnamedcosmicworks.az cosmosdb cassandra keyspace create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --name "cosmicworks"Create a new JSON object to represent your schema using a multi-line Bash command. Then, use the
az cosmosdb cassandra table createcommand to create a new table namedproducts.schemaJson=$(cat <<EOF { "columns": [ { "name": "id", "type": "text" }, { "name": "name", "type": "text" }, { "name": "category", "type": "text" }, { "name": "quantity", "type": "int" }, { "name": "price", "type": "decimal" }, { "name": "clearance", "type": "boolean" } ], "partitionKeys": [ { "name": "id" } ] } EOF )az cosmosdb cassandra table create \ --resource-group "<resource-group-name>" \ --account-name "<account-name>" \ --keyspace-name "cosmicworks" \ --name "product" \ --schema "$schemaJson"
Get credentials
Now, get the password for the client library to use to create a connection to the recently created account.
Use
az cosmosdb showto get the contact point and username for the account.az cosmosdb show \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --query "{username:name,contactPoint:documentEndpoint}"Record the value of the
contactPointandusernameproperties from the previous commands' output. These properties' values are the contact point and username you use later in this guide to connect to the account with the library.Use
az cosmosdb keys listto get the keys for the account.az cosmosdb keys list \ --resource-group "<resource-group-name>" \ --name "<account-name>" \ --type "keys"Record the value of the
primaryMasterKeyproperty from the previous commands' output. This property's value is the password you use later in this guide to connect to the account with the library.
Prepare development environment
Then, configure your development environment with a new project and the client library. This step is the last required prerequisite before moving on to the rest of this guide.
Start in an empty directory.
Import the
cassandra-driverpackage from the Python Package Index (PyPI).pip install cassandra-driverCreate the app.py file.
Object model
| Description | |
|---|---|
Cluster |
Represents a specific connection to a cluster |
Code examples
Authenticate client
Start by authenticating the client using the credentials gathered earlier in this guide.
Open the app.py file in your integrated development environment (IDE).
Import the following types from the
cassandra-drivermodule:cassandra.cluster.Clustercassandra.auth.PlainTextAuthProvider
from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProviderImport the following types from the
sslmodule:ssl.PROTOCOL_TLS_CLIENTssl.SSLContextssl.CERT_NONE
from ssl import PROTOCOL_TLS_CLIENT, SSLContext, CERT_NONECreate string variables for the credentials collected earlier in this guide. Name the variables
username,password, andcontactPoint.username = "<username>" password = "<password>" contactPoint = "<contact-point>"Configure the
SSLContextby creating a new variable namedssl_context, setting the protocol toPROTOCOL_TLS_CLIENT, disabling the hostname check, and setting the verification mode toCERT_NONE.ssl_context = SSLContext(PROTOCOL_TLS_CLIENT) ssl_context.check_hostname = False ssl_context.verify_mode = CERT_NONECreate a new
PlainTextAuthProviderobject with the credentials specified in the previous steps. Store the result in a variable namedauth_provider.auth_provider = PlainTextAuthProvider(username=username, password=password)Create a
Clusterobject using the credential and configuration variables created in the previous steps. Store the result in a variable namedcluster.cluster = Cluster([contactPoint], port=10350, auth_provider=auth_provider, ssl_context=ssl_context)Connect to the cluster.
session = cluster.connect("cosmicworks")
Warning
Complete transport layer security (TLS) validation is disabled in this guide to simplify authentication. For production deployments, fully enable validation.
Upsert data
Next, upsert new data into a table. Upserting ensures that the data is created or replaced appropriately depending on whether the same data already exists in the table.
Create a new string variable named
insertQuerywith the Cassandra Query Language (CQL) query for inserting a new row.insertQuery = """ INSERT INTO product (id, name, category, quantity, price, clearance) VALUES (%(id)s, %(name)s, %(category)s, %(quantity)s, %(price)s, %(clearance)s) """Create a new object with various properties of a new product and store it in a variable named
params.params = { "id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb", "name": "Yamba Surfboard", "category": "gear-surf-surfboards", "quantity": 12, "price": 850.00, "clearance": False }Use the
executefunction to run the query with the specified parameters.session.execute(insertQuery, params)
Read data
Then, read data that was previously upserted into the table.
Create a new string variable named
readQuerywith a CQL query that matches items with the sameidfield.readQuery = "SELECT * FROM product WHERE id = %s LIMIT 1"Create a string variable named
idwith the same value as the product created earlier in this guide.id = "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"Use the
executefunction to run the query stored inreadQuerypassing in theidvariable as an argument. Store the result in a variable namedreadResults.readResults = session.execute(readQuery, (id,))Use the
onefunction get the expected single result. Store this single result in a variable namedmatchedProduct.matchedProduct = readResults.one()
Query data
Finally, use a query to find all data that matches a specific filter in the table.
Create string variables named
findQueryandcategorywith the CQL query and required parameter.findQuery = "SELECT * FROM product WHERE category = %s ALLOW FILTERING" category = "gear-surf-surfboards"Use the two string variables and the
executefunction to query multiple results. Store the result of this query in a variable namedfindResults.findResults = session.execute(findQuery, (category,))Use a
forloop to iterate over the query results.for row in findResults: # Do something here with each result
Run the code
Run the newly created application using a terminal in your application directory.
python app.py
Clean up resources
When you no longer need the account, remove the account from your Azure subscription by deleting the resource.
az cosmosdb delete \
--resource-group "<resource-group-name>" \
--name "<account-name>"