Creating a Container
This guide explains how to create a container in Azure Cosmos DB using the Java SDK.
Prerequisites
- An Azure subscription.
- An Azure Cosmos DB account (SQL API).
- Java Development Kit (JDK) 8 or later installed.
- Maven or Gradle for dependency management.
- The Azure Cosmos DB Java SDK added to your project.
Steps to Create a Container
A container is the fundamental unit of scalability and throughput in Azure Cosmos DB. It holds a set of items, and a partition key that defines logical partitions.
1. Initialize the Cosmos Client
First, you need to initialize the Cosmos Client with your endpoint and master key.
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.models.CosmosContainerProperties;
import com.azure.cosmos.models.ThroughputProperties;
// ...
String endpoint = "YOUR_COSMOS_DB_ENDPOINT";
String masterKey = "YOUR_COSMOS_DB_MASTER_KEY";
String databaseId = "YOUR_DATABASE_ID";
String containerId = "YOUR_CONTAINER_ID";
String partitionKeyPath = "/yourPartitionKey"; // e.g., "/id" or "/categoryId"
CosmosClient client = new CosmosClientBuilder()
.endpoint(endpoint)
.key(masterKey)
.buildClient();
2. Get the Database Object
Once the client is initialized, get a reference to your database.
// Assuming 'client' is already initialized
// Use the database ID you've created or plan to use
// If the database doesn't exist, you'd create it first using client.createDatabase(databaseId)
// For simplicity, assuming database already exists
com.azure.cosmos.CosmosDatabase database = client.getDatabase(databaseId);
3. Define Container Properties and Throughput
Define the container's properties, including its ID and the partition key path. You also need to specify the throughput (Request Units per second - RU/s).
// Define container properties
CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyPath);
// Define throughput: Use autoscale or manual provisioning
// For manual provisioning:
// ThroughputProperties throughputProperties = ThroughputProperties.createManualThroughput(400); // 400 RU/s
// For autoscale provisioning (recommended for predictable workloads):
ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaleThroughput(1000); // Max 1000 RU/s
4. Create the Container
Use the `createContainer` method on the database object.
// Create the container
try {
database.createContainer(containerProperties, throughputProperties);
System.out.println("Container " + containerId + " created successfully.");
} catch (Exception e) {
System.err.println("Error creating container: " + e.getMessage());
// Handle potential conflicts if the container already exists
// or other exceptions.
} finally {
// Close the client connection when application exits
// client.close();
}
Full Example Code
Here's a complete, runnable example demonstrating the creation of a container.
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.CosmosDatabaseProperties;
import com.azure.cosmos.models.ThroughputProperties;
import com.azure.cosmos.models.CosmosContainerResponse;
public class CreateCosmosContainer {
private static String endpoint = "YOUR_COSMOS_DB_ENDPOINT"; // Replace with your endpoint
private static String masterKey = "YOUR_COSMOS_DB_MASTER_KEY"; // Replace with your master key
private static String databaseId = "my-sample-database";
private static String containerId = "my-sample-container";
private static String partitionKeyPath = "/categoryId"; // Example partition key path
public static void main(String[] args) {
CosmosClient client = new CosmosClientBuilder()
.endpoint(endpoint)
.key(masterKey)
.buildClient();
// Create database if it doesn't exist
createDatabaseIfNotExists(client);
CosmosDatabase database = client.getDatabase(databaseId);
// Define container properties
CosmosContainerProperties containerProperties = new CosmosContainerProperties(containerId, partitionKeyPath);
// Define throughput (e.g., autoscale with max 1000 RU/s)
ThroughputProperties throughputProperties = ThroughputProperties.createAutoscaleThroughput(1000);
try {
CosmosContainerResponse response = database.createContainer(containerProperties, throughputProperties);
System.out.println("Container " + containerId + " created successfully.");
System.out.println("ID: " + response.getProperties().getId());
System.out.println("Partition Key Path: " + response.getProperties().getPartitionKeyDefinition().getPaths());
System.out.println("Throughput: " + response.getProperties().getThroughput());
} catch (Exception e) {
System.err.println("Error creating container: " + e.getMessage());
} finally {
// Close the client connection
client.close();
System.out.println("Cosmos Client closed.");
}
}
private static void createDatabaseIfNotExists(CosmosClient client) {
try {
client.read()
.block(); // Check if connection is valid
} catch (Exception e) {
System.err.println("Error connecting to Cosmos DB: " + e.getMessage());
System.exit(1); // Exit if connection fails
}
CosmosDatabaseProperties dbProperties = new CosmosDatabaseProperties(databaseId);
try {
client.createDatabase(dbProperties);
System.out.println("Database " + databaseId + " created.");
} catch (Exception e) {
// If database already exists, it's okay
if (!e.getMessage().contains("Conflict")) {
System.err.println("Error creating database: " + e.getMessage());
} else {
System.out.println("Database " + databaseId + " already exists.");
}
}
}
}
Key Considerations
- Partition Key: Choosing an effective partition key is crucial for performance and scalability. It should distribute your data evenly across logical partitions.
- Throughput: Select the appropriate RU/s based on your workload. Autoscale is often a good starting point.
- Error Handling: Implement robust error handling, especially for potential conflicts if the container already exists.
- Resource Naming: Ensure unique IDs for your databases and containers.
Next Steps
After creating a container, you can start adding items, querying data, and managing your Azure Cosmos DB resources.
Explore Cosmos DB REST API Learn about Partitioning