Deleting Items in Azure Cosmos DB with Java SDK

This document guides you through the process of deleting items from your Azure Cosmos DB collections using the official Java SDK. Deleting items is a fundamental operation for managing data in your NoSQL database.

Prerequisites

Core Concepts

Deleting an item in Cosmos DB typically involves specifying the item's unique identifier (ID) and, if applicable, its partition key. The SDK provides methods to perform these operations efficiently.

Deleting an Item by ID

The most common way to delete an item is by providing its unique ID. If your container does not use a partition key, this is all you need.

Example: Deleting a document without a partition key


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

public class DeleteItemExample {

    private static final String ENDPOINT = "YOUR_COSMOS_DB_ENDPOINT";
    private static final String PRIMARY_KEY = "YOUR_COSMOS_DB_PRIMARY_KEY";
    private static final String DATABASE_NAME = "YOUR_DATABASE_NAME";
    private static final String CONTAINER_NAME = "YOUR_CONTAINER_NAME";

    public static void main(String[] args) {
        // Initialize the Cosmos client
        CosmosClient client = new CosmosClientBuilder()
                .endpoint(ENDPOINT)
                .key(PRIMARY_KEY)
                .buildClient();

        CosmosDatabase database = client.getDatabase(DATABASE_NAME);
        CosmosContainer container = database.getContainer(CONTAINER_NAME);

        // The ID of the item to delete
        String itemIdToDelete = "your-item-id";

        try {
            System.out.println("Attempting to delete item with ID: " + itemIdToDelete);

            // Delete the item
            CosmosResponse itemResponse = container.deleteItem(itemIdToDelete, new PartitionKey(itemIdToDelete)); // If no partition key, you might not need PartitionKey. For partitioned containers, use the actual partition key value.

            System.out.println("Item deleted successfully. Status code: " + itemResponse.getStatusCode());

        } catch (CosmosException dfe) {
            System.err.println("Error deleting item: " + dfe.getStatusCode() + " - " + dfe.getMessage());
        } finally {
            // Close the client
            client.close();
        }
    }
}
            

Deleting an Item with a Partition Key

For partitioned containers, you must provide both the item's ID and its partition key value to ensure the correct item is deleted from the relevant partition.

Example: Deleting a document with a partition key


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

public class DeleteItemPartitionedExample {

    private static final String ENDPOINT = "YOUR_COSMOS_DB_ENDPOINT";
    private static final String PRIMARY_KEY = "YOUR_COSMOS_DB_PRIMARY_KEY";
    private static final String DATABASE_NAME = "YOUR_DATABASE_NAME";
    private static final String CONTAINER_NAME = "YOUR_CONTAINER_NAME";
    private static final String PARTITION_KEY_PATH = "/yourPartitionKeyPath"; // e.g., "/category"

    public static void main(String[] args) {
        // Initialize the Cosmos client
        CosmosClient client = new CosmosClientBuilder()
                .endpoint(ENDPOINT)
                .key(PRIMARY_KEY)
                .buildClient();

        CosmosDatabase database = client.getDatabase(DATABASE_NAME);
        CosmosContainer container = database.getContainer(CONTAINER_NAME);

        // The ID and partition key of the item to delete
        String itemIdToDelete = "your-item-id";
        String partitionKeyValue = "your-partition-key-value"; // e.g., "electronics"

        try {
            System.out.println("Attempting to delete item with ID: " + itemIdToDelete + " and partition key: " + partitionKeyValue);

            // Create a PartitionKey object
            PartitionKey partitionKey = new PartitionKey(partitionKeyValue);

            // Delete the item
            CosmosResponse itemResponse = container.deleteItem(itemIdToDelete, partitionKey);

            System.out.println("Item deleted successfully. Status code: " + itemResponse.getStatusCode());

        } catch (CosmosException dfe) {
            System.err.println("Error deleting item: " + dfe.getStatusCode() + " - " + dfe.getMessage());
        } finally {
            // Close the client
            client.close();
        }
    }
}
            
Important Note: When deleting items, ensure you use the correct partition key value. If the partition key is incorrect, Cosmos DB will not find the item and will return a 404 (Not Found) error. For containers without a partition key, the `deleteItem(itemId, partitionKey)` overload is still available; you can pass `new PartitionKey(null)` or, in simpler cases where the ID is used as partition key (not recommended), `new PartitionKey(itemIdToDelete)`.

Error Handling

It's crucial to implement proper error handling. Common errors include:

The SDK throws CosmosException for errors, allowing you to catch and handle them gracefully.

API References

Key Classes and Methods

Best Practices