CRUD Operations with Azure Cosmos DB SDK for Java

This section provides comprehensive guidance on performing Create, Read, Update, and Delete (CRUD) operations using the Azure Cosmos DB SDK for Java. We'll cover essential methods for interacting with your data.

The Azure Cosmos DB SDK for Java simplifies data manipulation. You'll primarily interact with instances of CosmosClient, Database, and Container to perform these operations.

Prerequisites: Ensure you have the Azure Cosmos DB Java SDK dependency added to your project (e.g., in your pom.xml or build.gradle file).

1. Creating Items (Create)

To create a new item in a container, you use the upsertItem method. This method inserts the item if it doesn't exist or replaces it if an item with the same ID already exists.

import com.azure.cosmos.*;
import com.azure.cosmos.models.*;
import java.util.*;

// Assuming you have initialized CosmosClient, Database, and Container
public class CreateItemExample {
    public static void createItem(Container container, Object item) {
        try {
            ItemResponse<Object> response = container.upsertItem(item).block();
            if (response != null) {
                System.out.println("Item created/upserted successfully. Status code: " + response.getStatusCode());
            }
        } catch (Exception e) {
            System.err.println("Error creating item: " + e.getMessage());
        }
    }
}

In this example, item is a POJO (Plain Old Java Object) or a Map representing the data to be stored. Cosmos DB automatically serializes it to JSON.

2. Reading Items (Read)

To read a specific item, you need its unique ID and partition key. The readItem method is used for this purpose.

import com.azure.cosmos.*;
import com.azure.cosmos.models.*;

public class ReadItemExample {
    public static Object readItem(Container container, String itemId, String partitionKey) {
        try {
            ItemResponse<Object> response = container.readItem(itemId, new PartitionKey(partitionKey), Object.class).block();
            if (response != null) {
                System.out.println("Item read successfully. ETag: " + response.getETag());
                return response.getItem();
            }
        } catch (Exception e) {
            System.err.println("Error reading item: " + e.getMessage());
        }
        return null;
    }
}

The readItem method requires the item's ID and its partition key. The second argument to PartitionKey constructor should match the partition key value of the item.

3. Updating Items (Update)

Updating an item typically involves reading the item, modifying its properties, and then calling upsertItem again with the updated object. For more granular updates, consider using the JSON merge patch feature available in newer SDK versions or a stored procedure.

import com.azure.cosmos.*;
import com.azure.cosmos.models.*;
import java.util.*;

public class UpdateItemExample {
    public static void updateItem(Container container, String itemId, String partitionKey, Map updates) {
        Object existingItem = readItem(container, itemId, partitionKey); // Assuming readItem is accessible

        if (existingItem != null) {
            // Assuming existingItem is a Map, or cast to your POJO
            if (existingItem instanceof Map) {
                Map<String, Object> itemMap = (Map<String, Object>) existingItem;
                itemMap.putAll(updates);

                try {
                    ItemResponse<Object> response = container.upsertItem(itemMap).block();
                    if (response != null) {
                        System.out.println("Item updated successfully. Status code: " + response.getStatusCode());
                    }
                } catch (Exception e) {
                    System.err.println("Error updating item: " + e.getMessage());
                }
            }
        }
    }

    // Placeholder for the readItem method from the previous example
    private static Object readItem(Container container, String itemId, String partitionKey) {
        // Actual implementation would go here
        return new HashMap<String, Object>();
    }
}

This approach reads the item, applies changes to the in-memory object, and then upserts it back. For large or frequently updated items, consider the efficiency of this pattern.

4. Deleting Items (Delete)

To delete an item, you use the deleteItem method, providing the item's ID and partition key.

import com.azure.cosmos.*;
import com.azure.cosmos.models.*;

public class DeleteItemExample {
    public static void deleteItem(Container container, String itemId, String partitionKey) {
        try {
            ItemResponse<Void> response = container.deleteItem(itemId, new PartitionKey(partitionKey)).block();
            if (response != null) {
                System.out.println("Item deleted successfully. Status code: " + response.getStatusCode());
            }
        } catch (Exception e) {
            System.err.println("Error deleting item: " + e.getMessage());
        }
    }
}

Deleting an item is a permanent action. Ensure you have appropriate confirmations or error handling in place.

Performance Considerations: For high-throughput scenarios, consider batch operations or using stored procedures for complex CRUD logic to minimize network round trips and improve efficiency.

Next Steps

Now that you're familiar with basic CRUD operations, explore how to query your data more effectively using SQL or LINQ syntax in the next section.

Next: Querying Data →