Quickstart: Create an Azure Cosmos DB account and manage data with the Java SDK
This guide will walk you through the essential steps to get started with Azure Cosmos DB using the Java SDK. You'll learn how to create a database account, set up a container, and perform basic data operations.
Prerequisites
- Java Development Kit (JDK) 8 or later.
- Maven or Gradle build tool.
- An Azure subscription. If you don't have one, you can create a free account.
Note: For this quickstart, we'll use the free tier of Azure Cosmos DB for your Cosmos DB account. The free tier offers a limited amount of throughput and storage, which is perfect for getting started.
Step 1: Create an Azure Cosmos DB Account
You can create an Azure Cosmos DB account through the Azure portal, Azure CLI, or Azure PowerShell.
Using Azure Portal:
- Sign in to the Azure portal.
- Select Create a resource.
- Search for Azure Cosmos DB and select it.
- Click Create.
- In the Create Azure Cosmos DB account page, select your subscription, resource group, and enter a unique name for your account.
- For API, select Core (SQL).
- For Capacity mode, select Serverless. This will automatically provision you with a free tier account.
- Review and create your account.
Once the account is created, navigate to your Cosmos DB account in the Azure portal. You'll need the URI and Primary Key for your application. Find these under Keys.
Step 2: Set up your Java Project
Create a new Maven project. If you're using the command line, you can use the following command:
mvn archetype:generate -DgroupId=com.contoso -DartifactId=cosmosdb-java-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
Navigate into your project directory and open the pom.xml
file. Add the Azure Cosmos DB Java SDK dependency:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-cosmos</artifactId>
<version>4.43.0</version> <!-- Check for the latest version -->
</dependency>
Step 3: Write your Java Code
Replace the contents of your src/main/java/com/contoso/App.java
file with the following code. Remember to replace the placeholder values with your actual Cosmos DB account URI and primary key.
import com.azure.cosmos.*;
import com.azure.cosmos.models.*;
import com.azure.cosmos.util.CosmosPagedIterable;
import java.util.UUID;
public class App {
// Replace with your Cosmos DB endpoint and key
private static String endpoint = "YOUR_COSMOS_DB_ENDPOINT";
private static String key = "YOUR_COSMOS_DB_PRIMARY_KEY";
private static String databaseName = "ToDoList";
private static String containerName = "Items";
private CosmosClient client;
private CosmosDatabase database;
private CosmosContainer container;
public static void main(String[] args) {
App app = new App();
app.run();
}
public void run() {
// Initialize Cosmos Client
CosmosClientBuilder builder = new CosmosClientBuilder()
.endpointDiscoveryEnabled(true)
.endpoint(endpoint)
.key(key)
.consistencyLevel(ConsistencyLevel.EVENTUAL); // Or another suitable level
client = builder.buildClient();
// Create database if it doesn't exist
createDatabaseIfNotExists();
// Create container if it doesn't exist
createContainerIfNotExists();
// Perform operations
createItemExample();
readItemExample();
queryItemsExample();
deleteItemExample();
System.out.println("Quickstart operations completed.");
}
private void createDatabaseIfNotExists() {
System.out.println("Creating database " + databaseName + " if it doesn't exist...");
client.createDatabaseIfNotExists(databaseName);
database = client.getDatabase(databaseName);
System.out.println("Database ready.");
}
private void createContainerIfNotExists() {
System.out.println("Creating container " + containerName + " if it doesn't exist...");
if (database.getContainer(containerName) == null) {
CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerName, "/partitionKey");
container = database.createContainer(containerProperties).getContainer();
System.out.println("Container created.");
} else {
container = database.getContainer(containerName);
System.out.println("Container already exists.");
}
}
private void createItemExample() {
System.out.println("\nCreating an item...");
Item item = new Item(UUID.randomUUID().toString(), "Learn Azure Cosmos DB", "This is a sample task.", false);
ItemResponse<Item> response = container.createItem(item).block(); // block() is used for simplicity in this example
System.out.println("Item created: " + response.getItem().getId() + " with status code: " + response.getStatusCode());
}
private void readItemExample() {
String itemId = "YOUR_ITEM_ID_TO_READ"; // Replace with an actual item ID
System.out.println("\nReading item with ID: " + itemId);
try {
ItemResponse<Item> response = container.readItem(itemId, new PartitionKey(itemId), Item.class);
System.out.println("Item found: " + response.getItem());
} catch (CosmosException e) {
System.err.println("Error reading item: " + e.getStatusCode() + " - " + e.getMessage());
}
}
private void queryItemsExample() {
System.out.println("\nQuerying all items...");
CosmosPagedIterable<Item> items = container.readAllItems(new CosmosQueryRequestOptions(), Item.class);
System.out.println("Found items:");
items.forEach(item -> System.out.println("\t" + item));
}
private void deleteItemExample() {
String itemIdToDelete = "YOUR_ITEM_ID_TO_DELETE"; // Replace with an actual item ID
System.out.println("\nDeleting item with ID: " + itemIdToDelete);
try {
ItemResponse<Void> response = container.deleteItem(itemIdToDelete, new PartitionKey(itemIdToDelete));
System.out.println("Item deleted with status code: " + response.getStatusCode());
} catch (CosmosException e) {
System.err.println("Error deleting item: " + e.getStatusCode() + " - " + e.getMessage());
}
}
// Helper class for the item structure
static class Item {
public String id;
public String name;
public String description;
public boolean completed;
public Item() {}
public Item(String id, String name, String description, boolean completed) {
this.id = id;
this.name = name;
this.description = description;
this.completed = completed;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public boolean isCompleted() {
return completed;
}
@Override
public String toString() {
return "Item{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
", completed=" + completed +
'}';
}
}
}
Important:
- Replace
YOUR_COSMOS_DB_ENDPOINT
andYOUR_COSMOS_DB_PRIMARY_KEY
with the actual values from your Azure Cosmos DB account. - For the
readItemExample
anddeleteItemExample
, you'll need to provide validitemId
s that exist in your container. - The
partitionKey
for this example is set to/partitionKey
in the container creation. Make sure your `Item` class has a field namedpartitionKey
or adjust the container creation and item operations accordingly. In this example, we're using theid
as the partition key for simplicity, but in production, you should choose a partition key that provides good distribution.
Step 4: Build and Run your Application
Use Maven to compile and run your application:
mvn clean install exec:java -Dexec.mainClass="com.contoso.App"
You should see output indicating the creation of the database and container, followed by the results of the item operations.
Next Steps
Congratulations! You've successfully created your first Azure Cosmos DB application with the Java SDK. Explore the following resources to learn more: