Azure Cosmos DB SQL API:Java SDK v4 示例Azure Cosmos DB SQL API: Java SDK v4 examples

重要

若要详细了解 Java SDK v4,请参阅 Azure Cosmos DB Java SDK v4 发行说明Maven 存储库、Azure Cosmos DB Java SDK v4 性能提示和 Azure Cosmos DB Java SDK v4 故障排除指南获取详细信息。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. 如果你当前使用的是早于 v4 的版本,请参阅迁移到 Azure Cosmos DB Java SDK v4 指南,获取升级到 v4 的相关帮助。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.

重要

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

可以使用 URI 为 https://localhost:8081Azure Cosmos DB 模拟器You can use the Azure Cosmos DB Emulator with a URI of https://localhost:8081. 有关在模拟器中使用的密钥,请参阅对请求进行身份验证For the key to use with the emulator, see Authenticating requests.

azure-cosmos-java-sql-api-samples GitHub 存储库中包含可对 Azure Cosmos DB 资源执行 CRUD 操作和其他常见操作的最新示例应用程序。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:

  • 每个示例 Java项目文件中各项任务的链接。Links to the tasks in each of the example Java project files.
  • 指向相关的 API 参考内容的链接。Links to the related API reference content.

先决条件Prerequisites

需要以下条件才能运行此示例应用程序:You need the following to run this sample application:

  • Java 开发工具包 8Java Development Kit 8
  • Azure Cosmos DB Java SDK v4Azure Cosmos DB Java SDK v4

可以选择使用 Maven 获取最新的 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 会自动添加任何必需的依赖项。Maven automatically adds any necessary dependencies. 否则,可以直接下载 pom.xml 文件中列出的依赖项并将它们添加到生成路径。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

可以使用 IDE(Eclipse、IntelliJ 或 VSCODE)或使用 Maven 从命令行运行示例。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 master key

才能使示例可以对你的帐户进行读/写访问。in order to give the samples read/write access to your account.

若要运行示例,请指定其 Main 类To run a sample, specify its Main Class

com.azure.cosmos.examples.sample.synchronicity.MainClass

其中 sample.synchronicity.MainClass 可以是where sample.synchronicity.MainClass can be

  • crudquickstart.sync.SampleCRUDQuickstartcrudquickstart.sync.SampleCRUDQuickstart
  • crudquickstart.async.SampleCRUDQuickstartAsynccrudquickstart.async.SampleCRUDQuickstartAsync
  • indexmanagement.sync.SampleIndexManagementindexmanagement.sync.SampleIndexManagement
  • indexmanagement.async.SampleIndexManagementAsyncindexmanagement.async.SampleIndexManagementAsync
  • storedprocedure.sync.SampleStoredProcedurestoredprocedure.sync.SampleStoredProcedure
  • storedprocedure.async.SampleStoredProcedureAsyncstoredprocedure.async.SampleStoredProcedureAsync
  • changefeed.SampleChangeFeedProcessor (Changefeed 只有一个异步示例,没有同步示例。) ...等等...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. 这些示例会发出多个调用以创建 CosmosContainerThe samples issue multiple calls to create a CosmosContainer. 每当执行此操作时,即会根据所创建的集合的性能层,对订阅收取使用 1 小时的费用。Each time this is done, your subscription is billed for 1 hour of usage for the performance tier of the collection created.

数据库示例Database examples

数据库 CRUD 示例文件演示如何执行以下任务。The Database CRUD Samples file shows how to perform the following tasks. 若要在运行以下示例之前了解 Azure Cosmos 数据库,请参阅使用数据库、容器和项概念性文章。To learn about the Azure Cosmos databases before running the following samples, see Working with databases, containers, and items conceptual article.

任务Task API 参考API reference
创建数据库Create a database CosmosClient.createDatabaseIfNotExistsCosmosClient.createDatabaseIfNotExists
按 ID 读取数据库Read a database by ID CosmosClient.getDatabaseCosmosClient.getDatabase
Read all the databasesRead all the databases CosmosClient.readAllDatabasesCosmosClient.readAllDatabases
删除数据库Delete a database CosmosDatabase.deleteCosmosDatabase.delete

集合示例Collection examples

集合 CRUD 示例文件演示如何执行以下任务。The Collection CRUD Samples file shows how to perform the following tasks. 若要在运行以下示例之前了解 Azure Cosmos 集合,请参阅使用数据库、容器和项概念性文章。To learn about the Azure Cosmos collections before running the following samples, see Working with databases, containers, and items conceptual article.

任务Task API 参考API reference
创建集合Create a collection CosmosDatabase.createContainerIfNotExistsCosmosDatabase.createContainerIfNotExists
Change configured performance of a collectionChange configured performance of a collection CosmosContainer.replaceProvisionedThroughputCosmosContainer.replaceProvisionedThroughput
按 ID 获取集合Get a collection by ID CosmosDatabase.getContainerCosmosDatabase.getContainer
Read all the collections in a databaseRead all the collections in a database CosmosDatabase.readAllContainersCosmosDatabase.readAllContainers
删除集合Delete a collection CosmosContainer.deleteCosmosContainer.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.

自动缩放数据库 CRUD 示例文件演示如何执行以下任务。The autoscale Database CRUD Samples file shows how to perform the following tasks.

任务Task API 参考API reference
创建具有指定自动缩放最大吞吐量的数据库Create a database with specified autoscale max throughput CosmosClient.createDatabaseCosmosClient.createDatabase
ThroughputProperties.createAutoscaledThroughputThroughputProperties.createAutoscaledThroughput

自动缩放集合 CRUD 示例文件演示如何执行以下任务。The autoscale Collection CRUD Samples file shows how to perform the following tasks.

任务Task API 参考API reference
创建具有指定自动缩放最大吞吐量的集合Create a collection with specified autoscale max throughput CosmosDatabase.createContainerIfNotExistsCosmosDatabase.createContainerIfNotExists
更改集合的已配置自动缩放最大吞吐量Change configured autoscale max throughput of a collection CosmosContainer.replaceThroughputCosmosContainer.replaceThroughput
读取集合的自动缩放吞吐量配置Read autoscale throughput configuration of a collection CosmosContainer.readThroughputCosmosContainer.readThroughput

分析存储集合示例Analytical storage collection examples

分析存储集合 CRUD 示例文件演示如何执行以下任务。The Analytical storage Collection CRUD Samples file shows how to perform the following tasks. 若要在运行以下示例之前了解 Azure Cosmos 集合,请阅读有关 Azure Cosmos DB Synapse 和分析存储的内容。To learn about the Azure Cosmos collections before running the following samples, read about Azure Cosmos DB Synapse and Analytical Store.

任务Task API 参考API reference
创建集合Create a collection CosmosDatabase.createContainerIfNotExistsCosmosDatabase.createContainerIfNotExists

文档示例Document examples

文档 CRUD 示例文件演示如何执行以下任务。The Document CRUD Samples file shows how to perform the following tasks. 若要在运行以下示例之前了解 Azure Cosmos 文档,请参阅使用数据库、容器和项概念性文章。To learn about the Azure Cosmos documents before running the following samples, see Working with databases, containers, and items conceptual article.

任务Task API 参考API reference
创建文档Create a document CosmosContainer.createItemCosmosContainer.createItem
按 ID 读取文档Read a document by ID CosmosContainer.readItemCosmosContainer.readItem
查询文档Query for documents CosmosContainer.queryItemsCosmosContainer.queryItems
替换文档Replace a document CosmosContainer.replaceItemCosmosContainer.replaceItem
更新插入文档Upsert a document CosmosContainer.upsertItemCosmosContainer.upsertItem
删除文档Delete a document CosmosContainer.deleteItemCosmosContainer.deleteItem
使用条件 ETag 检查替换文档Replace a document with conditional ETag check AccessCondition.setTypeAccessCondition.setType
AccessCondition.setConditionAccessCondition.setCondition
仅当文档已更改时读取文档Read document only if document has changed AccessCondition.setTypeAccessCondition.setType
AccessCondition.setConditionAccessCondition.setCondition

索引示例Indexing examples

集合 CRUD 示例文件演示如何执行以下任务。The Collection CRUD Samples file shows how to perform the following tasks. 若要在运行以下示例之前了解 Azure Cosmos DB 中的索引,请参阅索引策略索引类型索引路径概念文章。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 参考API reference
从索引中排除文档Exclude a document from the index ExcludedIndexExcludedIndex
IndexingPolicyIndexingPolicy
使用延迟索引Use Lazy Indexing IndexingPolicy.IndexingModeIndexingPolicy.IndexingMode
在索引中包括指定的文档路径Include specified documents paths in the index IndexingPolicy.IncludedPathsIndexingPolicy.IncludedPaths
从索引中排除指定的文档路径Exclude specified documents paths from the index IndexingPolicy.ExcludedPathsIndexingPolicy.ExcludedPaths
创建组合索引Create a composite index IndexingPolicy.setCompositeIndexesIndexingPolicy.setCompositeIndexes
CompositePathCompositePath
对哈希索引路径强制执行范围扫描操作Force a range scan operation on a hash indexed path FeedOptions.EnableScanInQueryFeedOptions.EnableScanInQuery
对字符串使用范围索引Use range indexes on Strings IndexingPolicy.IncludedPathsIndexingPolicy.IncludedPaths
RangeIndexRangeIndex
执行索引转换Perform an index transform -
创建地理空间索引Create a geospatial index IndexingPolicy.setSpatialIndexesIndexingPolicy.setSpatialIndexes
SpatialSpecSpatialSpec
SpatialTypeSpatialType

有关索引的详细信息,请参阅 Azure Cosmos DB 索引策略For more information about indexing, see Azure Cosmos DB indexing policies.

查询示例Query examples

查询示例文件演示如何使用 SQL 查询语法执行以下任务。The Query Samples file shows how to do the following tasks using the SQL query grammar. 若要在运行以下示例之前了解 Azure Cosmos DB 中的 SQL 查询引用,请参阅 Azure Cosmos DB 的 SQL 查询示例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 参考API reference
查询所有文档Query for all documents CosmosContainer.queryItemsCosmosContainer.queryItems
使用 == 查询等式Query for equality using == CosmosContainer.queryItemsCosmosContainer.queryItems
使用 != 和 NOT 查询不等式Query for inequality using != and NOT CosmosContainer.queryItemsCosmosContainer.queryItems
使用 >、<、>=、<= 等范围运算符进行查询Query using range operators like >, <, >=, <= CosmosContainer.queryItemsCosmosContainer.queryItems
使用范围运算符对字符串进行查询Query using range operators against strings CosmosContainer.queryItemsCosmosContainer.queryItems
使用 ORDER BY 进行查询Query with ORDER BY CosmosContainer.queryItemsCosmosContainer.queryItems
使用 DISTINCT 查询Query with DISTINCT CosmosContainer.queryItemsCosmosContainer.queryItems
使用聚合函数进行查询Query with aggregate functions CosmosContainer.queryItemsCosmosContainer.queryItems
使用子文档Work with subdocuments CosmosContainer.queryItemsCosmosContainer.queryItems
使用文档内联接进行查询Query with intra-document Joins CosmosContainer.queryItemsCosmosContainer.queryItems
使用字符串、数学和数组运算符进行查询Query with string, math, and array operators CosmosContainer.queryItemsCosmosContainer.queryItems
通过使用 SqlQuerySpec 的参数化 SQL 进行查询Query with parameterized SQL using SqlQuerySpec CosmosContainer.queryItemsCosmosContainer.queryItems
使用显式分页进行查询Query with explicit paging CosmosContainer.queryItemsCosmosContainer.queryItems
并行查询已分区集合Query partitioned collections in parallel CosmosContainer.queryItemsCosmosContainer.queryItems
使用 ORDER BY 针对已分区集合进行查询Query with ORDER BY for partitioned collections CosmosContainer.queryItemsCosmosContainer.queryItems

更改源示例Change feed examples

更改源处理器示例文件演示如何执行以下任务。The Change Feed Processor Sample file shows how to do the following tasks. 若要在运行以下示例之前了解 Azure Cosmos DB 中的更改源,请参阅读取 Azure Cosmos DB 更改源更改源处理器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 参考API reference
基本的更改源功能Basic change feed functionality ChangeFeedProcessor.changeFeedProcessorBuilderChangeFeedProcessor.changeFeedProcessorBuilder
读取特定时间的更改源Read change feed from a specific time ChangeFeedProcessor.changeFeedProcessorBuilderChangeFeedProcessor.changeFeedProcessorBuilder
从头读取更改源Read change feed from the beginning -

服务器端编程示例Server-side programming examples

存储过程示例文件演示如何执行以下任务。The Stored Procedure Sample file shows how to do the following tasks. 若要在运行以下示例之前了解 Azure Cosmos DB 中的服务器端编程,请参阅存储过程、触发器和用户定义的函数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 参考API reference
创建存储过程Create a stored procedure CosmosScripts.createStoredProcedureCosmosScripts.createStoredProcedure
执行存储过程Execute a stored procedure CosmosStoredProcedure.executeCosmosStoredProcedure.execute
删除存储过程Delete a stored procedure CosmosStoredProcedure.deleteCosmosStoredProcedure.delete

用户管理示例User management examples

用户管理示例文件演示如何执行以下任务:The User Management Sample file shows how to do the following tasks:

任务Task API 参考API reference
创建用户Create a user -
对集合或文档设置权限Set permissions on a collection or document -
获取用户权限列表Get a list of a user's permissions -