Azure Cosmos DB SQL API: Java SDK v4 examples
APPLIES TO:
SQL API
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 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 400 RU/s and 5 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 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
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. 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 Samples file shows how to perform the following tasks. To learn about the Azure Cosmos databases before running the following samples, see Working with databases, containers, and items conceptual article.
| Task | API reference |
|---|---|
| Create a database | CosmosClient.createDatabaseIfNotExists |
| Read a database by ID | CosmosClient.getDatabase |
| Read all the databases | CosmosClient.readAllDatabases |
| Delete a database | CosmosDatabase.delete |
Collection examples
The Collection CRUD Samples file shows how to perform the following tasks. To learn about the Azure Cosmos collections before running the following samples, see Working with databases, containers, and items conceptual article.
| Task | API reference |
|---|---|
| Create a collection | CosmosDatabase.createContainerIfNotExists |
| Change configured performance of a collection | CosmosContainer.replaceProvisionedThroughput |
| 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 CRUD Samples file shows how to perform the following tasks.
| Task | API reference |
|---|---|
| Create a database with specified autoscale max throughput | CosmosClient.createDatabase ThroughputProperties.createAutoscaledThroughput |
The autoscale Collection CRUD Samples file shows how to perform the following tasks.
| Task | API reference |
|---|---|
| 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 file shows how to perform the following tasks. To learn about the Azure Cosmos collections before running the following samples, read about Azure Cosmos DB Synapse and Analytical Store.
| Task | API reference |
|---|---|
| Create a collection | CosmosDatabase.createContainerIfNotExists |
Document examples
The Document CRUD Samples file shows how to perform the following tasks. To learn about the Azure Cosmos documents before running the following samples, see Working with databases, containers, and items conceptual article.
| Task | API reference |
|---|---|
| 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 | AccessCondition.setType AccessCondition.setCondition |
| Read document only if document has changed | AccessCondition.setType AccessCondition.setCondition |
| Partial document update | CosmosContainer.patchItem |
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 |
|---|---|
| Exclude a document from the index | ExcludedIndex IndexingPolicy |
| Use Lazy Indexing | IndexingPolicy.IndexingMode |
| 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 |
| Force a range scan operation on a hash indexed path | FeedOptions.EnableScanInQuery |
| Use range indexes on Strings | IndexingPolicy.IncludedPaths RangeIndex |
| Perform an index transform | - |
| Create a geospatial index | IndexingPolicy.setSpatialIndexes SpatialSpec SpatialType |
For more information about indexing, see Azure Cosmos DB indexing policies.
Query examples
The Query Samples file shows 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.
| Task | API reference |
|---|---|
| Query for all documents | CosmosContainer.queryItems |
| Query for equality using == | CosmosContainer.queryItems |
| Query for inequality using != and NOT | CosmosContainer.queryItems |
| Query using range operators like >, <, >=, <= | CosmosContainer.queryItems |
| Query using range operators against strings | CosmosContainer.queryItems |
| Query with ORDER BY | CosmosContainer.queryItems |
| Query with DISTINCT | CosmosContainer.queryItems |
| Query with aggregate functions | CosmosContainer.queryItems |
| Work with subdocuments | CosmosContainer.queryItems |
| Query with intra-document Joins | CosmosContainer.queryItems |
| Query with string, math, and array operators | CosmosContainer.queryItems |
| Query with parameterized SQL using SqlQuerySpec | CosmosContainer.queryItems |
| Query with explicit paging | CosmosContainer.queryItems |
| Query partitioned collections in parallel | CosmosContainer.queryItems |
| Query with ORDER BY for partitioned collections | CosmosContainer.queryItems |
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 a specific time | ChangeFeedProcessor.changeFeedProcessorBuilder |
| Read change feed from the beginning | - |
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 |
User management examples
The User Management Sample file shows how to do the following tasks:
| Task | API reference |
|---|---|
| Create a user | - |
| Set permissions on a collection or document | - |
| Get a list of a user's permissions | - |
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
Tilbakemeldinger
Send inn og vis tilbakemelding for