azure-cosmos-java — Claude Code skill for Cosmos DB in Java
A skill that tells your agent how to use the Azure Cosmos DB Java SDK: clients, queries, partition keys and error handling.
npx skills add microsoft/skills --skill azure-cosmos-java -a claude-codeWhat azure-cosmos-java does
The skill covers the azure-cosmos client library for the NoSQL API. It walks through CosmosClient and CosmosAsyncClient, the CosmosDatabase and CosmosContainer hierarchy, creating a database and container, CRUD calls and queryItems. Code samples are Java, and reference tables list the consistency levels from Strong down to Eventual along with what each client class is for.
You need COSMOS_ENDPOINT and COSMOS_KEY in your environment, and the dependency comes in through Maven — either com.azure:azure-cosmos directly or the azure-sdk-bom. No key means no client, so sort out account access before asking the agent to write anything.
Error handling gets its own section. A 409 status means the item is already there, 429 means you hit the request limit, and the response carries getRetryAfterDuration(). The skill also pushes you to build one client and keep it for the whole app, and to switch on direct mode when latency matters in production.
What it helps with
- create a database and container in Cosmos DB from Java
- move blocking calls to
CosmosAsyncClientwith chainedflatMap - catch a 429 and retry after the given delay
- pick a partition key that spreads data and requests
- read the RU cost of an operation from
getRequestCharge
Example prompts for the agent
- Write a Java
CosmosClientfor Cosmos DB, reading the endpoint and key from environment variables - Build async CRUD for the
myContainercontainer with partition key/partitionKey - Add
CosmosExceptionhandling for status codes 409 and 429
How to install azure-cosmos-java
1Skills CLI (Vercel)
npx skills add microsoft/skills --skill azure-cosmos-java -a claude-code2Manually: put the files in place
~/.claude/skills/azure-cosmos-java/SKILL.mdCopy the whole skill folder; for one project use .claude/skills/azure-cosmos-java/
Manually: put the files in place
.agents/skills/azure-cosmos-java/SKILL.mdFor all projects use ~/.agents/skills/
Manually: put the files in place
.cursor/skills/azure-cosmos-java/SKILL.mdCursor also reads .agents/skills/ and .claude/skills/
1GitHub CLI
gh skill install microsoft/skills azure-cosmos-java2Manually: put the files in place
.github/skills/azure-cosmos-java/SKILL.mdPlatform CLI
gemini skills install https://github.com/microsoft/skills --path .github/plugins/azure-sdk-java/skills/azure-cosmos-javaManually: put the files in place
.devin/skills/azure-cosmos-java/SKILL.mdThe legacy .windsurf/skills/ path still works
Claude.ai
Zip the folder and upload it in Settings → Capabilities → Skills
Step by step, with commands for each platform: How to install skills in Claude Code: five ways
Questions about azure-cosmos-java
How do I install azure-cosmos-java in Claude Code?
Run npx skills add microsoft/skills --skill azure-cosmos-java -a claude-code. The skill file lands at ~/.claude/skills/azure-cosmos-java/SKILL.md.
What does azure-cosmos-java do?
It gives the agent a reference for the Cosmos DB Java SDK: building clients, working with databases and containers, querying, consistency levels and error codes.
What do I need before using it?
The com.azure:azure-cosmos Maven dependency plus COSMOS_ENDPOINT and COSMOS_KEY in your environment. Without them the samples in the skill won't run.
Source text
SKILL.md · MIT
---
name: azure-cosmos-java
description: |
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".
license: MIT
metadata:
author: Microsoft
version: "1.0.0"
package: azure-cosmos
---
# Azure Cosmos DB SDK for Java
Client library for Azure Cosmos DB NoSQL API with global distribution and reactive patterns.
## Installation
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-cosmos</artifactId>
<version>LATEST</version>
</dependency>
```
Or use Azure SDK BOM:
```xml
<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
```bash
COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/
COSMOS_KEY=<your-primary-key>
```
## Authentication
### Key-based Authentication
```java
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
```java
import com.azure.cosmos.CosmosAsyncClient;
CosmosAsyncClient asyncClient = new CosmosClientBuilder()
.endpoint(serviceEndpoint)
.key(key)
.buildAsyncClient();
```
### With Customizations
```java
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
| Class | Purpose |
|-------|---------|
| `CosmosClient` / `CosmosAsyncClient` | Account-level operations |
| `CosmosDatabase` / `CosmosAsyncDatabase` | Database operations |
| `CosmosContainer` / `CosmosAsyncContainer` | Container/item operations |
## Core Workflow
### Create Database
```java
// 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
```java
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
```java
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
```java
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
| Level | Guarantee |
|-------|-----------|
| Strong | Linearizability |
| Bounded Staleness | Consistent prefix with bounded lag |
| Session | Consistent prefix within session |
| Consistent Prefix | Reads never see out-of-order writes |
| Eventual | No ordering guarantee |
### Request Units (RUs)
All operations consume RUs. Check response headers:
```java
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
```java
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
| Resource | URL |
|----------|-----|
| Maven Package | https://central.sonatype.com/artifact/com.azure/azure-cosmos |
| API Documentation | https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html |
| Product Docs | https://learn.microsoft.com/azure/cosmos-db/ |
| Samples | https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples |
| Performance Guide | https://learn.microsoft.com/azure/cosmos-db/performance-tips-java-sdk-v4-sql |
| Troubleshooting | https://learn.microsoft.com/azure/cosmos-db/troubleshoot-java-sdk-v4-sql |
© Microsoft · MIT · microsoft/skills