Tutorial: Create a API for Cassandra account in Azure Cosmos DB by using a Java application to store key/value data

APPLIES TO: Cassandra

As a developer, you might have applications that use key/value pairs. You can use a API for Cassandra account in Azure Cosmos DB to store the key/value data. This tutorial describes how to use a Java application to create a API for Cassandra account in Azure Cosmos DB, add a database (also called a keyspace), and add a table. The Java application uses the Java driver to create a user database that contains details such as user ID, user name, and user city.

This tutorial covers the following tasks:

  • Create a Cassandra database account
  • Get the account connection string
  • Create a Maven project and dependencies
  • Add a database and a table
  • Run the app

Prerequisites

Create a database account

  1. From the Azure portal menu or the Home page, select Create a resource.

  2. On the New page, search for and select Azure Cosmos DB.

  3. On the Azure Cosmos DB page, select Create.

  4. On the API page, select Create under the Cassandra section.

    The API determines the type of account to create. Azure Cosmos DB provides five APIs: NoSQL 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 API for Cassandra.

    Learn more about the API for Cassandra.

  5. In the Create Azure Cosmos DB Account page, enter the basic 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 DB 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.cn 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: NoSQL 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 API for Cassandra.

    Learn more about the API for Cassandra.
    Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is closest to your users to give them the fastest access to the data.
    Capacity mode Provisioned throughput or Serverless Select Provisioned throughput to create an account in provisioned throughput mode. Select Serverless to create an account in serverless mode.
    Apply Azure Cosmos DB free tier discount Apply or Do not apply With Azure Cosmos DB free tier, you will get the first 1000 RU/s and 25 GB of storage for free in an account. Learn more about free tier.

    Note

    You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    The new account page for Azure Cosmos DB for Apache Cassandra

  6. In the Global Distribution tab, configure the following details. You can leave the default values for the purpose of this quickstart:

    Setting Value Description
    Geo-Redundancy Disable Enable or disable multiple-region distribution on your account by pairing your region with a pair region. You can add more regions to your account later.
    Multi-region Writes Disable Multi-region writes capability allows you to take advantage of the provisioned throughput for your databases and containers across China.
    Availability Zones Disable Availability Zones are isolated locations within an Azure region. Each zone is made up of one or more datacenters equipped with independent power, cooling, and networking.

    Note

    The following options are not available if you select Serverless as the Capacity mode:

    • Apply Free Tier Discount
    • Geo-redundancy
    • Multi-region Writes
  7. Optionally you can configure additional details in the following tabs:

    • Networking - Configure access from a virtual network.
    • Backup Policy - Configure either periodic or continuous backup policy.
    • Encryption - Use either service-managed key or a customer-managed key.
    • Tags - Tags are name/value pairs that enable you to categorize resources and view consolidated billing by applying the same tag to multiple resources and resource groups.
  8. Select Review + create.

  9. Review the account settings, and then select Create. It takes a few minutes to create the account. Wait for the portal page to display Your deployment is complete.

    The Azure portal Notifications pane

  10. Select Go to resource to go to the Azure Cosmos DB account page.

Get the connection details of your account

Get the connection string information from the Azure portal, and copy it into the Java configuration file. The connection string enables your app to communicate with your hosted database.

  1. From the Azure portal, go to your Azure Cosmos DB account.

  2. Open the Connection String pane.

  3. Copy the CONTACT POINT, PORT, USERNAME, and PRIMARY PASSWORD values to use in the next steps.

Create the project and the dependencies

The Java sample project that you use in this article is hosted in GitHub. You can run the steps in this doc or download the sample from the azure-cosmos-db-cassandra-java-getting-started repository.

After you download the files, update the connection string information within the java-examples\src\main\resources\config.properties file and run it.

cassandra_host=<FILLME_with_CONTACT POINT> 
cassandra_port = 10350 
cassandra_username=<FILLME_with_USERNAME> 
cassandra_password=<FILLME_with_PRIMARY PASSWORD> 

Use the following steps to build the sample from scratch:

  1. From the terminal or command prompt, create a new Maven project called Cassandra-demo.

    mvn archetype:generate -DgroupId=com.azure.cosmosdb.cassandra -DartifactId=cassandra-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 
    
  2. Locate the cassandra-demo folder. Using a text editor, open the pom.xml file that was generated.

    Add the Cassandra dependencies and build plugins required by your project, as shown in the pom.xml file.

  3. Under the cassandra-demo\src\main folder, create a new folder named resources. Under the resources folder, add the config.properties and log4j.properties files:

    • The config.properties file stores the connection endpoint and key values of the API for Cassandra account.

    • The log4j.properties file defines the level of logging required for interacting with the API for Cassandra.

  4. Browse to the src/main/java/com/azure/cosmosdb/cassandra/ folder. Within the cassandra folder, create another folder named utils. The new folder stores the utility classes required to connect to the API for Cassandra account.

    Add the CassandraUtils class to create the cluster and to open and close Cassandra sessions. The cluster connects to the API for Cassandra account in Azure Cosmos DB and returns a session to access. Use the Configurations class to read connection string information from the config.properties file.

  5. The Java sample creates a database with user information such as user name, user ID, and user city. You need to define get and set methods to access user details in the main function.

    Create a User.java class under the src/main/java/com/azure/cosmosdb/cassandra/ folder with get and set methods.

Add a database and a table

This section describes how to add a database (keyspace) and a table, by using CQL.

  1. Under the src\main\java\com\azure\cosmosdb\cassandra folder, create a new folder named repository.

  2. Create the UserRepository Java class and add the following code to it:

    package com.azure.cosmosdb.cassandra.repository; 
    import java.util.List; 
    import com.datastax.driver.core.BoundStatement; 
    import com.datastax.driver.core.PreparedStatement; 
    import com.datastax.driver.core.Row; 
    import com.datastax.driver.core.Session; 
    import org.slf4j.Logger; 
    import org.slf4j.LoggerFactory; 
    
    /** 
     * Create a Cassandra session 
     */ 
    public class UserRepository { 
    
        private static final Logger LOGGER = LoggerFactory.getLogger(UserRepository.class); 
        private Session session; 
        public UserRepository(Session session) { 
            this.session = session; 
        } 
    
        /** 
        * Create keyspace uprofile in cassandra DB 
         */ 
    
        public void createKeyspace() { 
             final String query = "CREATE KEYSPACE IF NOT EXISTS uprofile WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 }"; 
            session.execute(query); 
            LOGGER.info("Created keyspace 'uprofile'"); 
        } 
    
        /** 
         * Create user table in cassandra DB 
         */ 
    
        public void createTable() { 
            final String query = "CREATE TABLE IF NOT EXISTS uprofile.user (user_id int PRIMARY KEY, user_name text, user_bcity text)"; 
            session.execute(query); 
            LOGGER.info("Created table 'user'"); 
        } 
    } 
    
  3. Locate the src\main\java\com\azure\cosmosdb\cassandra folder, and create a new subfolder named examples.

  4. Create the UserProfile Java class. This class contains the main method that calls the createKeyspace and createTable methods you defined earlier:

    package com.azure.cosmosdb.cassandra.examples; 
    import java.io.IOException; 
    import com.azure.cosmosdb.cassandra.repository.UserRepository; 
    import com.azure.cosmosdb.cassandra.util.CassandraUtils; 
    import com.datastax.driver.core.PreparedStatement; 
    import com.datastax.driver.core.Session; 
    import org.slf4j.Logger; 
    import org.slf4j.LoggerFactory; 
    
    /** 
     * Example class which will demonstrate following operations on Cassandra Database on CosmosDB 
     * - Create Keyspace 
     * - Create Table 
     * - Insert Rows 
     * - Select all data from a table 
     * - Select a row from a table 
     */ 
    
    public class UserProfile { 
    
        private static final Logger LOGGER = LoggerFactory.getLogger(UserProfile.class); 
        public static void main(String[] s) throws Exception { 
            CassandraUtils utils = new CassandraUtils(); 
            Session cassandraSession = utils.getSession(); 
    
            try { 
                UserRepository repository = new UserRepository(cassandraSession); 
                //Create keyspace in cassandra database 
                repository.createKeyspace(); 
                //Create table in cassandra database 
                repository.createTable(); 
    
            } finally { 
                utils.close(); 
                LOGGER.info("Please delete your table after verifying the presence of the data in portal or from CQL"); 
            } 
        } 
    } 
    

Run the app

  1. Open a command prompt or terminal window. Paste the following code block.

    This code changes the directory (cd) to the folder path where you created the project. Then, it runs the mvn clean install command to generate the cosmosdb-cassandra-examples.jar file within the target folder. Finally, it runs the Java application.

    cd cassandra-demo
    
    mvn clean install 
    
    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.

  2. Now, in the Azure portal, open Data Explorer to confirm that the keyspace and table were created.

Next steps

In this tutorial, you've learned how to create a API for Cassandra account in Azure Cosmos DB, a database, and a table by using a Java application. You can now proceed to the next article: