快速入門:使用 Java SDK 和 Azure Cosmos DB 資料表 API 來建置圖形資料庫Quickstart: Build a graph database with the Java SDK and the Azure Cosmos DB Table API

Azure Cosmos DB 是 Microsoft 的全域分散式多模型資料庫服務。Azure Cosmos DB is Microsoft’s globally distributed multi-model database service. 您可使用 Azure Cosmos DB 快速地建立和查詢受控文件、資料表及圖形資料庫。Using Azure Cosmos DB, you can quickly create and query managed document, table, and graph databases.

本快速入門會使用 Azure Cosmos DB 適用的 Azure 入口網站工具,建立簡易的圖形資料庫。This quickstart creates a simple graph database using the Azure portal tools for Azure Cosmos DB. 本快速入門也說明如何透過使用 OSS Apache TinkerPop 驅動程式的 Gremlin API 資料庫,快速建立 Java 主控台應用程式。This quickstart also shows you how to quickly create a Java console app using a Gremlin API database using the OSS Apache TinkerPop driver. 本快速入門中的指示可運用在任何足以執行 Java 應用程式的作業系統上。The instructions in this quickstart can be followed on any operating system that is capable of running Java. 本快速入門可讓您熟悉如何在 UI 中或以程式設計方式建立和修改圖形 (不論您偏好哪種方式)。This quickstart familiarizes you with creating and modifying graphs 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.

此外: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 建立 Gremlin (圖形) 資料庫帳戶,才可以建立圖形資料庫。Before you can create a graph database, you need to create a Gremlin (Graph) database account with Azure Cosmos DB.

  1. 在新的瀏覽器視窗中,登入 Azure 入口網站In a new browser window, sign in to the Azure portal.

  2. 按一下 [建立資源] > [資料庫] > [Azure Cosmos DB] 。Click Create a resource > Databases > Azure Cosmos DB.

    Azure 入口網站的 [資料庫] 窗格

  3. 在 [建立 Azure Cosmos DB 帳戶] 頁面中,輸入新的 Azure Cosmos DB 帳戶的設定。In the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    設定Setting Value 說明Description
    訂用帳戶Subscription 您的訂用帳戶Your subscription 選取要用於此 Azure Cosmos DB 帳戶的 Azure 訂用帳戶。Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    資源群組Resource Group 新建Create new

    然後輸入識別碼中所提供的同一個唯一名稱Then enter the same unique name as provided in ID
    選取 [建立新的] 。Select Create new. 然後為您的帳戶輸入新的資源群組名稱。Then enter a new resource-group name for your account. 為求簡化,請使用和識別碼相同的名稱。For simplicity, use the same name as your ID.
    帳戶名稱Account Name 輸入唯一名稱Enter a unique name 輸入唯一名稱來識別您的 Azure Cosmos DB 帳戶。Enter a unique name to identify your Azure Cosmos DB 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 use only lowercase letters, numbers, and the hyphen (-) character. 長度必須介於 3 到 31 個字元之間。It must be between 3 and 31 characters in length.
    APIAPI Gremlin (圖形)Gremlin (graph) API 會決定要建立的帳戶類型。The API determines the type of account to create. Azure Cosmos DB 提供五個 API:Core(SQL) (適用於文件資料庫)、Gremlin (適用於圖形資料庫)、MongoDB (適用於文件資料庫)、「Azure 資料表」及 Cassandra。Azure Cosmos DB provides five APIs: Core(SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. 目前,您必須為每個 API 建立個別個帳戶。Currently, you must create a separate account for each API.

    選取 [Gremlin (圖形)] ,因為在此快速入門中,您會建立可搭配 Gremlin API 使用的資料表。Select Gremlin (graph) because in this quickstart you are creating a table that works with the Gremlin API.

    深入了解圖形 APILearn more about the Graph API.
    位置Location 選取最接近使用者的區域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's closest to your users to give them the fastest access to the data.

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

    Azure Cosmos DB 的新帳戶區段

  4. 建立帳戶需要幾分鐘的時間。The account creation takes a few minutes. 等候入口網站顯示 [恭喜!已建立您的 Azure Cosmos DB 帳戶] 頁面。Wait for the portal to display the Congratulations! Your Azure Cosmos DB account was created page.

    Azure 入口網站的 [通知] 窗格

新增圖形Add a graph

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

  1. 選取 [資料總管] > [新增圖形] 。Select Data Explorer > New Graph.

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

    Azure 入口網站資料總管 [新增圖形] 頁面

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

    設定Setting 建議的值Suggested value 說明Description
    資料庫識別碼Database ID sample-databasesample-database 輸入 sample-database 作為新資料庫的名稱。Enter sample-database as the name for the new database. 資料庫名稱的長度必須介於 1 到 255 個字元,且不能包含 / \ # ? 或尾端空格。Database names must be between 1 and 255 characters, and cannot contain / \ # ? or a trailing space.
    ThroughputThroughput 400 RU400 RUs 將輸送量變更為每秒 400 個要求單位 (RU/秒)。Change the throughput to 400 request units per second (RU/s). 如果您想要降低延遲,稍後可以相應增加輸送量。If you want to reduce latency, you can scale up the throughput later.
    圖形識別碼Graph ID sample-graphsample-graph 輸入 sample-graph 作為新集合的名稱。Enter sample-graph as the name for your new collection. 圖形名稱與資料庫識別碼具有相同的字元需求。Graph names have the same character requirements as database IDs.
    資料分割索引鍵Partition Key /pk/pk 所有 Cosmos DB 帳戶都需要分割索引鍵,才能進行水準調整。All Cosmos DB accounts need a partition key to horizontally scale. 了解如何在圖表資料分割一文中選取適當的分割區索引鍵。Learn how to select an appropriate partition key in the Graph Data Partitioning article.
  3. 填妥表單後,選取 [確定] 。Once the form is filled out, select OK.

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

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

  1. 開啟命令提示字元,建立名為 git-samples 的新資料夾,然後關閉命令提示字元。Open a command prompt, create a new folder named git-samples, then close the command prompt.

    md "C:\git-samples"
    
  2. 開啟 git 終端機視窗 (例如 git bash),並使用 cd 命令變更至要安裝範例應用程式的資料夾。Open a git terminal window, such as git bash, and use the cd command to change to a folder to install the sample app.

    cd "C:\git-samples"
    
  3. 執行下列命令來複製範例存放庫。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-graph-java-getting-started.git
    

檢閱程式碼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 Update your connection string.

下列程式碼片段皆是取自 C:\git-samples\azure-cosmos-db-graph-java-getting-started\src\GetStarted\Program.java 檔案。The following snippets are all taken from the C:\git-samples\azure-cosmos-db-graph-java-getting-started\src\GetStarted\Program.java file.

  • Gremlin Client 已從 C:\git-samples\azure-cosmos-db-graph-java-getting-started\src\remote.yaml 檔案中的組態初始化。The Gremlin Client is initialized from the configuration in the C:\git-samples\azure-cosmos-db-graph-java-getting-started\src\remote.yaml file.

    cluster = Cluster.build(new File("src/remote.yaml")).create();
    ...
    client = cluster.connect();
    
  • 已使用 client.submit 方法執行一系列的 Gremlin 步驟。Series of Gremlin steps are executed using the client.submit method.

    ResultSet results = client.submit(gremlin);
    
    CompletableFuture<List<Result>> completableFutureResults = results.all();
    List<Result> resultList = completableFutureResults.get();
    
    for (Result result : resultList) {
        System.out.println(result.toString());
    }
    

更新您的連線資訊Update your connection information

現在,返回 Azure 入口網站以取得連線資訊,並將其複製到應用程式中。Now go back to the Azure portal to get your connection information and copy it into the app. 這些設定可讓您的應用程式與託管資料庫進行通訊。These settings enable your app to communicate with your hosted database.

  1. Azure 入口網站中,選取 [金鑰] 。In the Azure portal, select Keys.

    複製 URI 值的第一個部分。Copy the first portion of the URI value.

    在 Azure 入口網站的 [金鑰] 頁面中,檢視並複製存取金鑰

  2. 開啟 src/remote.yaml 檔案,並將唯一 ID 貼至 hosts: [$name$.graphs.azure.com] 中的 $name$Open the src/remote.yaml file and paste the unique ID value over $name$ in hosts: [$name$.graphs.azure.com].

    remote.yaml 的行 1 現應如下所示Line 1 of remote.yaml should now look similar to

    hosts: [test-graph.graphs.azure.com]

  3. endpoint 值中將 graphs 變更為 gremlin.cosmosdbChange graphs to gremlin.cosmosdb in the endpoint value. (如果您已在 2017 年 12 月 20 日之前建立圖形資料庫帳戶,就不需要變更端點值,可繼續下一步。)(If you created your graph database account before December 20, 2017, make no changes to the endpoint value and continue to the next step.)

    端點值現在看起來應該像這樣:The endpoint value should now look like this:

    "endpoint": "https://testgraphacct.gremlin.cosmosdb.azure.com:443/"

  4. 在 Azure 入口網站中,使用複製按鈕複製 PRIMARY KEY,然後將其貼上至 password: $masterKey$ 中的 $masterKey$In the Azure portal, use the copy button to copy the PRIMARY KEY and paste it over $masterKey$ in password: $masterKey$.

    remote.yaml 的行 4 現應如下所示Line 4 of remote.yaml should now look similar to

    password: 2Ggkr662ifxz2Mg==

  5. 變更 remote.yaml 的行 3,從Change line 3 of remote.yaml from

    username: /dbs/$database$/colls/$collection$

    toto

    username: /dbs/sample-database/colls/sample-graph

    如果您已使用範例資料庫或圖形的唯一名稱,請更新為適當值。If you used a unique name for your sample database or graph, update the values as appropriate.

  6. 儲存 remote.yaml 檔案。Save the remote.yaml file.

執行主控台應用程式Run the console app

  1. 在 git 終端機視窗中,cd 至 azure-cosmos-db-graph-java-getting-started 資料夾。In the git terminal window, cd to the azure-cosmos-db-graph-java-getting-started folder.

    cd "C:\git-samples\azure-cosmos-db-graph-java-getting-started"
    
  2. 在 git 終端機視窗中,使用下列命令來安裝必要的 Java 套件。In the git terminal window, use the following command to install the required Java packages.

    mvn package
    
  3. 在 git 終端機視窗中,使用下列命令以啟動 JAVA 應用程式。In the git terminal window, use the following command to start the Java application.

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

    終端機視窗會顯示要新增至圖形的頂點。The terminal window displays the vertices being added to the graph.

    如果遇到逾時錯誤,請檢查您已在更新您的連線資訊中正確更新連線資訊,也請嘗試重新執行最後一個命令。If you experience timeout errors, check that you updated the connection information correctly in Update your connection information, and also try running the last command again.

    程式停止後,選取 Enter,然後在網際網路瀏覽器中切換回 Azure 入口網站。Once the program stops, select Enter, then switch back to the Azure portal in your internet browser.

檢閱並新增範例資料Review and add sample data

您現在可以移回 [資料總管] 並查看已新增到圖行的頂點,然後新增額外的資料點。You can now go back to Data Explorer and see the vertices added to the graph, and add additional data points.

  1. 選取 [資料總管] ,展開 sample-graph,選取 [圖形] ,然後再選取 [套用篩選條件] 。Select Data Explorer, expand sample-graph, select Graph, and then select Apply Filter.

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

  2. 在 [結果] 清單中,請注意已新增到圖形的新使用者。In the Results list, notice the new users added to the graph. 選取 [ben] ,並注意到此使用者已連線到 robin。Select ben and notice that the user is connected to robin. 您可以拖放移動周圍的頂點、捲動滑鼠滾輪執行縮放、使用雙箭號展開圖形大小。You can move the vertices around by dragging and dropping, zoom in and out by scrolling the wheel of your mouse, and expand the size of the graph with the double-arrow.

    Azure 入口網站的資料總管之圖形中的新頂點

  3. 現在來加入一些新使用者。Let's add a few new users. 選取 [新增頂點] 將資料新增至您的圖形。Select New Vertex to add data to your graph.

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

  4. 在 [標籤] 方塊中,輸入「人員」 。In the label box, enter person.

  5. 選取 [新增屬性] ,以新增以下各項屬性。Select Add property to add each of the following properties. 請注意,您可以在圖形中為每個人建立獨特的屬性。Notice that you can create unique properties for each person in your graph. 只需要識別碼索引鍵。Only the id key is required.

    索引鍵key valuevalue 注意Notes
    idid ashleyashley 頂點的唯一識別碼。The unique identifier for the vertex. 如果您未指定識別碼,系統會為您產生一個。If you don't specify an id, one is generated for you.
    gendergender femalefemale
    techtech javajava

    注意

    在本快速入門中,您會建立非資料分割集合。In this quickstart you create a non-partitioned collection. 不過,如果您藉由在集合建立期間指定資料分割索引鍵來建立資料分割集合,您就必須包含資料分割索引鍵作為每個新頂點的索引鍵。However, if you create a partitioned collection by specifying a partition key during the collection creation, then you need to include the partition key as a key in each new vertex.

  6. 選取 [確定] 。Select OK. 您可能需要展開畫面,才能在螢幕底部看到 [確定] 。You may need to expand your screen to see OK on the bottom of the screen.

  7. 再次選取 [新增頂點] 並新增額外的新使用者。Select New Vertex again and add an additional new user.

  8. 輸入人員的標籤。Enter a label of person.

  9. 選取 [新增屬性] ,以新增以下各項屬性:Select Add property to add each of the following properties:

    索引鍵key valuevalue 注意Notes
    idid rakeshrakesh 頂點的唯一識別碼。The unique identifier for the vertex. 如果您未指定識別碼,系統會為您產生一個。If you don't specify an id, one is generated for you.
    gendergender malemale
    schoolschool MITMIT
  10. 選取 [確定] 。Select OK.

  11. 選取 [套用篩選條件] 按鈕,預設的 g.V() 篩選條件會顯示圖形中的所有值。ClSelectck the Apply Filter button with the default g.V() filter to display all the values in the graph. 所有使用者現在會顯示在 [結果] 清單中。All of the users now show in the Results list.

    隨著您新增更多的資料,您可以使用篩選條件來限制您的結果。As you add more data, you can use filters to limit your results. 依預設,[資料總管] 會使用 g.V() 擷取圖形中的所有頂點。By default, Data Explorer uses g.V() to retrieve all vertices in a graph. 您可將其變更為不同的圖形查詢 (例如 g.V().count()),以使用 JSON 格式傳回圖形中所有頂點的計數。You can change it to a different graph query, such as g.V().count(), to return a count of all the vertices in the graph in JSON format. 若您變更篩選條件,請將篩選條件變更回 g.V(),然後選取 [套用篩選條件] ,即可再次顯示所有的結果。If you changed the filter, change the filter back to g.V() and select Apply Filter to display all the results again.

  12. 現在您可以將 rakesh 和 ashley 連線。Now you can connect rakesh, and ashley. 請確定已在 [結果] 清單中選取 ashley,然後選取右下方 [目標] 旁邊的 [變更圖形中頂點的目標]。Ensure ashley is selected in the Results list, then select Change the target of a vertex in a graph next to Targets on lower right side. 您可能需要加寬視窗,才可看到按鈕。You may need to widen your window to see the button.

    變更圖形中頂點的目標 - Azure CosmosDB

  13. 在 [目標] 方塊中輸入 rakesh ,並在 [邊緣標籤] 方塊中輸入「認識」 ,然後選取核取方塊。In the Target box enter rakesh, and in the Edge label box enter knows, and then select the check box.

    在資料總管中新增連線 - Azure CosmosDB

  14. 現在從 [結果] 清單中選取 rakesh 並查看 ashley 與 rakesh 是否已連線。Now select rakesh from the results list and see that ashley and rakesh are connected.

    資料總管中連線的兩個頂點 - Azure CosmosDB

    這會完成本教學課程中的資源建立部分。That completes the resource creation part of this tutorial. 您可以繼續將頂點新增至圖形、修改現有的頂點,或是變更查詢。You can continue to add vertexes to your graph, modify the existing vertexes, or change the queries. 現在讓我們檢閱 Azure Cosmos DB 提供的計量,然後再清除資源。Now let's review the metrics Azure Cosmos DB provides, and then clean up the resources.

在 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.

    選取要刪除的資源群組

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

    刪除資源群組

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

後續步驟Next steps

在本快速入門中,您已了解如何建立 Azure Cosmos DB 帳戶、如何使用 [資料總管] 來建立圖形,以及如何執行應用程式。In this quickstart, you've learned how to create an Azure Cosmos DB account, create a graph using the Data Explorer, and run an app. 您現在可以使用 Gremlin 來建置更複雜的查詢和實作強大的圖形周遊邏輯。You can now build more complex queries and implement powerful graph traversal logic using Gremlin.