AZ

azure-cosmos-java

SDK for Java-based Azure Cosmos DB operations and reactive programming.

Install

mkdir -p .claude/skills/azure-cosmos-java && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/8443" && unzip -o skill.zip -d .claude/skills/azure-cosmos-java && rm skill.zip

Installs to .claude/skills/azure-cosmos-java

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Azure Cosmos DB SDK for Java. NoSQL database operations with global distribution, multi-model support, and reactive patterns. Triggers: "CosmosClient java", "CosmosAsyncClient", "cosmos database java", "cosmosdb java", "document database java".
244 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Perform NoSQL document CRUD operations
  • Execute reactive database queries
  • Configure global distribution settings
  • Manage consistency levels

How it works

The SDK provides a client hierarchy for account, database, and container operations, supporting both synchronous and reactive asynchronous patterns.

Inputs & outputs

You give it
NoSQL document
You get back
Database operation result

When to use azure-cosmos-java

  • NoSQL document operations in Java
  • Implementing reactive Cosmos DB queries
  • Setting up global distribution

About this skill

Azure Cosmos DB SDK for Java

Client library for Azure Cosmos DB NoSQL API with global distribution and reactive patterns.

Installation

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-cosmos</artifactId>
    <version>LATEST</version>
</dependency>

Or use Azure SDK BOM:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-cosmos</artifactId>
    </dependency>
</dependencies>

Environment Variables

COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/
COSMOS_KEY=<your-primary-key>

Authentication

Key-based Authentication

import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;

CosmosClient client = new CosmosClientBuilder()
    .endpoint(System.getenv("COSMOS_ENDPOINT"))
    .key(System.getenv("COSMOS_KEY"))
    .buildClient();

Async Client

import com.azure.cosmos.CosmosAsyncClient;

CosmosAsyncClient asyncClient = new CosmosClientBuilder()
    .endpoint(serviceEndpoint)
    .key(key)
    .buildAsyncClient();

With Customizations

import com.azure.cosmos.ConsistencyLevel;
import java.util.Arrays;

CosmosClient client = new CosmosClientBuilder()
    .endpoint(serviceEndpoint)
    .key(key)
    .directMode(directConnectionConfig, gatewayConnectionConfig)
    .consistencyLevel(ConsistencyLevel.SESSION)
    .connectionSharingAcrossClientsEnabled(true)
    .contentResponseOnWriteEnabled(true)
    .userAgentSuffix("my-application")
    .preferredRegions(Arrays.asList("West US", "East US"))
    .buildClient();

Client Hierarchy

ClassPurpose
CosmosClient / CosmosAsyncClientAccount-level operations
CosmosDatabase / CosmosAsyncDatabaseDatabase operations
CosmosContainer / CosmosAsyncContainerContainer/item operations

Core Workflow

Create Database

// Sync
client.createDatabaseIfNotExists("myDatabase")
    .map(response -> client.getDatabase(response.getProperties().getId()));

// Async with chaining
asyncClient.createDatabaseIfNotExists("myDatabase")
    .map(response -> asyncClient.getDatabase(response.getProperties().getId()))
    .subscribe(database -> System.out.println("Created: " + database.getId()));

Create Container

asyncClient.createDatabaseIfNotExists("myDatabase")
    .flatMap(dbResponse -> {
        String databaseId = dbResponse.getProperties().getId();
        return asyncClient.getDatabase(databaseId)
            .createContainerIfNotExists("myContainer", "/partitionKey")
            .map(containerResponse -> asyncClient.getDatabase(databaseId)
                .getContainer(containerResponse.getProperties().getId()));
    })
    .subscribe(container -> System.out.println("Container: " + container.getId()));

CRUD Operations

import com.azure.cosmos.models.PartitionKey;

CosmosAsyncContainer container = asyncClient
    .getDatabase("myDatabase")
    .getContainer("myContainer");

// Create
container.createItem(new User("1", "John Doe", "[email protected]"))
    .flatMap(response -> {
        System.out.println("Created: " + response.getItem());
        // Read
        return container.readItem(
            response.getItem().getId(),
            new PartitionKey(response.getItem().getId()),
            User.class);
    })
    .flatMap(response -> {
        System.out.println("Read: " + response.getItem());
        // Update
        User user = response.getItem();
        user.setEmail("[email protected]");
        return container.replaceItem(
            user,
            user.getId(),
            new PartitionKey(user.getId()));
    })
    .flatMap(response -> {
        // Delete
        return container.deleteItem(
            response.getItem().getId(),
            new PartitionKey(response.getItem().getId()));
    })
    .block();

Query Documents

import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.util.CosmosPagedIterable;

CosmosContainer container = client.getDatabase("myDatabase").getContainer("myContainer");

String query = "SELECT * FROM c WHERE c.status = @status";
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();

CosmosPagedIterable<User> results = container.queryItems(
    query,
    options,
    User.class
);

results.forEach(user -> System.out.println("User: " + user.getName()));

Key Concepts

Partition Keys

Choose a partition key with:

  • High cardinality (many distinct values)
  • Even distribution of data and requests
  • Frequently used in queries

Consistency Levels

LevelGuarantee
StrongLinearizability
Bounded StalenessConsistent prefix with bounded lag
SessionConsistent prefix within session
Consistent PrefixReads never see out-of-order writes
EventualNo ordering guarantee

Request Units (RUs)

All operations consume RUs. Check response headers:

CosmosItemResponse<User> response = container.createItem(user);
System.out.println("RU charge: " + response.getRequestCharge());

Best Practices

  1. Reuse CosmosClient — Create once, reuse throughout application
  2. Use async client for high-throughput scenarios
  3. Choose partition key carefully — Affects performance and scalability
  4. Enable content response on write for immediate access to created items
  5. Configure preferred regions for geo-distributed applications
  6. Handle 429 errors with retry policies (built-in by default)
  7. Use direct mode for lowest latency in production

Error Handling

import com.azure.cosmos.CosmosException;

try {
    container.createItem(item);
} catch (CosmosException e) {
    System.err.println("Status: " + e.getStatusCode());
    System.err.println("Message: " + e.getMessage());
    System.err.println("Request charge: " + e.getRequestCharge());
    
    if (e.getStatusCode() == 409) {
        System.err.println("Item already exists");
    } else if (e.getStatusCode() == 429) {
        System.err.println("Rate limited, retry after: " + e.getRetryAfterDuration());
    }
}

Reference Links

ResourceURL
Maven Packagehttps://central.sonatype.com/artifact/com.azure/azure-cosmos
API Documentationhttps://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html
Product Docshttps://learn.microsoft.com/azure/cosmos-db/
Sampleshttps://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples
Performance Guidehttps://learn.microsoft.com/azure/cosmos-db/performance-tips-java-sdk-v4-sql
Troubleshootinghttps://learn.microsoft.com/azure/cosmos-db/troubleshoot-java-sdk-v4-sql

When not to use it

  • When requiring relational database features
  • When exceeding Request Unit budgets

Prerequisites

azure-cosmos package

Limitations

  • Requires careful partition key selection for performance
  • Operations consume Request Units

How it compares

It enables reactive data streams for high-throughput scenarios compared to standard blocking database drivers.

Compared to similar skills

azure-cosmos-java side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
azure-cosmos-java (this skill)03moReviewIntermediate
jpa-patterns35moNo flagsIntermediate
azure-storage-blob-java13moReviewIntermediate
ignite-cluster-setup17moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by microsoft

View all by microsoft

You might also like

jpa-patterns

affaan-m

JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.

322

azure-storage-blob-java

microsoft

Build blob storage applications with Azure Storage Blob SDK for Java. Use when uploading, downloading, or managing files in Azure Blob Storage, working with containers, or implementing streaming data operations.

15

ignite-cluster-setup

apache

Set up and manage a local Apache Ignite 3 cluster using just commands. Use when asked to setup cluster, start nodes, rebuild, initialize cluster, or check status.

12

316-frameworks-spring-mongodb-migrations-mongock

jabrena

Use when you need to add or review Mongock MongoDB data migrations in a Spring Boot application — including Maven coordinates, Spring Data MongoDB drivers, migration scan packages, @ChangeUnit classes, lock/transaction settings, and Testcontainers verification. This should trigger for requests such

00

minecraft-bukkit-pro

sickn33

Master Minecraft server plugin development with Bukkit, Spigot, and Paper APIs. Specializes in event-driven architecture, command systems, world manipulation, player management, and performance optimization. Use PROACTIVELY for plugin architecture, gameplay mechanics, server-side features, or cross-version compatibility.

9078

workflow-orchestration-patterns

wshobson

Design durable workflows with Temporal for distributed systems. Covers workflow vs activity separation, saga patterns, state management, and determinism constraints. Use when building long-running processes, distributed transactions, or microservice orchestration.

10117

Search skills

Search the agent skills registry