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 Java to store, manage, and query unstructured data. Follow the steps in this guide to create a new account, install a Java client library, connect to the account, perform common operations, and query your final sample data.
API reference documentation | Library source code | Package (Maven)
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 login
command.
- If you prefer to run CLI reference commands locally, sign in to the Azure CLI by using the
- Java 21 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 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"
Get credentials
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.
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.
Generate a new Java console project using Maven.
mvn archetype:generate -DgroupId=quickstart -DartifactId=console -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Import the
java-driver-core
package from Maven. Add this section to your pom.xml file.<dependency> <groupId>org.apache.cassandra</groupId> <artifactId>java-driver-core</artifactId> <version>[4.,)</version> </dependency>
Open the /console/src/main/java/quickstart/App.java file.
Observe the existing Java application boilerplate.
package quickstart; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
Remove the comments and console output from the boilerplate. This code block is the starting point for the remainder of this guide.
package quickstart; public class App { public static void main(String[] args) { } }
Import the
java.security.NoSuchAlgorithmException
namespace.import java.security.NoSuchAlgorithmException;
Update the
main
method signature to indicate that it could throw theNoSuchAlgorithmException
exception.public static void main(String[] args) throws NoSuchAlgorithmException { }
Important
The remaining steps within this guide assume that you're adding your code within the
main
method.Build the project.
mvn compile
Object model
Description | |
---|---|
CqlSession |
Represents a specific connection to a cluster |
PreparedStatement |
Represents a precompiled CQL statement that can be executed multiple times efficiently |
BoundStatement |
Represents a prepared statement with bound parameters |
Row |
Represents a single row of a query result |
Code examples
Authenticate client
Start by authenticating the client using the credentials gathered earlier in this guide.
Open the /console/src/main/java/quickstart/App.java file in your integrated development environment (IDE).
Import the following types:
java.net.InetSocketAddress
javax.net.ssl.SSLContext
com.datastax.oss.driver.api.core.CqlIdentifier
com.datastax.oss.driver.api.core.CqlSession
com.datastax.oss.driver.api.core.cql.BoundStatement
com.datastax.oss.driver.api.core.cql.PreparedStatement
com.datastax.oss.driver.api.core.cql.ResultSet
com.datastax.oss.driver.api.core.cql.Row
import java.net.InetSocketAddress; import javax.net.ssl.SSLContext; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.cql.BoundStatement; import com.datastax.oss.driver.api.core.cql.PreparedStatement; import com.datastax.oss.driver.api.core.cql.ResultSet; import com.datastax.oss.driver.api.core.cql.Row;
Create string variables for the credentials collected earlier in this guide. Name the variables
username
,password
, andcontactPoint
. Also create a string variable namedregion
for the local data center.String username = "<username>"; String password = "<password>"; String contactPoint = "<contact-point>";
Create another string variable for the region where you created your Azure Cosmos DB for Apache Cassandra account. Name this variable
region
.String region = "<region>";
Create an
SSLContext
object to ensure that you're using the transport layer security (TLS) protocol.SSLContext sslContext = SSLContext.getDefault();
Create a new
CqlSession
object using the credential and configuration variables created in the previous steps. Set the contact point, local data center, authentication credentials, keyspace, and Transport Layer Security (TLS) context.CqlSession session = CqlSession.builder() .addContactPoint(new InetSocketAddress(contactPoint, 10350)) .withLocalDatacenter(region) .withAuthCredentials(username, password) .withKeyspace(CqlIdentifier.fromCql("cosmicworks")) .withSslContext(sslContext) .build();
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.
Define a new class named
Product
with fields corresponding to the table created earlier in this guide.class Product { public String id; public String name; public String category; public int quantity; public boolean clearance; public Product(String id, String name, String category, int quantity, boolean clearance) { this.id = id; this.name = name; this.category = category; this.quantity = quantity; this.clearance = clearance; } @Override public String toString() { return String.format("Product{id='%s', name='%s', category='%s', quantity=%d, clearance=%b}", id, name, category, quantity, clearance); } }
Tip
In Java, you can create this type in another file or create it at the end of the existing file.
Create a new object of type
Product
. Store the object in a variable namedproduct
.Product product = new Product( "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb", "Yamba Surfboard", "gear-surf-surfboards", 12, false );
Create a new string variable named
insertQuery
with the Cassandra Query Language (CQL) query for inserting a new row.String insertQuery = "INSERT INTO product (id, name, category, quantity, clearance) VALUES (?, ?, ?, ?, ?)";
Prepare the insert statement and bind the product properties as parameters.
PreparedStatement insertStmt = session.prepare(insertQuery); BoundStatement boundInsert = insertStmt.bind( product.id, product.name, product.category, product.quantity, product.clearance );
Upsert the product by executing the bound statement.
session.execute(boundInsert);
Read data
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.String readQuery = "SELECT * FROM product WHERE id = ? LIMIT 1";
Create a string variable named
id
with the same value as the product created earlier in this guide.String id = "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb";
Prepare the statement and bind the product's
id
field as a parameter.PreparedStatement readStmt = session.prepare(readQuery); BoundStatement boundRead = readStmt.bind(id);
Execute the bound statement and store the result in a variable named
readResult
.ResultSet readResult = session.execute(boundRead);
Retrieve the first row from the result set and map it to a
Product
object if found.Row row = readResult.one(); Product matchedProduct = new Product( row.getString("id"), row.getString("name"), row.getString("category"), row.getInt("quantity"), row.getBoolean("clearance") );
Query data
Now, use a query to find all data that matches a specific filter in the table.
Create a new string variable named
findQuery
with a CQL query that matches items with the samecategory
field.String findQuery = "SELECT * FROM product WHERE category = ? ALLOW FILTERING";
Create a string variable named
id
with the same value as the product created earlier in this guide.String category = "gear-surf-surfboards";
Prepare the statement and bind the product category as a parameter.
PreparedStatement findStmt = session.prepare(findQuery); BoundStatement boundFind = findStmt.bind(category);
Execute the bound statement and store the result in a variable named
findResults
.ResultSet results = session.execute(boundFind);
Iterate over the query results and map each row to a
Product
object.for (Row result : results) { Product queriedProduct = new Product( result.getString("id"), result.getString("name"), result.getString("category"), result.getInt("quantity"), result.getBoolean("clearance") ); // Do something here with each result }
Close session
In Java, you're required to close the session after you're done with any queries and operations.
session.close();
Run the code
Run the newly created application using a terminal in your application directory.
mvn compile
mvn exec:java -Dexec.mainClass="quickstart.App"
Tip
Ensure that you're running this command within the /console path created within this guide.
Clean up resources
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.