Microsoft Learn

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

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:

  1. Sign in to the Azure portal.
  2. Select Create a resource.
  3. Search for Azure Cosmos DB and select it.
  4. Click Create.
  5. In the Create Azure Cosmos DB account page, select your subscription, resource group, and enter a unique name for your account.
  6. For API, select Core (SQL).
  7. For Capacity mode, select Serverless. This will automatically provision you with a free tier account.
  8. 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:

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: