Azure Cosmos Java
MicrosoftOfficialCreated by Microsoft
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The Azure Cosmos DB SDK for Java provides a comprehensive set of tools for developers to integrate NoSQL database operations into Java applications. It supports both synchronous and asynchronous programming models, allowing for flexible interaction with databases, containers, and items. The SDK includes features for managing consistency levels, configuring connection modes, and handling geo-distributed data, alongside built-in support for error handling and request unit monitoring.
What it does
- Provides client classes for account, database, and container-level operations.
- Supports both synchronous and asynchronous (reactive) execution patterns.
- Enables CRUD operations on database items with partition key support.
- Allows for SQL-based querying of documents within containers.
- Offers configuration options for consistency levels and preferred regions.
- Includes mechanisms for monitoring request unit (RU) consumption.
When to use it
- When building Java applications that require connectivity to Azure Cosmos DB.
- When you need to perform NoSQL database operations within a Java environment.
- When implementing reactive patterns for database interactions.
- When managing multi-region data distribution in Azure.
Advantages
- Native Java support for Azure Cosmos DB features.
- Flexible client configuration for various consistency and connection requirements.
- Comprehensive error handling and retry logic.
- Supports both simple synchronous and complex asynchronous workflows.
Usage examples
- “How do I initialize a synchronous CosmosClient in Java?”
- The SDK provides the CosmosClientBuilder class to configure and build a CosmosClient using an endpoint and key.
- “Show me how to perform a CRUD operation using the async client.”
- The SDK uses reactive patterns to chain createItem, readItem, replaceItem, and deleteItem operations on a CosmosAsyncContainer.
- “How can I query items from a container?”
- You can use the queryItems method on a CosmosContainer, providing a SQL query string and request options to retrieve items.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/microsoft/azure-cosmos-java/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip azure-cosmos-java.zip -d .agents/skills
Documentation by Microsoft
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
| Class | Purpose |
|---|---|
CosmosClient / CosmosAsyncClient | Account-level operations |
CosmosDatabase / CosmosAsyncDatabase | Database operations |
CosmosContainer / CosmosAsyncContainer | Container/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
| 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:
CosmosItemResponse<User> response = container.createItem(user);
System.out.println("RU charge: " + response.getRequestCharge());Best Practices
Reuse CosmosClient — Create once, reuse throughout application
Use async client for high-throughput scenarios
Choose partition key carefully — Affects performance and scalability
Enable content response on write for immediate access to created items
Configure preferred regions for geo-distributed applications
Handle 429 errors with retry policies (built-in by default)
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
Files
- ATTRIBUTION.mdAdded by AutoGineer958 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md7.3 KiB
- references/examples.md11.7 KiB
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Microsoft
- Publisher
- Microsoft (Official)
- Source
- microsoft/skills · .github/plugins/azure-sdk-java/skills/azure-cosmos-java · commit 0696600
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Microsoft or Microsoft.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download azure-cosmos-java.zip