NoSQL 教程:构建 SQL API Java 控制台应用程序NoSQL tutorial: Build a SQL API Java console application

欢迎使用适用于 Azure Cosmos DB Java SDK 的 SQL API 的 NoSQL 教程!Welcome to the NoSQL tutorial for the SQL API for Azure Cosmos DB Java SDK! 学习本教程后,将拥有一个可创建并查询 Azure Cosmos DB 资源的控制台应用程序。After following this tutorial, you'll have a console application that creates and queries Azure Cosmos DB resources.

我们介绍:We cover:

  • 创建并连接到 Azure Cosmos DB 帐户Creating and connecting to an Azure Cosmos DB account
  • 配置 Visual Studio 解决方案Configuring your Visual Studio Solution
  • 创建联机数据库Creating an online database
  • 创建集合Creating a collection
  • 创建 JSON 文档Creating JSON documents
  • 查询集合Querying the collection
  • 创建 JSON 文档Creating JSON documents
  • 查询集合Querying the collection
  • 替换文档Replacing a document
  • 删除文档Deleting a document
  • 删除数据库Deleting the database

现在,让我们开始吧!Now let's get started!

先决条件Prerequisites

确保具有以下内容:Make sure you have the following:

步骤 1:创建 Azure Cosmos DB 帐户Step 1: Create an Azure Cosmos DB account

创建 Azure Cosmos DB 帐户。Let's create an Azure Cosmos DB account. 如果已有一个可用的帐户,可以直接跳到克隆 GitHub 项目If you already have an account you want to use, you can skip ahead to Clone the GitHub project. 如果使用 Azure Cosmos DB 模拟器,请遵循 Azure Cosmos DB 模拟器中的步骤设置该模拟器,并直接跳到克隆 GitHub 项目If you are using the Azure Cosmos DB Emulator, follow the steps at Azure Cosmos DB Emulator to set up the emulator and skip ahead to Clone the GitHub project.

  1. 转到 Azure 门户以创建 Azure Cosmos DB 帐户。Go to the Azure portal to create an Azure Cosmos DB account. 在你的主页上,从“Azure 服务” 面板中选择“创建资源” 。At your homepage choose Create a resource from the Azure services panel.

    创建资源

  2. 搜索“Azure Cosmos DB”,然后选择它。 。Search for and select Azure Cosmos DB.

    Azure 门户资源下拉列表

  3. 选择“创建” 。Select Create.

    创建 Azure Cosmos DB 资源

  4. 在“创建 Azure Cosmos DB 帐户”页上,输入新 Azure Cosmos 帐户的基本设置 。On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos account.

    设置Setting Value 说明Description
    订阅Subscription 订阅名称Subscription name 选择要用于此 Azure Cosmos 帐户的 Azure 订阅。Select the Azure subscription that you want to use for this Azure Cosmos account.
    资源组Resource Group 资源组名称Resource group name 选择一个资源组,或者选择“新建”,然后输入新资源组的唯一名称。 Select a resource group, or select Create new, then enter a unique name for the new resource group.
    帐户名Account Name 唯一的名称A unique name 输入标识此 Azure Cosmos 帐户的名称。Enter a name to identify your Azure Cosmos account. 由于 documents.azure.cn 将追加到所提供的名称以创建 URI,因此,请使用唯一的名称 。Because documents.azure.cn is appended to the name that you provide to create your URI, use a unique name.

    名称只能包含小写字母、数字和连字符 (-) 字符。The name can only contain lowercase letters, numbers, and the hyphen (-) character. 它的长度必须介于 3 到 31 个字符之间。It must be between 3-31 characters in length.
    APIAPI 要创建的帐户的类型The type of account to create 选择“Core (SQL)”,以便使用 SQL 语法创建文档数据库并进行查询 。Select Core (SQL) to create a document database and query by using SQL syntax.

    API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据的 Core (SQL) 和 MongoDB、适用于图形数据的 Gremlin、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.

    详细了解 SQL APILearn more about the SQL API.
    应用免费层折扣Apply Free Tier Discount 应用或不应用Apply or Do not apply 使用 Azure Cosmos DB 免费层,你将在帐户中获得每秒的前 400 RU 免费的吞吐量和 5 GB 的免费存储。With Azure Cosmos DB free tier, you will get the first 400 RU/s and 5 GB of storage for free in an account. 了解免费层的详细信息。Learn more about free tier.
    位置Location 离用户最近的区域The region closest to your users 选择用于托管 Azure Cosmos DB 帐户的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用离用户最近的位置,使他们能够以最快的速度访问数据。Use the location that is closest to your users to give them the fastest access to the data.
    帐户类型Account Type 生产或非生产Production or Non-Production 如果帐户将用于生产工作负荷,请选择“生产” 。Select Production if the account will be used for a production workload. 如果帐户将用于非生产环境(例如开发、测试、QA 或过渡),请选择“非生产” 。Select Non-Production if the account will be used for non-production, e.g. development, testing, QA, or staging. 这是一个 Azure 资源标记设置,用于调整门户体验,但不会影响基础 Azure Cosmos DB 帐户。This is an Azure resource tag setting that tunes the Portal experience but does not affect the underlying Azure Cosmos DB account. 可以随时更改此值。You can change this value anytime.

    Note

    每个 Azure 订阅最多可以有一个免费层 Azure Cosmos DB 帐户,并且你必须在创建帐户时选择加入使用。You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. 如果看不到用于应用免费层折扣的选项,这意味着订阅中的另一个帐户已启用免费层。If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    Azure Cosmos DB 的“新建帐户”页

  5. 选择“查看 + 创建” 。Select Review + create. 可以跳过“网络”和“标记”部分 。You can skip the Network and Tags sections.

  6. 检查帐户设置,然后选择“创建”。 Review the account settings, and then select Create. 创建帐户需要几分钟时间。It takes a few minutes to create the account. 等待门户页显示“你的部署已完成” 消息。Wait for the portal page to display Your deployment is complete.

    Azure 门户“通知”窗格

  7. 选择“转到资源”,转到 Azure Cosmos DB 帐户页。 Select Go to resource to go to the Azure Cosmos DB account page.

    Azure Cosmos DB 帐户页

步骤 2:克隆 GitHub 项目Step 2: Clone the GitHub project

首先,可以根据 Get Started with Azure Cosmos DB and Java(Azure Cosmos DB 和 Java 入门)中所述克隆 GitHub 存储库。You can get started by cloning the GitHub repository for Get Started with Azure Cosmos DB and Java. 例如,从本地目录运行以下命令,在本地检索示例项目。For example, from a local directory run the following to retrieve the sample project locally.

git clone git@github.com:Azure-Samples/azure-cosmos-db-documentdb-java-getting-started.git

cd azure-cosmos-db-documentdb-java-getting-started

该目录包含项目的 pom.xml,以及含有 Java 源代码的 src 文件夹,其中包括 Program.java,说明如何使用 Azure Cosmos DB 执行简单的操作,例如创建文档以及查询集合中的数据。The directory contains a pom.xml for the project and a src folder containing Java source code including Program.java which shows how perform simple operations with Azure Cosmos DB like creating documents and querying data within a collection. pom.xml 依赖于 Maven 上的 Azure Cosmos DB Java SDKThe pom.xml includes a dependency on the Azure Cosmos DB Java SDK on Maven.

<dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>azure-documentdb</artifactId>
    <version>LATEST</version>
</dependency>

步骤 3:连接到 Azure Cosmos DB 帐户Step 3: Connect to an Azure Cosmos DB account

接下来,返回到 Azure 门户检索终结点和主密钥。Next, head back to the Azure portal to retrieve your endpoint and primary master key. Azure Cosmos DB 终结点和主密钥是必需的,可让应用程序知道要连接的对象,使 Azure Cosmos DB 信任应用程序的连接。The Azure Cosmos DB endpoint and primary key are necessary for your application to understand where to connect to, and for Azure Cosmos DB to trust your application's connection.

在 Azure 门户中,导航到 Azure Cosmos DB 帐户,然后单击“密钥” 。In the Azure portal, navigate to your Azure Cosmos DB account, and then click Keys. 从门户复制 URI,并将其粘贴到 Program.java 文件的 https://FILLME.documents.azure.cn 中。Copy the URI from the portal and paste it into https://FILLME.documents.azure.cn in the Program.java file. 然后从门户中复制“主密钥”并将它粘贴到 FILLMEThen copy the PRIMARY KEY from the portal and paste it into FILLME.

this.client = new DocumentClient(
    "https://FILLME.documents.azure.cn",
    "FILLME"
    , new ConnectionPolicy(),
    ConsistencyLevel.Session);

NoSQL 教程用于创建 Java 控制台应用程序的 Azure 门户的屏幕截图。

步骤 4:创建数据库Step 4: Create a database

可以使用 DocumentClient 类的 createDatabase 方法创建 Azure Cosmos DB 数据库Your Azure Cosmos DB database can be created by using the createDatabase method of the DocumentClient class. 数据库是跨集合分区的 JSON 文档存储的逻辑容器。A database is the logical container of JSON document storage partitioned across collections.

Database database = new Database();
database.setId("familydb");
this.client.createDatabase(database, null);

步骤 5:创建集合Step 5: Create a collection

Warning

createCollection 创建一个具有保留吞吐量的新集合,它牵涉定价。createCollection creates a new collection with reserved throughput, which has pricing implications. 有关详细信息,请访问定价页For more details, visit our pricing page.

可以使用 DocumentClient 类的 createCollection 方法创建集合。A collection can be created by using the createCollection method of the DocumentClient class. 集合是 JSON 文档和相关联的 JavaScript 应用程序逻辑的容器。A collection is a container of JSON documents and associated JavaScript application logic.

DocumentCollection collectionInfo = new DocumentCollection();
collectionInfo.setId("familycoll");

// Azure Cosmos containers can be reserved with throughput specified in request units/second. 
// Here we create a collection with 400 RU/s.
RequestOptions requestOptions = new RequestOptions();
requestOptions.setOfferThroughput(400);

this.client.createCollection("/dbs/familydb", collectionInfo, requestOptions);

步骤 6:创建 JSON 文档Step 6: Create JSON documents

可以使用 DocumentClient 类的 createDocument 方法创建文档。A document can be created by using the createDocument method of the DocumentClient class. 文档是用户定义的(任意)JSON 内容。Documents are user-defined (arbitrary) JSON content. 现在,我们可以插入一个或多个文档。We can now insert one or more documents. 如果已有要在数据库中存储的数据,则可以使用 Azure Cosmos DB 的数据迁移工具将数据导入数据库。If you already have data you'd like to store in your database, you can use Azure Cosmos DB's Data Migration tool to import the data into a database.

// Insert your Java objects as documents 
Family andersenFamily = new Family();
andersenFamily.setId("Andersen.1");
andersenFamily.setLastName("Andersen")

// More initialization skipped for brevity. You can have nested references
andersenFamily.setParents(new Parent[] { parent1, parent2 });
andersenFamily.setDistrict("WA5");
Address address = new Address();
address.setCity("Seattle");
address.setCounty("King");
address.setState("WA");

andersenFamily.setAddress(address);
andersenFamily.setRegistered(true);

this.client.createDocument("/dbs/familydb/colls/familycoll", family, new RequestOptions(), true);

说明 NoSQL 教程创建 Java 控制台应用程序所用帐户、联机数据库、集合和文档的层次关系的图表

步骤 7:查询 Azure Cosmos DB 资源Step 7: Query Azure Cosmos DB resources

Azure Cosmos DB 支持对存储在每个集合中的 JSON 文档进行各种查询Azure Cosmos DB supports rich queries against JSON documents stored in each collection. 以下示例代码展示了如何将 SQL 语法与 queryDocuments 方法一起使用来查询 Azure Cosmos DB 中的文档。The following sample code shows how to query documents in Azure Cosmos DB using SQL syntax with the queryDocuments method.

FeedResponse<Document> queryResults = this.client.queryDocuments(
    "/dbs/familydb/colls/familycoll",
    "SELECT * FROM Family WHERE Family.lastName = 'Andersen'", 
    null);

System.out.println("Running SQL query...");
for (Document family : queryResults.getQueryIterable()) {
    System.out.println(String.format("\tRead %s", family));
}

步骤 8:替换 JSON 文档Step 8: Replace JSON document

Azure Cosmos DB 支持使用 replaceDocument 方法更新 JSON 文档。Azure Cosmos DB supports updating JSON documents using the replaceDocument method.

// Update a property
andersenFamily.Children[0].Grade = 6;

this.client.replaceDocument(
    "/dbs/familydb/colls/familycoll/docs/Andersen.1", 
    andersenFamily,
    null);

步骤 9:删除 JSON 文档Step 9: Delete JSON document

Azure Cosmos DB 支持使用 deleteDocument 方法更新 JSON 文档。Similarly, Azure Cosmos DB supports deleting JSON documents using the deleteDocument method.

this.client.delete("/dbs/familydb/colls/familycoll/docs/Andersen.1", null);

步骤 10:删除数据库Step 10: Delete the database

删除已创建的数据库将删除该数据库及其所有子资源(集合、文档等)。Deleting the created database removes the database and all children resources (collections, documents, etc.).

this.client.deleteDatabase("/dbs/familydb", null);

步骤 11:一起运行 Java 控制台应用程序!Step 11: Run your Java console application all together!

若要从控制台运行应用程序,请导航到项目文件夹,然后使用 Maven 进行编译:To run the application from the console, navigate to the project folder and compile using Maven:

mvn package

运行 mvn package 可从 Maven 下载最新的 Azure Cosmos DB 库,并生成 GetStarted-0.0.1-SNAPSHOT.jarRunning mvn package downloads the latest Azure Cosmos DB library from Maven and produces GetStarted-0.0.1-SNAPSHOT.jar. 然后,通过运行以下命令来运行该应用:Then run the app by running:

mvn exec:java -D exec.mainClass=GetStarted.Program

祝贺!Congratulations! 已经完成本 NoSQL 教程,并且获得了一个可正常使用的 Java 控制台应用程序!You've completed this NoSQL tutorial and have a working Java console application!

后续步骤Next steps