Modifica

Condividi tramite


Quickstart: Azure Cosmos DB for Apache Cassandra client library for Java

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.
  • 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.

  1. 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>"
    
  2. 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"
    
  3. Create a new keyspace using az cosmosdb cassandra keyspace create named cosmicworks.

    az cosmosdb cassandra keyspace create \
        --resource-group "<resource-group-name>" \
        --account-name "<account-name>" \
        --name "cosmicworks"
    
  4. 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 named products.

    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.

  1. 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}"
    
  2. Record the value of the contactPoint and username 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.

  3. 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"
    
  4. 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.

  1. Start in an empty directory.

  2. Generate a new Java console project using Maven.

    mvn archetype:generate -DgroupId=quickstart -DartifactId=console -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    
  3. 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>
    
  4. Open the /console/src/main/java/quickstart/App.java file.

  5. Observe the existing Java application boilerplate.

    package quickstart;
    
    /**
     * Hello world!
     *
     */
    public class App 
    {
        public static void main( String[] args )
        {
            System.out.println( "Hello World!" );
        }
    }
    
  6. 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)
        {
        }
    }
    
  7. Import the java.security.NoSuchAlgorithmException namespace.

    import java.security.NoSuchAlgorithmException;
    
  8. Update the main method signature to indicate that it could throw the NoSuchAlgorithmException 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.

  9. 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.

  1. Open the /console/src/main/java/quickstart/App.java file in your integrated development environment (IDE).

  2. 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;
    
  3. Create string variables for the credentials collected earlier in this guide. Name the variables username, password, and contactPoint. Also create a string variable named region for the local data center.

    String username = "<username>";
    String password = "<password>";
    String contactPoint = "<contact-point>";
    
  4. 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>";
    
  5. Create an SSLContext object to ensure that you're using the transport layer security (TLS) protocol.

    SSLContext sslContext = SSLContext.getDefault();
    
  6. 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.

  1. 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.

  2. Create a new object of type Product. Store the object in a variable named product.

    Product product = new Product(
        "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
        "Yamba Surfboard",
        "gear-surf-surfboards",
        12,
        false
    );
    
  3. 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 (?, ?, ?, ?, ?)";
    
  4. 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
    );
    
  5. Upsert the product by executing the bound statement.

    session.execute(boundInsert);
    

Read data

Then, read data that was previously upserted into the table.

  1. Create a new string variable named readQuery with a CQL query that matches items with the same id field.

    String readQuery = "SELECT * FROM product WHERE id = ? LIMIT 1";
    
  2. 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";
    
  3. Prepare the statement and bind the product's id field as a parameter.

    PreparedStatement readStmt = session.prepare(readQuery);
    BoundStatement boundRead = readStmt.bind(id);
    
  4. Execute the bound statement and store the result in a variable named readResult.

    ResultSet readResult = session.execute(boundRead);
    
  5. 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.

  1. Create a new string variable named findQuery with a CQL query that matches items with the same category field.

    String findQuery = "SELECT * FROM product WHERE category = ? ALLOW FILTERING";
    
  2. Create a string variable named id with the same value as the product created earlier in this guide.

    String category = "gear-surf-surfboards";
    
  3. Prepare the statement and bind the product category as a parameter.

    PreparedStatement findStmt = session.prepare(findQuery);
    BoundStatement boundFind = findStmt.bind(category);
    
  4. Execute the bound statement and store the result in a variable named findResults.

    ResultSet results = session.execute(boundFind);
    
  5. 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.

  1. 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}"
    
  2. Record the value of the contactPoint and username 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.

  3. 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"
    
  4. 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.

Next step