Azure Cosmos DB for NoSQL: Java SDK v4 examples
APPLIES TO: NoSQL
Important
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.
Important
If you don't have an Azure subscription, create a trial account before you begin.
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.
Prerequisites
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 VS Code) 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
com.azure.cosmos.examples.sample.synchronicity.MainClass
where sample.synchronicity.MainClass can be
- crudquickstart.sync.SampleCRUDQuickstart
- crudquickstart.async.SampleCRUDQuickstartAsync
- indexmanagement.sync.SampleIndexManagement
- indexmanagement.async.SampleIndexManagementAsync
- storedprocedure.sync.SampleStoredProcedure
- storedprocedure.async.SampleStoredProcedureAsync
- changefeed.SampleChangeFeedProcessor (Changefeed has only an async sample, no sync sample.) ...etc...
Note
Each sample is self-contained; it sets itself up and cleans up after itself. The samples issue multiple calls to create a CosmosContainer
or CosmosAsyncContainer
. Each time this is done, your subscription is billed for 1 hour of usage for the performance tier of the collection created.
Database examples
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.
Task | API reference |
---|---|
Create a database | CosmosClient.createDatabaseIfNotExists CosmosAsyncClient.createDatabaseIfNotExists |
Read a database by ID | CosmosClient.getDatabase CosmosAsyncClient.getDatabase |
Read all the databases | CosmosClient.readAllDatabases CosmosAsyncClient.readAllDatabases |
Delete a database | CosmosDatabase.delete CosmosAsyncDatabase.delete |
Collection examples
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.
Task | API reference |
---|---|
Create a collection | CosmosDatabase.createContainerIfNotExists CosmosAsyncDatabase.createContainerIfNotExists |
Change configured performance of a collection | CosmosContainer.replaceThroughput CosmosAsyncContainer.replaceProvisionedThroughput |
Get a collection by ID | CosmosDatabase.getContainer CosmosAsyncDatabase.getContainer |
Read all the collections in a database | CosmosDatabase.readAllContainers CosmosAsyncDatabase.readAllContainers |
Delete a collection | CosmosContainer.delete CosmosAsyncContainer.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.
Task | API reference |
---|---|
Create a database with specified autoscale max throughput | CosmosClient.createDatabase CosmosAsyncClient.createDatabase |
The autoscale collection samples files for sync and async show how to perform the following tasks.
Task | API reference |
---|---|
Create a collection with specified autoscale max throughput | CosmosDatabase.createContainerIfNotExists CosmosAsyncDatabase.createContainerIfNotExists |
Change configured autoscale max throughput of a collection | CosmosContainer.replaceThroughput CosmosAsyncContainer.replaceThroughput |
Read autoscale throughput configuration of a collection | CosmosContainer.readThroughput CosmosAsyncContainer.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.
Task | API reference |
---|---|
Create a collection | CosmosDatabase.createContainerIfNotExists CosmosAsyncDatabase.createContainerIfNotExists |
Item examples
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.
Note
You must specify a partition key when performing operations against a specific item.
Task | API reference |
---|---|
Create a document | CosmosContainer.createItem CosmosAsyncContainer.createItem |
Read a document by ID | CosmosContainer.readItem CosmosAsyncContainer.readItem |
Query for documents | CosmosContainer.queryItems CosmosAsyncContainer.queryItems |
Replace a document | CosmosContainer.replaceItem CosmosAsyncContainer.replaceItem |
Upsert a document | CosmosContainer.upsertItem CosmosAsyncContainer.upsertItem |
Delete a document | CosmosContainer.deleteItem CosmosAsyncContainer.deleteItem |
Replace a document with conditional ETag check | CosmosItemRequestOptions.setIfMatchETag (sync) CosmosItemRequestOptions.setIfMatchETag (async) |
Read document only if document has changed | CosmosItemRequestOptions.setIfNoneMatchETag (sync) CosmosItemRequestOptions.setIfNoneMatchETag (async) |
Partial document update | CosmosContainer.patchItem |
Bulk document update | Bulk samples |
Transactional batch | batch samples |
Indexing examples
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.
Task | API reference |
---|---|
Include specified documents paths in the index | IndexingPolicy.IncludedPaths |
Exclude specified documents paths from the index | IndexingPolicy.ExcludedPaths |
Create a composite index | IndexingPolicy.setCompositeIndexes CompositePath |
Create a geospatial index | IndexingPolicy.setSpatialIndexes SpatialSpec SpatialType |
For more information about indexing, see Azure Cosmos DB indexing policies.
Query examples
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.
Task | API reference |
---|---|
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.
Task | API reference |
---|---|
Create a stored procedure | CosmosScripts.createStoredProcedure |
Execute a stored procedure | CosmosStoredProcedure.execute |
Delete a stored procedure | CosmosStoredProcedure.delete |
Next steps
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