Azure Cosmos DB for NoSQL: Java SDK v4 examples
APPLIES TO: NoSQL
To learn more about Java SDK v4, please see the Azure Cosmos DB Java SDK v4 Release notes, Maven repository, Azure Cosmos DB Java SDK v4 performance tips, and Azure Cosmos DB Java SDK v4 troubleshooting guide for more information. If you are currently using an older version than v4, see the Migrate to Azure Cosmos DB Java SDK v4 guide for help upgrading to v4.
If you don't have an Azure subscription, create an Azure free account before you begin.
- You can activate Visual Studio subscriber benefits: Your Visual Studio subscription gives you credits every month that you can use for paid Azure services.
You can try Azure Cosmos DB for free, without an Azure subscription, and with no commitment required. Alternatively, you can create an Azure Cosmos DB free tier account, with the first 1000 RU/s and 25 GB of storage for free. You can also use the Azure Cosmos DB emulator with a URI of
https://localhost:8081. For the key to use with the emulator, see Authenticating requests.
The latest sample applications that perform CRUD operations and other common operations on Azure Cosmos DB resources are included in the azure-cosmos-java-sql-api-samples GitHub repository. This article provides:
- Links to the tasks in each of the example Java project files.
- Links to the related API reference content.
You need the following to run this sample application:
- Java Development Kit 8
- Azure Cosmos DB Java SDK v4
You can optionally use Maven to get the latest Azure Cosmos DB Java SDK v4 binaries for use in your project. Maven automatically adds any necessary dependencies. Otherwise, you can directly download the dependencies listed in the pom.xml file and add them to your build path.
<dependency> <groupId>com.azure</groupId> <artifactId>azure-cosmos</artifactId> <version>LATEST</version> </dependency>
Running the sample applications
Clone the sample repo:
$ git clone https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples.git $ cd azure-cosmos-java-sql-api-samples
You can run the samples using either an IDE (Eclipse, IntelliJ, or VSCODE) or from the command line using Maven.
These environment variables must be set
ACCOUNT_HOST=your account hostname;ACCOUNT_KEY=your account primary key
in order to give the samples read/write access to your account.
To run a sample, specify its Main Class
where sample.synchronicity.MainClass can be
- changefeed.SampleChangeFeedProcessor (Changefeed has only an async sample, no sync sample.) ...etc...
Each sample is self-contained; it sets itself up and cleans up after itself. The samples issue multiple calls to create a
CosmosAsyncContainer. Each time this is done, your subscription is billed for 1 hour of usage for the performance tier of the collection created.
The Database CRUD Sample files for sync and async show how to perform the following tasks. To learn about the Azure Cosmos DB databases before running the following samples, see Working with databases, containers, and items conceptual article.
|Create a database||CosmosClient.createDatabaseIfNotExists
|Read a database by ID||CosmosClient.getDatabase
|Read all the databases||CosmosClient.readAllDatabases
|Delete a database||CosmosDatabase.delete
The Collection CRUD Samples files for sync and async show how to perform the following tasks. To learn about the Azure Cosmos DB collections before running the following samples, see Working with databases, containers, and items conceptual article.
|Create a collection||CosmosDatabase.createContainerIfNotExists
|Change configured performance of a collection||CosmosContainer.replaceThroughput
|Get a collection by ID||CosmosDatabase.getContainer
|Read all the collections in a database||CosmosDatabase.readAllContainers
|Delete a collection||CosmosContainer.delete
Autoscale collection examples
To learn more about autoscale before running these samples, take a look at these instructions for enabling autoscale in your account and in your databases and containers.
The autoscale database sample files for sync and async show how to perform the following task.
|Create a database with specified autoscale max throughput||CosmosClient.createDatabase
The autoscale collection samples files for sync and async show how to perform the following tasks.
|Create a collection with specified autoscale max throughput||CosmosDatabase.createContainerIfNotExists
|Change configured autoscale max throughput of a collection||CosmosContainer.replaceThroughput
|Read autoscale throughput configuration of a collection||CosmosContainer.readThroughput
Analytical storage collection examples
The Analytical storage Collection CRUD Samples files for sync and async show how to perform the following tasks. To learn about the Azure Cosmos DB collections before running the following samples, read about Azure Cosmos DB Synapse and Analytical Store.
|Create a collection||CosmosDatabase.createContainerIfNotExists
The Document CRUD Samples files for sync and async show how to perform the following tasks. To learn about the Azure Cosmos DB documents before running the following samples, see Working with databases, containers, and items conceptual article.
|Create a document||CosmosContainer.createItem
|Read a document by ID||CosmosContainer.readItem
|Query for documents||CosmosContainer.queryItems
|Replace a document||CosmosContainer.replaceItem
|Upsert a document||CosmosContainer.upsertItem
|Delete a document||CosmosContainer.deleteItem
|Replace a document with conditional ETag check||CosmosItemRequestOptions.setIfMatchETag (sync)
|Read document only if document has changed||CosmosItemRequestOptions.setIfNoneMatchETag (sync)
|Partial document update||CosmosContainer.patchItem|
|Bulk document update||Bulk samples|
|Transactional batch||batch samples|
The Collection CRUD Samples file shows how to perform the following tasks. To learn about indexing in Azure Cosmos DB before running the following samples, see indexing policies, indexing types, and indexing paths conceptual articles.
|Include specified documents paths in the index||IndexingPolicy.IncludedPaths|
|Exclude specified documents paths from the index||IndexingPolicy.ExcludedPaths|
|Create a composite index||IndexingPolicy.setCompositeIndexes
|Create a geospatial index||IndexingPolicy.setSpatialIndexes
For more information about indexing, see Azure Cosmos DB indexing policies.
The Query Samples files for sync and async show how to do the following tasks using the SQL query grammar. To learn about the SQL query reference in Azure Cosmos DB before you run the following samples, see SQL query examples for Azure Cosmos DB.
Change feed examples
The Change Feed Processor Sample file shows how to do the following tasks. To learn about change feed in Azure Cosmos DB before you run the following samples, see Read Azure Cosmos DB change feed and Change feed processor.
|Basic change feed functionality||ChangeFeedProcessor.changeFeedProcessorBuilder|
|Read change feed from the beginning||ChangeFeedProcessorOptions.setStartFromBeginning()|
Server-side programming examples
The Stored Procedure Sample file shows how to do the following tasks. To learn about server-side programming in Azure Cosmos DB before you run the following samples, see Stored procedures, triggers, and user-defined functions.
|Create a stored procedure||CosmosScripts.createStoredProcedure|
|Execute a stored procedure||CosmosStoredProcedure.execute|
|Delete a stored procedure||CosmosStoredProcedure.delete|
Trying to do capacity planning for a migration to Azure Cosmos DB? You can use information about your existing database cluster for capacity planning.
- If all you know is the number of vcores and servers in your existing database cluster, read about estimating request units using vCores or vCPUs
- If you know typical request rates for your current database workload, read about estimating request units using Azure Cosmos DB capacity planner
Submit and view feedback for