Quickstart: Build a Java app to manage Azure Cosmos DB Cassandra API data (v4 Driver)

In this quickstart, you create an Azure Cosmos DB Cassandra API account, and use a Cassandra Java app cloned from GitHub to create a Cassandra database and container using the v4.x Apache Cassandra drivers for Java. Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with global distribution and horizontal scale capabilities.

Prerequisites

Create a database account

Before you can create a document database, you need to create a Cassandra account with Azure Cosmos DB.

  1. In a new browser window, sign in to the Azure portal.

  2. In the left menu, select Create a resource.

    Create a resource in the Azure portal

  3. On the New page, select Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  4. On the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    Setting Value Description
    Subscription Your subscription Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource Group Create new

    Then enter the same name as Account Name
    Select Create new. Then enter a new resource group name for your account. For simplicity, use the same name as your Azure Cosmos account name.
    Account Name Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Your account URI will be cassandra.cosmos.azure.com appended to your unique account name.

    The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    API Cassandra The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. You must create a separate account for each API.

    Select Cassandra, because in this quickstart you are creating a table that works with the Cassandra API.

    Learn more about the Cassandra API.
    Location Select the region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.

    Select Review+Create. You can skip the Network and Tags section.

    The new account page for Azure Cosmos DB

  5. The account creation takes a few minutes. Wait for the portal to display the page saying Congratulations! Your Azure Cosmos DB account was created.

Clone the sample application

Now let's switch to working with code. Let's clone a Cassandra app from GitHub, set the connection string, and run it. You'll see how easy it is to work with data programmatically.

  1. Open a command prompt. Create a new folder named git-samples. Then, close the command prompt.

    md "C:\git-samples"
    
  2. Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
    
  3. Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-cassandra-java-getting-started-v4.git
    

Review the code

This step is optional. If you're interested to learn how the code creates the database resources, you can review the following snippets. Otherwise, you can skip ahead to Update your connection string. These snippets are all taken from the src/main/java/com/azure/cosmosdb/cassandra/util/CassandraUtils.java file.

  • The CqlSession connects to the Azure Cosmos DB Cassandra API and returns a session to access (Cluster object from v3 driver is now obsolete). Cassandra Host, Port, User name and password is set using the connection string page in the Azure portal.

        this.session = CqlSession.builder().withSslContext(sc)
                .addContactPoint(new InetSocketAddress(cassandraHost, cassandraPort)).withLocalDatacenter(region)
                .withAuthCredentials(cassandraUsername, cassandraPassword).build();
    

The following snippets are from the src/main/java/com/azure/cosmosdb/cassandra/repository/UserRepository.java file.

  • Drop the keyspace if it already exists from a previous run.

    public void dropKeyspace() {
        String query = "DROP KEYSPACE IF EXISTS "+keyspace+"";
        session.execute(query);
        LOGGER.info("dropped keyspace '"+keyspace+"'");
    } 
    
  • A new keyspace is created.

    public void createKeyspace() {
        String query = "CREATE KEYSPACE "+keyspace+" WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 }";
        session.execute(query);
        LOGGER.info("Created keyspace '"+keyspace+"'");
    }
    
  • A new table is created.

      public void createTable() {
          String query = "CREATE TABLE "+keyspace+"."+table+" (user_id int PRIMARY KEY, user_name text, user_bcity text)";
          session.execute(query);
          LOGGER.info("Created table '"+table+"'");
      }
    
  • User entities are inserted using a prepared statement object.

    public String prepareInsertStatement() {
        final String insertStatement = "INSERT INTO  "+keyspace+"."+table+" (user_id, user_name , user_bcity) VALUES (?,?,?)";
        return insertStatement;
    }
    
    public void insertUser(String preparedStatement, int id, String name, String city) {
        PreparedStatement prepared = session.prepare(preparedStatement);
        BoundStatement bound = prepared.bind(id, city, name).setIdempotent(true);
        session.execute(bound);
    }
    
  • Query to get get all User information.

    public void selectAllUsers() {
        final String query = "SELECT * FROM "+keyspace+"."+table+"";
        List<Row> rows = session.execute(query).all();
    
        for (Row row : rows) {
            LOGGER.info("Obtained row: {} | {} | {} ", row.getInt("user_id"), row.getString("user_name"), row.getString("user_bcity"));
        }
    }
    
  • Query to get a single User information.

    public void selectUser(int id) {
        final String query = "SELECT * FROM "+keyspace+"."+table+" where user_id = 3";
        Row row = session.execute(query).one();
    
        LOGGER.info("Obtained row: {} | {} | {} ", row.getInt("user_id"), row.getString("user_name"), row.getString("user_bcity"));
    }
    

Update your connection string

Now go back to the Azure portal to get your connection string information and copy it into the app. The connection string details enable your app to communicate with your hosted database.

  1. In your Azure Cosmos DB account in the Azure portal, select Connection String.

    View and copy a username from the Azure portal, Connection String page

  2. Use the button on the right side of the screen to copy the CONTACT POINT value.

  3. Open the config.properties file from the C:\git-samples\azure-cosmosdb-cassandra-java-getting-started\java-examples\src\main\resources folder.

  4. Paste the CONTACT POINT value from the portal over <Cassandra endpoint host> on line 2.

    Line 2 of config.properties should now look similar to

    cassandra_host=cosmos-db-quickstart.cassandra.cosmosdb.azure.com

  5. Go back to the portal and copy the USERNAME value. Past the USERNAME value from the portal over <cassandra endpoint username> on line 4.

    Line 4 of config.properties should now look similar to

    cassandra_username=cosmos-db-quickstart

  6. Go back to the portal and copy the PASSWORD value. Paste the PASSWORD value from the portal over <cassandra endpoint password> on line 5.

    Line 5 of config.properties should now look similar to

    cassandra_password=2Ggkr662ifxz2Mg...==

  7. On line 6, if you want to use a specific TLS/SSL certificate, then replace <SSL key store file location> with the location of the TLS/SSL certificate. If a value is not provided, the JDK certificate installed at <JAVA_HOME>/jre/lib/security/cacerts is used.

  8. If you changed line 6 to use a specific TLS/SSL certificate, update line 7 to use the password for that certificate.

  9. Note that you will need to add the default region (e.g. West US) for the contact point, e.g.

    region=West US

    This is because the v.4x driver only allows one local DC to be paired with the contact point. If you want to add a region other than the default (which is the region that was given when the Cosmos DB account was first created), you will need to use regional suffix when adding contact point, e.g. host-westus.cassandra.cosmos.azure.com.

  10. Save the config.properties file.

Run the Java app

  1. In the git terminal window, cd to the azure-cosmosdb-cassandra-java-getting-started-v4 folder.

    cd "C:\git-samples\azure-cosmosdb-cassandra-java-getting-started-v4"
    
  2. In the git terminal window, use the following command to generate the cosmosdb-cassandra-examples.jar file.

    mvn clean install
    
  3. In the git terminal window, run the following command to start the Java application.

    java -cp target/cosmosdb-cassandra-examples.jar com.azure.cosmosdb.cassandra.examples.UserProfile
    

    The terminal window displays notifications that the keyspace and table are created. It then selects and returns all users in the table and displays the output, and then selects a row by ID and displays the value.

    Press Ctrl+C to stop execution of the program and close the console window.

  4. In the Azure portal, open Data Explorer to query, modify, and work with this new data.

    View the data in Data Explorer - Azure Cosmos DB

Review SLAs in the Azure portal

The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. This suite of metrics makes monitoring your SLAs transparent.

To review metrics and SLAs:

  1. Select Metrics in your Cosmos DB account's navigation menu.

  2. Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB metrics suite

  3. Review the metrics on the other tabs.

Clean up resources

When you're done with your app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. To delete the resources:

  1. In the Azure portal Search bar, search for and select Resource groups.

  2. From the list, select the resource group you created for this quickstart.

    Select the resource group to delete

  3. On the resource group Overview page, select Delete resource group.

    Delete the resource group

  4. In the next window, enter the name of the resource group to delete, and then select Delete.

Next steps

In this quickstart, you learned how to create an Azure Cosmos DB account with Cassandra API, and run a Cassandra Java app that creates a Cassandra database and container. You can now import additional data into your Azure Cosmos DB account.