See: Description
Package | Description |
---|---|
com.azure.cosmos |
This package provides interfaces for interacting with Azure Cosmos DB.
|
com.azure.cosmos.models |
This package provides rest contracts for interacting with Azure Cosmos DB SQL APIs.
|
com.azure.cosmos.util |
This package provides utilities such as
CosmosPagedFlux and CosmosPagedIterable for interacting with Azure Cosmos DB SQL APIs. |
Azure Cosmos DB is Microsoft’s globally distributed, multi-model database service for operational and analytics workloads. It offers multi-mastering feature by automatically scaling throughput, compute, and storage. This project provides SDK library in Java for interacting with SQL API of Azure Cosmos DB Database Service.
Source code | Package (Maven) | API reference documentation | Product documentation | Samples
Please include the azure-sdk-bom to your project to take dependency on GA version of the library. In the following snippet, replace the {bomversionto_target} placeholder with the version number. To learn more about the BOM, see the AZURE SDK BOM README.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-sdk-bom</artifactId>
<version>{bom_version_to_target}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
and then include the direct dependency in the dependencies section without the version tag.
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-cosmos</artifactId>
</dependency>
</dependencies>
If you want to take dependency on a particular version of the library that is not present in the BOM, add the direct dependency to your project as follows.
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-cosmos</artifactId>
<version>4.17.0</version>
</dependency>
Refer to maven central for previous releases
Refer to javadocs for more details on the package
SLF4J is only needed if you plan to use logging, please also download an SLF4J binding which will link the SLF4J API with the logging implementation of your choice. See the SLF4J user manual for more information.
The SDK provides Reactor Core based async APIs. You can read more about Reactor Core and Flux/Mono types here
In order to interact with the Azure CosmosDB service you'll need to create an instance of the Cosmos Client class. To make this possible you will need an url and key of the Azure CosmosDB service.
The SDK provides two clients.
1. CosmosAsyncClient
for operations using asynchronous APIs.
2. CosmosClient
for operations using synchronous (blocking) APIs.
CosmosAsyncClient cosmosAsyncClient = new CosmosClientBuilder()
.endpoint(serviceEndpoint)
.key(key)
.buildAsyncClient();
CosmosClient cosmosClient = new CosmosClientBuilder()
.endpoint(serviceEndpoint)
.key(key)
.buildClient();
Azure Cosmos DB Java SDK provides client-side logical representation to access the Azure Cosmos DB SQL API. A Cosmos DB account contains zero or more databases, a database (DB) contains zero or more containers, and a container contains zero or more items. You may read more about databases, containers and items here. A few important properties defined at the level of the container, among them are provisioned throughput and partition key.
The following section provides several code snippets covering some of the most common CosmosDB SQL API tasks, including: * Create Cosmos Client * Create Database * Create Container * CRUD operation on Items
// Create a new CosmosAsyncClient via the CosmosClientBuilder
// It only requires endpoint and key, but other useful settings are available
CosmosAsyncClient cosmosAsyncClient = new CosmosClientBuilder()
.endpoint("<YOUR ENDPOINT HERE>")
.key("<YOUR KEY HERE>")
.buildAsyncClient();
// Create a new CosmosClient via the CosmosClientBuilder
CosmosClient cosmosClient = new CosmosClientBuilder()
.endpoint("<YOUR ENDPOINT HERE>")
.key("<YOUR KEY HERE>")
.buildClient();
// Create a new CosmosClient with customizations
CosmosClient cosmosClient = new CosmosClientBuilder()
.endpoint(serviceEndpoint)
.key(key)
.directMode(directConnectionConfig, gatewayConnectionConfig)
.consistencyLevel(ConsistencyLevel.SESSION)
.connectionSharingAcrossClientsEnabled(true)
.contentResponseOnWriteEnabled(true)
.userAgentSuffix("my-application1-client")
.preferredRegions(Collections.singletonList("West US", "East US"))
.buildClient();
Using any one of the clients created in previous example, you can create a database like this:
// Get a reference to the container
// This will create (or read) a database and its container.
client.createDatabaseIfNotExists(DATABASE_NAME)
// TIP: Our APIs are Reactor Core based, so try to chain your calls
.flatMap(response -> client.getDatabase(DATABASE_NAME)
.subscribe();
Using the above created database, you can chain another operation to it for creating a container like this:
client.createDatabaseIfNotExists(DATABASE_NAME)
// TIP: Our APIs are Reactor Core based, so try to chain your calls
.flatMap(response -> client.getDatabase(DATABASE_NAME)
// Create Container
.createContainerIfNotExists(CONTAINER_NAME, "/id"))
.flatMap(response -> Mono.just(client.getDatabase(DATABASE_NAME).getContainer(CONTAINER_NAME)))
.subscribe();
// Create an item
container.createItem(new Passenger("carla.davis @outlook.com", "Carla Davis", "SEA", "IND"))
.flatMap(response -> {
System.out.println("Created item: " + response.getItem());
// Read that item 👓
return container.readItem(response.getItem().getId(),
new PartitionKey(response.getItem().getId()),
Passenger.class);
})
.flatMap(response -> {
System.out.println("Read item: " + response.getItem());
// Replace that item 🔁
Passenger p = response.getItem();
p.setDestination("SFO");
return container.replaceItem(p,
response.getItem().getId(),
new PartitionKey(response.getItem().getId()));
})
// delete that item 💣
.flatMap(response -> container.deleteItem(response.getItem().getId(),
new PartitionKey(response.getItem().getId())))
.block(); // Blocking for demo purposes (avoid doing this in production unless you must)
// ...
We have a get started sample app available here.
Also, we have more examples examples project.
Azure Cosmos DB is a fast and flexible distributed database that scales seamlessly with guaranteed latency and throughput. You do not have to make major architecture changes or write complex code to scale your database with Azure Cosmos DB. Scaling up and down is as easy as making a single API call or SDK method call. However, because Azure Cosmos DB is accessed via network calls there are client-side optimizations you can make to achieve peak performance when using Azure Cosmos DB Java SDK v4.
Performance guide covers these client-side optimizations.
Troubleshooting guide covers common issues, workarounds, diagnostic steps, and tools when you use Azure Cosmos DB Java SDK v4 with Azure Cosmos DB SQL API accounts.
Azure Cosmos DB Java SDK v4 uses SLF4j as the logging facade that supports logging into popular logging frameworks such as log4j and logback.
For example, if you want to use log4j as the logging framework, add the following libs in your Java classpath.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
Also add a log4j config.
# this is a sample log4j configuration
# Set root logger level to INFO and its only appender to A1.
log4j.rootLogger=INFO, A1
log4j.category.com.azure.cosmos=INFO
#log4j.category.io.netty=OFF
#log4j.category.io.projectreactor=OFF
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d %5X{pid} [%t] %-5p %c - %m%n
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
Copyright © 2021 Microsoft Corporation. All rights reserved.