Quickstart: Build a Java app to manage Azure Cosmos DB for Apache Cassandra data (v3 Driver)
APPLIES TO: Cassandra
In this quickstart, you create an Azure Cosmos DB for Apache Cassandra account, and use a Cassandra Java app cloned from GitHub to create a Cassandra database and container using the v3.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
- An Azure account with an active subscription. Create one for free. Or try Azure Cosmos DB for free without an Azure subscription.
- Java Development Kit (JDK) 8. Point your
JAVA_HOME
environment variable to the folder where the JDK is installed. - A Maven binary archive. On Ubuntu, run
apt-get install maven
to install Maven. - Git. On Ubuntu, run
sudo apt-get install git
to install Git.
Note
This is a simple quickstart which uses version 3 of the open-source Apache Cassandra driver for Java. In most cases, you should be able to connect an existing Apache Cassandra dependent Java application to Azure Cosmos DB for Apache Cassandra without any changes to your existing code. However, we recommend adding our custom Java extension, which includes custom retry and load balancing policies, for a better overall experience. This is to handle rate limiting and application level failover in Azure Cosmos DB respectively. You can find a comprehensive sample which implements the extension here.
Create a database account
Before you can create a document database, you need to create a Cassandra account with Azure Cosmos DB.
From the Azure portal menu or the Home page, select Create a resource.
On the New page, search for and select Azure Cosmos DB.
On the Azure Cosmos DB page, select Create.
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.
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 NameSelect 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.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.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. Limit total account throughput Select to limit throughput of the account This is useful if you want to limit the total throughput of the account to a specific value. 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.
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 global 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 the globe. 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
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.
Select Review + create.
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.
Select Go to resource to go to the Azure Cosmos DB account page.
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.
Open a command prompt. Create a new folder named
git-samples
. Then, close the command prompt.md "C:\git-samples"
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"
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.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 Cassandra host, port, user name, password, and TLS/SSL options are set. The connection string information comes from the connection string page in the Azure portal.
cluster = Cluster.builder().addContactPoint(cassandraHost).withPort(cassandraPort).withCredentials(cassandraUsername, cassandraPassword).withSSL(sslOptions).build();
The
cluster
connects to the Azure Cosmos DB for Apache Cassandra and returns a session to access.return cluster.connect();
The following snippets are from the src/main/java/com/azure/cosmosdb/cassandra/repository/UserRepository.java file.
Create a new keyspace.
public void createKeyspace() { final String query = "CREATE KEYSPACE IF NOT EXISTS uprofile WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3' } "; session.execute(query); LOGGER.info("Created keyspace 'uprofile'"); }
Create a new table.
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'"); }
Insert user entities using a prepared statement object.
public PreparedStatement prepareInsertStatement() { final String insertStatement = "INSERT INTO uprofile.user (user_id, user_name, user_bcity) VALUES (?,?,?)"; return session.prepare(insertStatement); } public void insertUser(PreparedStatement statement, int id, String name, String city) { BoundStatement boundStatement = new BoundStatement(statement); session.execute(boundStatement.bind(id, name, city)); }
Query to get all user information.
public void selectAllUsers() { final String query = "SELECT * FROM uprofile.user"; 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's information.
public void selectUser(int id) { final String query = "SELECT * FROM uprofile.user 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.
In your Azure Cosmos DB account in the Azure portal, select Connection String.
Use the button on the right side of the screen to copy the CONTACT POINT value.
Open the config.properties file from the C:\git-samples\azure-cosmosdb-cassandra-java-getting-started\java-examples\src\main\resources folder.
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
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
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...==
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.If you changed line 6 to use a specific TLS/SSL certificate, update line 7 to use the password for that certificate.
Save the config.properties file.
Run the Java app
In the git terminal window,
cd
to theazure-cosmosdb-cassandra-java-getting-started
folder.cd "C:\git-samples\azure-cosmosdb-cassandra-java-getting-started"
In the git terminal window, use the following command to generate the
cosmosdb-cassandra-examples.jar
file.mvn clean install
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.
In the Azure portal, open Data Explorer to query, modify, and work with this new data.
Review SLAs in the Azure portal
The Azure portal monitors your Azure 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:
Select Metrics in your Azure Cosmos DB account's navigation menu.
Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.
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:
In the Azure portal Search bar, search for and select Resource groups.
From the list, select the resource group you created for this quickstart.
On the resource group Overview page, select Delete resource group.
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 API for Cassandra, 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.