Getting Started with Azure Cosmos DB SDK for Java
Welcome to the getting started guide for the Azure Cosmos DB SDK for Java. This tutorial will walk you through the essential steps to set up your environment and perform basic operations with Azure Cosmos DB using Java.
Prerequisites
- Azure Subscription: You need an active Azure subscription. If you don't have one, you can create a free account.
- Azure Cosmos DB Account: Create an Azure Cosmos DB account in the Azure portal. Choose the Core (SQL) API.
- Java Development Kit (JDK): Install JDK version 8 or later.
- Maven: Install Apache Maven.
- IDE: A Java Integrated Development Environment (IDE) such as IntelliJ IDEA, Eclipse, or VS Code.
Step 1: Create an Azure Cosmos DB Account
If you haven't already, create an Azure Cosmos DB account. Follow the official Azure documentation for detailed steps.
Create Azure Cosmos DB Account
Step 2: Set Up Your Java Project
We'll use Maven to manage our project dependencies. Create a new Maven project and add the Azure Cosmos DB Java SDK dependency to your pom.xml file.
Add Dependency to pom.xml
Open your pom.xml file and add the following to the <dependencies> section:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-cosmos</artifactId>
<version>4.53.0</version> <!-- Check for the latest version -->
</dependency>
After saving pom.xml, Maven will automatically download the SDK. If not, you can refresh your project in your IDE or run mvn install from your project's root directory.
Step 3: Connect to Azure Cosmos DB
You'll need your Cosmos DB account's endpoint and primary key to connect. You can find these in the Azure portal under your Cosmos DB account's "Keys" section.
Create a Java class (e.g., CosmosDbManager.java) and add the following code:
import com.azure.cosmos.ConsistencyLevel;
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosDatabase;
import com.azure.cosmos.CosmosException;
public class CosmosDbManager {
private static final String ENDPOINT = "YOUR_COSMOS_DB_ENDPOINT"; // Replace with your endpoint
private static final String KEY = "YOUR_COSMOS_DB_PRIMARY_KEY"; // Replace with your key
private static final String DATABASE_NAME = "ToDoList"; // Example database name
private CosmosClient client;
private CosmosDatabase database;
public CosmosDbManager() {
try {
client = new CosmosClientBuilder()
.endpoint(ENDPOINT)
.key(KEY)
.consistencyLevel(ConsistencyLevel.EVENTUAL) // Or other consistency levels
.buildClient();
database = client.getDatabase(DATABASE_NAME);
System.out.println("Connected to Cosmos DB database: " + DATABASE_NAME);
} catch (CosmosException e) {
System.err.println("Failed to connect to Cosmos DB: " + e.getMessage());
e.printStackTrace();
}
}
public CosmosDatabase getDatabase() {
return database;
}
public void closeClient() {
if (client != null) {
client.close();
System.out.println("Cosmos DB client closed.");
}
}
public static void main(String[] args) {
CosmosDbManager dbManager = new CosmosDbManager();
// You can now use dbManager.getDatabase() for further operations
// For example, creating a container:
// dbManager.getDatabase().createContainerIfNotExists("Items", "/partitionKey");
dbManager.closeClient();
}
}
Explanation:
- Endpoint and Key: These are your credentials to access your Cosmos DB account.
- CosmosClientBuilder: This class is used to configure and build the
CosmosClient. - ConsistencyLevel: Specifies the consistency level for your operations.
EVENTUALis the lowest consistency, offering high availability and performance. - CosmosClient: The main object for interacting with Azure Cosmos DB.
- CosmosDatabase: Represents a database within your Cosmos DB account.
Step 4: Performing Basic Operations
Once connected, you can start performing operations like creating databases, containers, and items.
Creating a Container
Containers are where your data is stored. You need to specify a partition key path for optimal performance.
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosDatabase;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.PartitionKey;
// ... inside your CosmosDbManager class or a new method ...
public void createContainer(String containerName, String partitionKeyPath) {
try {
CosmosContainerProperties properties = new CosmosContainerProperties(containerName, new PartitionKey(partitionKeyPath));
database.createContainerIfNotExists(properties, ThroughputProperties.createManualThroughput(400)); // Set initial throughput
System.out.println("Container '" + containerName + "' created or already exists.");
} catch (CosmosException e) {
System.err.println("Failed to create container '" + containerName + "': " + e.getMessage());
e.printStackTrace();
}
}
// In your main method or elsewhere:
// dbManager.createContainer("Tasks", "/category");
Creating an Item
Items are the actual data entities within your containers. They are typically JSON documents.
import com.azure.cosmos.CosmosContainer;
import com.azure.cosmos.models.CosmosItemResponse;
// Assuming you have a data model class, e.g., Item.java
public class Item {
public String id;
public String name;
public String category;
// ... other properties
}
// ... inside your CosmosDbManager class or a new method ...
public void createItem(String containerName, Item item) {
try {
CosmosContainer container = database.getContainer(containerName);
CosmosItemResponse response = container.createItem(item);
System.out.println("Item created with ID: " + response.getItem().get("id"));
} catch (CosmosException e) {
System.err.println("Failed to create item: " + e.getMessage());
e.printStackTrace();
}
}
// Example usage:
// Item newItem = new Item();
// newItem.id = UUID.randomUUID().toString(); // Unique ID
// newItem.name = "Learn Cosmos DB";
// newItem.category = "Education";
// dbManager.createItem("Tasks", newItem);
Next Steps
You have successfully set up your environment and performed basic operations. Now you can explore more advanced features:
For comprehensive information, refer to the official Azure Cosmos DB Java SDK documentation.