快速入門:建置 JAVA 應用程式來管理 Azure Cosmos DB SQL API 資料Quickstart: Build a Java app to manage Azure Cosmos DB SQL API data

本快速入門說明如何使用 Java 應用程式,從您的 Azure Cosmos DB SQL API 帳戶建立和管理文件資料庫。This quickstart shows you how to use a Java application to create and manage a document database from your Azure Cosmos DB SQL API account. 首先,您必須使用 Azure 入口網站建立 Azure Cosmos DB SQL API 帳戶、使用 SQL Java SDK 建立 Java 應用程式,然後使用 Java 應用程式將資源新增至您的 Cosmos DB 帳戶。First, you create an Azure Cosmos DB SQL API account using the Azure portal, create a Java app using the SQL Java SDK, and then add resources to your Cosmos DB account by using the Java application. 本快速入門中的指示可運用在任何足以執行 Java 應用程式的作業系統上。The instructions in this quickstart can be followed on any operating system that is capable of running Java. 完成本快速入門之後,您就會熟悉如何在 UI 中或以程式設計方式建立和修改 Cosmos DB 資料庫和容器 (不論您偏好哪種方式)。After completing this quickstart you'll be familiar with creating and modifying Cosmos DB databases, containers in either the UI or programmatically, whichever is your preference.

必要條件Prerequisites

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.

您可以免費試用 Azure Cosmos DB,無須 Azure 訂用帳戶,也無須任何費用和約定付款。You can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments. 或者,您也可以搭配使用 Azure Cosmos DB 模擬器https://localhost:8081 的 URI。Or, you can use the Azure Cosmos DB Emulator with a URI of https://localhost:8081. 驗證要求中會提供主索引鍵。The Primary Key is provided in Authenticating requests.

此外:In addition:

  • JAVA 開發套件 (JDK) 8 版 (英文)Java Development Kit (JDK) version 8
    • 務必設定 JAVA_HOME 環境變數,以指向 JDK 安裝所在的資料夾。Be sure to set the JAVA_HOME environment variable to point to the folder where the JDK is installed.
  • 下載安裝 Maven 二進位封存檔Download and install a Maven binary archive
    • 在 Ubuntu 上,您可以執行 apt-get install maven 來安裝 Maven。On Ubuntu, you can run apt-get install maven to install Maven.
  • GitGit
    • 在 Ubuntu 上,您可以執行 sudo apt-get install git 來安裝 Git。On Ubuntu, you can run sudo apt-get install git to install Git.

建立資料庫帳戶Create a database account

您必須先使用 Azure Cosmos DB 建立 SQL API 帳戶,才可以建立文件資料庫。Before you can create a document database, you need to create a SQL API account with Azure Cosmos DB.

  1. 登入 Azure 入口網站Sign in to the Azure portal.

  2. 選取 [建立資源] > [資料庫] > [Azure Cosmos DB] 。Select Create a resource > Databases > Azure Cosmos DB.

    Azure 入口網站資料庫窗格

  3. 在 [建立 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
    SubscriptionSubscription 訂用帳戶名稱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 輸入唯一名稱Enter a unique name 輸入名稱來識別您的 Azure Cosmos 帳戶。Enter a name to identify your Azure Cosmos account. 因為 documents.azure.com 會附加到您所提供的識別碼以建立 URI,請使用唯一識別碼。Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    識別碼只能包含小寫字母、數字及連字號 (-) 字元。The ID can only contain lowercase letters, numbers, and the hyphen (-) character. 其長度必須介於 3 到 31 個字元之間。It must be between 3-31 characters in length.
    APIAPI Core (SQL)Core (SQL) 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.

    選取 [Core(SQL)] ,以使用 SQL 語法建立文件資料庫並進行查詢。Select Core (SQL) to create a document database and query by using SQL syntax.

    進一步了解 SQL APILearn more about the SQL API.
    LocationLocation 選取最接近使用者的區域Select 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.

    Azure Cosmos DB 的新帳戶頁面

  4. 選取 [檢閱 + 建立] 。Select Review + create. 您可以略過 [網路] 和 [標記] 區段。You can skip the Network and Tags sections.

  5. 檢閱帳戶設定,然後選取 [建立] 。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 入口網站的 [通知] 窗格

  6. 選取 [移至資源] 以移至 Azure Cosmos DB 帳戶頁面。Select Go to resource to go to the Azure Cosmos DB account page.

    Azure Cosmos DB 帳戶頁面

新增容器Add a container

您現在可以在 Azure 入口網站中使用 [資料總管] 工具,建立資料庫和容器。You can now use the Data Explorer tool in the Azure portal to create a database and container.

  1. 選取 [資料總管] > [新增容器] 。Select Data Explorer > New Container.

    [新增容器] 區域會顯示在最右邊,您可能需要向右捲動才能看到它。The Add Container area is displayed on the far right, you may need to scroll right to see it.

    Azure 入口網站資料總管,[新增容器] 窗格

  2. 在 [新增容器] 頁面上,輸入新容器的設定。In the Add container page, enter the settings for the new container.

    設定Setting 建議的值Suggested value 說明Description
    資料庫識別碼Database ID 工作Tasks 輸入 ToDoList 作為新資料庫的名稱。Enter ToDoList as the name for the new database. 資料庫名稱必須包含從 1 到 255 個字元,且不能包含 /, \\, #, ? 或尾端空格。Database names must contain from 1 through 255 characters, and they cannot contain /, \\, #, ?, or a trailing space. 核取 [佈建資料庫輸送量] 選項,它可讓您在資料庫中的所有容器內共用佈建到資料庫的輸送量。Check the Provision database throughput option, it allows you to share the throughput provisioned to the database across all the containers within the database. 此選項也有助於節省成本。This option also helps with cost savings.
    輸送量Throughput 400400 讓輸送量保持在每秒 400 個要求單位 (RU/秒)。Leave the throughput at 400 request units per second (RU/s). 如果您想要降低延遲,稍後可以相應增加輸送量。If you want to reduce latency, you can scale up the throughput later.
    容器識別碼Container ID 項目Items 輸入 Items 作為新容器的名稱。Enter Items as the name for your new container. 容器識別碼與資料庫名稱具有相同的字元需求。Container IDs have the same character requirements as database names.
    分割區索引鍵Partition key /類別/category 本文中所述的範例使用 /category 作為分割區索引鍵。The sample described in this article uses /category as the partition key.

    除了上述的設定,您可以選擇性地為容器新增 [唯一索引鍵] 。In addition to the preceding settings, you can optionally add Unique keys for the container. 在此範例中,讓我們將欄位保留空白。Let's leave the field empty in this example. 唯一索引鍵可讓開發人員在資料庫中新增一層資料完整性。Unique keys provide developers with the ability to add a layer of data integrity to the database. 您可在建立容器時建立唯一索引鍵原則,以確保每個資料分割索引鍵一或多個值的唯一性。By creating a unique key policy while creating a container, you ensure the uniqueness of one or more values per partition key. 若要深入了解,請參閱 Azure Cosmos DB 中的唯一索引鍵一文。To learn more, refer to the Unique keys in Azure Cosmos DB article.

    選取 [確定] 。Select OK. [資料總管] 會顯示新的資料庫和容器。The Data Explorer displays the new database and container.

新增範例資料Add sample data

您現在可以使用 [資料總管] 將資料新增至您的新容器。You can now add data to your new container using Data Explorer.

  1. 在 [資料總管] 中,展開 Tasks 資料庫,然後展開 Items 容器。From the Data Explorer, expand the Tasks database, expand the Items container. 選取 [項目] ,然後選取 [新增項目] 。Select Items, and then select New Item.

    在 Azure 入口網站的 [資料總管] 中建立新文件

  2. 現在將文件新增至具有下列結構的容器。Now add a document to the container with the following structure.

    {
        "id": "1",
        "category": "personal",
        "name": "groceries",
        "description": "Pick up apples and strawberries.",
        "isComplete": false
    }
    
  3. 將 json 新增至 [文件] 索引標籤後,選取 [儲存] 。Once you've added the json to the Documents tab, select Save.

    將 json 資料複製在 Azure 入口網站的 [資料總管] 中並選取 [儲存]

  4. 多建立並儲存一份文件,以便在其中插入 id 屬性的唯一值,並適當變更其他屬性。Create and save one more document where you insert a unique value for the id property, and change the other properties as you see fit. 新文件可擁有您想要的任何結構,因為 Azure Cosmos DB 不會對您的資料強加任何結構描述。Your new documents can have any structure you want as Azure Cosmos DB doesn't impose any schema on your data.

查詢資料Query your data

您可以在 [資料總管] 中,使用查詢來擷取和篩選您的資料。You can use queries in Data Explorer to retrieve and filter your data.

  1. 在 [資料總管] 中的 [文件] 索引標籤頂端,檢閱預設查詢 SELECT * FROM cAt the top of the Documents tab in Data Explorer, review the default query SELECT * FROM c. 此查詢會依照識別碼順序擷取並顯示集合中的所有文件。This query retrieves and displays all documents in the collection in ID order.

    [資料總管] 中的預設查詢為 SELECT * FROM c

  2. 若要變更查詢,請選取 [編輯篩選條件] ,以 ORDER BY c._ts DESC 取代預設查詢,然後選取 [套用篩選條件] 。To change the query, select Edit Filter, replace the default query with ORDER BY c._ts DESC, and then select Apply Filter.

    新增 ORDER BY c._ts DESC 並按一下 [套用篩選],以變更預設查詢

    經過修改的查詢會根據文件的時間戳記,依遞減順序顯示文件,因此現會最先列出您的第二份文件。The modified query displays the documents in descending order based on their time stamp, so now your second document is listed first.

    已將查詢變更為 ORDER BY c._ts DESC 並按一下 [套用篩選]

若您熟悉 SQL 語法,則可在查詢述詞方塊中輸入任何支援的 SQL 查詢If you're familiar with SQL syntax, you can enter any supported SQL queries in the query predicate box. 您也可以使用 [資料總管] 來建立伺服器端商務邏輯的預存程序、UDF 和觸發程序。You can also use Data Explorer to create stored procedures, UDFs, and triggers for server-side business logic.

[資料總管] 可讓您透過 Azure 入口網站輕鬆存取 API 中所有可用的內建程式設計資料存取功能。Data Explorer provides easy Azure portal access to all of the built-in programmatic data access features available in the APIs. 您也可以使用入口網站來調整輸送量、取得金鑰和連接字串,以及檢閱 Azure Cosmos DB 帳戶的計量和 SLA。You also use the portal to scale throughput, get keys and connection strings, and review metrics and SLAs for your Azure Cosmos DB account.

複製範例應用程式Clone the sample application

現在讓我們切換為使用程式碼。Now let's switch to working with code. 我們將從 GitHub 複製 SQL API 應用程式、設定連接字串,然後加以執行。Let's clone a SQL API app from GitHub, set the connection string, and run it. 您會看到,以程式設計方式來處理資料有多麼的容易。You'll see how easy it is to work with data programmatically.

  1. 執行下列命令來複製範例存放庫。Run the following command to clone the sample repository. 此命令會在您的電腦上建立範例應用程式副本。This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-sql-api-async-java-getting-started
    

檢閱程式碼Review the code

此為選用步驟。This step is optional. 若您想要瞭解如何在程式碼中建立資料庫資源,則可檢閱下列程式碼片段。If you're interested in learning how the database resources are created in the code, you can review the following snippets. 或是,您可以直接跳到執行應用程式Otherwise, you can skip ahead to Run the app .

  • AsyncDocumentClient 初始化。AsyncDocumentClient initialization. AsyncDocumentClient 提供適用於 Azure Cosmos 資料庫服務的用戶端邏輯表示法。The AsyncDocumentClient provides client-side logical representation for the Azure Cosmos database service. 此用戶端會用於設定和執行針對服務的要求。This client is used to configure and execute requests against the service.

    client = new AsyncDocumentClient.Builder()
             .withServiceEndpoint(YOUR_COSMOS_DB_ENDPOINT)
             .withMasterKeyOrResourceToken(YOUR_COSMOS_DB_MASTER_KEY)
             .withConnectionPolicy(ConnectionPolicy.GetDefault())
             .withConsistencyLevel(ConsistencyLevel.Eventual)
             .build();
    
  • 資料庫建立。Database creation.

    Database databaseDefinition = new Database();
    databaseDefinition.setId(databaseName);
    
    client.createDatabase(databaseDefinition, null)
            .toCompletable()
            .await();
    
  • DocumentCollection 建立。DocumentCollection creation.

    DocumentCollection collectionDefinition = new DocumentCollection();
    collectionDefinition.setId(collectionName);
    
    //...
    
    client.createCollection(databaseLink, collectionDefinition, requestOptions)
            .toCompletable()
            .await();
    
  • 使用 createDocument 方法建立文件。Document creation by using the createDocument method.

    // Any Java object within your code
    // can be serialized into JSON and written to Azure Cosmos DB
    Family andersenFamily = new Family();
    andersenFamily.setId("Andersen.1");
    andersenFamily.setLastName("Andersen");
    // More properties
    
    String collectionLink = String.format("/dbs/%s/colls/%s", databaseName, collectionName);
    client.createDocument(collectionLink, family, null, true)
            .toCompletable()
            .await();
    
    
  • 使用 queryDocuments 方法,透過 JSON 執行 SQL 查詢。SQL queries over JSON are performed using the queryDocuments method.

    FeedOptions queryOptions = new FeedOptions();
    queryOptions.setPageSize(-1);
    queryOptions.setEnableCrossPartitionQuery(true);
    queryOptions.setMaxDegreeOfParallelism(-1);
    
    String collectionLink = String.format("/dbs/%s/colls/%s",
            databaseName,
            collectionName);
    Iterator<FeedResponse<Document>> it = client.queryDocuments(
            collectionLink,
            "SELECT * FROM Family WHERE Family.lastName = 'Andersen'",
            queryOptions).toBlocking().getIterator();
    
    System.out.println("Running SQL query...");
    while (it.hasNext()) {
        FeedResponse<Document> page = it.next();
        System.out.println(
                String.format("\tRead a page of results with %d items",
                        page.getResults().size()));
        for (Document doc : page.getResults()) {
            System.out.println(String.format("\t doc %s", doc));
        }
    }
    

執行應用程式Run the app

現在,返回 Azure 入口網站以取得連接字串資訊,然後使用端點資訊啟動應用程式。Now go back to the Azure portal to get your connection string information and launch the app with your endpoint information. 這可讓您的應用程式與託管資料庫進行通訊。This enables your app to communicate with your hosted database.

  1. 在 git 終端機視窗中,cd 至範例程式碼資料夾。In the git terminal window, cd to the sample code folder.

    cd azure-cosmos-db-sql-api-async-java-getting-started/azure-cosmosdb-get-started
    
  2. 在 git 終端機視窗中,使用下列命令來安裝必要的 Java 套件。In the git terminal window, use the following command to install the required Java packages.

    mvn package
    
  3. 在 git 終端機視窗中,使用下列命令啟動 Java 應用程式 (請將 YOUR_COSMOS_DB_HOSTNAME 取代為入口網站中加上引號的 URI 值,並將 YOUR_COSMOS_DB_MASTER_KEY 取代為入口網站中加上引號的主要金鑰)In the git terminal window, use the following command to start the Java application (replace YOUR_COSMOS_DB_HOSTNAME with the quoted URI value from the portal, and replace YOUR_COSMOS_DB_MASTER_KEY with the quoted primary key from portal)

    mvn exec:java -DACCOUNT_HOST=YOUR_COSMOS_DB_HOSTNAME -DACCOUNT_KEY=YOUR_COSMOS_DB_MASTER_KEY
    
    

    終端機視窗會顯示已建立 FamilyDB 資料庫的通知。The terminal window displays a notification that the FamilyDB database was created.

  4. 請按任一按鍵來建立資料庫,然後按下另一個按鍵來建立集合。Press a key to create the database, and then another key to create the collection.

    切換回瀏覽器中的資料總管,您會看到資料總管中現在已包含 FamilyDB 資料庫和 FamilyCollection 集合。Switch back to Data Explorer in your browser to see that it now contains a FamilyDB database, and FamilyCollection collection.

  5. 切換至 [主控台] 視窗,然後按下任一按鍵來建立第一個文件,然後按下另一個按鍵以建立第二個文件。Switch to the console window and press a key to create the first document, and then another key to create the second document. 然後切換回資料總管以檢視這些文件。Then switch back to Data Explorer to view them.

  6. 按下任一按鍵以執行查詢,並在 [主控台] 視窗中查看輸出。Press a key to run a query and see the output in the console window.

  7. 應用程式並不會刪除已建立的資源。The app doesn't delete the created resources. 切換回入口網站,從您的帳戶中清除資源Switch back to the portal to clean up the resources. 以免產生費用。from your account so that you don't incur charges.

    主控台輸出

在 Azure 入口網站中檢閱 SLAReview SLAs in the Azure portal

Azure 入口網站會監視您的 Cosmos DB 帳戶輸送量、儲存體、可用性、延遲和一致性。The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Azure Cosmos DB 服務等級協定 (SLA) 相關聯的計量圖表會顯示相較於實際效能的 SLA 值。Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. 此計量套件可讓您以更透明的方式監視監視 SLA。This suite of metrics makes monitoring your SLAs transparent.

若要檢閱計量和 SLA:To review metrics and SLAs:

  1. 在您的 Cosmos DB 帳戶導覽功能表中,選取 [計量] 。Select Metrics in your Cosmos DB account's navigation menu.

  2. 選取一個索引標籤 (例如 [延遲] ),並在右側選取時間範圍。Select a tab such as Latency, and select a timeframe on the right. 比較圖表中的實際SLA 的資料行。Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB 計量套件

  3. 檢閱其他索引標籤中的計量。Review the metrics on the other tabs.

清除資源Clean up resources

完成您的 Web 應用程式和 Azure Cosmos DB 帳戶之後,您可以將建立的 Azure 資源刪除,以免產生更多費用。When you're done with your web app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. 若要刪除資源:To delete the resources:

  1. 在 Azure 入口網站中,選取最左邊的 [資源群組] 。In the Azure portal, select Resource groups on the far left. 若已摺疊左側功能表,請選取展開按鈕加以展開。If the left menu is collapsed, select Expand button to expand it.

  2. 選取您在本快速入門中建立的資源群組。Select the resource group you created for this quickstart.

    Azure 入口網站中的計量

  3. 在新視窗中,選取 [刪除資源群組] 。In the new window, select Delete resource group.

    Azure 入口網站中的計量

  4. 在下個視窗中輸入要刪除的資源群組名稱,然後選取 [刪除] 。In the next window, enter the name of the resource group to delete, and then select Delete.

後續步驟Next steps

在本快速入門中,您已了解如何使用 [資料總管] 來建立 Azure Cosmos 帳戶、文件資料庫和容器,以及如何執行應用程式來以程式設計方式執行同樣的作業。In this quickstart, you've learned how to create an Azure Cosmos account, document database, and container using the Data Explorer, and run an app to do the same thing programmatically. 您現可將其他資料匯入至 Azure Cosmos 容器。You can now import additional data into your Azure Cosmos container.