Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
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)
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 login
command.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
- Python 3.12 or later
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.
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 create
command to create a new resource group in your subscription.az group create \ --name "<resource-group-name>" \ --location "<location>"
Use the
az cosmosdb create
command 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 create
namedcosmicworks
.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 create
command 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"
Now, get the password for the client library to use to create a connection to the recently created account.
Use
az cosmosdb show
to 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
contactPoint
andusername
properties 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 list
to 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
primaryMasterKey
property 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.
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-driver
package from the Python Package Index (PyPI).pip install cassandra-driver
Create the app.py file.
Description | |
---|---|
Cluster |
Represents a specific connection to a cluster |
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-driver
module:cassandra.cluster.Cluster
cassandra.auth.PlainTextAuthProvider
from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider
Import the following types from the
ssl
module:ssl.PROTOCOL_TLS_CLIENT
ssl.SSLContext
ssl.CERT_NONE
from ssl import PROTOCOL_TLS_CLIENT, SSLContext, CERT_NONE
Create 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
SSLContext
by 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_NONE
Create a new
PlainTextAuthProvider
object 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
Cluster
object 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")
Avviso
Complete transport layer security (TLS) validation is disabled in this guide to simplify authentication. For production deployments, fully enable validation.
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
insertQuery
with 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
execute
function to run the query with the specified parameters.session.execute(insertQuery, params)
Then, read data that was previously upserted into the table.
Create a new string variable named
readQuery
with a CQL query that matches items with the sameid
field.readQuery = "SELECT * FROM product WHERE id = %s LIMIT 1"
Create a string variable named
id
with the same value as the product created earlier in this guide.id = "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"
Use the
execute
function to run the query stored inreadQuery
passing in theid
variable as an argument. Store the result in a variable namedreadResults
.readResults = session.execute(readQuery, (id,))
Use the
one
function get the expected single result. Store this single result in a variable namedmatchedProduct
.matchedProduct = readResults.one()
Finally, use a query to find all data that matches a specific filter in the table.
Create string variables named
findQuery
andcategory
with 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
execute
function to query multiple results. Store the result of this query in a variable namedfindResults
.findResults = session.execute(findQuery, (category,))
Use a
for
loop to iterate over the query results.for row in findResults: # Do something here with each result
Run the newly created application using a terminal in your application directory.
python app.py
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>"