快速入門:使用 Azure Cosmos DB Gremlin API 帳戶建置 .NET Framework 或 Core 應用程式Quickstart: Build a .NET Framework or Core application using the Azure Cosmos DB Gremlin API account

Azure Cosmos DB 是 Microsoft 的全域分散式多模型資料庫服務。Azure Cosmos DB is Microsoft's globally distributed multi-model database service. 您可以快速建立及查詢文件、索引鍵/值及圖形資料庫,所有這些都受惠於位於 Azure Cosmos DB 核心的全域散發和水平調整功能。You can quickly create and query document, key/value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Azure Cosmos DB.

本快速入門示範如何使用 Azure 入口網站建立 Azure Cosmos DB Gremlin API 帳戶、資料庫和圖表 (容器)。This quickstart demonstrates how to create an Azure Cosmos DB Gremlin API account, database, and graph (container) using the Azure portal. 您會接著使用開放原始碼 Gremlin.Net 來建置和執行主控台應用程式。You then build and run a console app built using the open-source driver Gremlin.Net.

必要條件Prerequisites

如果尚未安裝 Visual Studio 2019,您可以下載並使用免費的 Visual Studio 2019 Community 版本If you don't already have Visual Studio 2019 installed, you can download and use the free Visual Studio 2019 Community Edition. 務必在 Visual Studio 設定期間啟用 Azure 開發Make sure that you enable Azure development during the Visual Studio setup.

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

建立資料庫帳戶Create a database account

  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

現在,我們將從 GitHub 複製 Gremlin API 應用程式、設定連接字串,然後加以執行。Now 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 the new 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-gremlindotnet-getting-started.git
    
  4. 然後開啟 Visual Studio 並開啟方案檔案。Then open Visual Studio and open the solution file.

  5. 在專案中還原 NuGet 套件。Restore the NuGet packages in the project. 這應該包含 Gremlin.Net 驅動程式,以及 Newtonsoft.Json 套件。This should include the Gremlin.Net driver, as well as the Newtonsoft.Json package.

  6. 您也可以使用 Nuget 套件管理員或 nuget 命令列公用程式,手動安裝 Gremlin.Net 驅動程式:You can also install the Gremlin.Net driver manually using the Nuget package manager, or the nuget command-line utility:

    nuget install Gremlin.Net
    

檢閱程式碼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.

下列程式碼片段全部取自 Program.cs 檔案。The following snippets are all taken from the Program.cs file.

  • 根據以上 (第 19 行) 建立的帳戶,設定您的連線參數:Set your connection parameters based on the account created above (Line 19):

    private static string hostname = "your-endpoint.gremlin.cosmosdb.azure.com";
    private static int port = 443;
    private static string authKey = "your-authentication-key";
    private static string database = "your-database";
    private static string collection = "your-graph-container";
    
  • 要執行的 Gremlin 命令會列於字典 (第 26 行) 中:The Gremlin commands to be executed are listed in a Dictionary (Line 26):

    private static Dictionary<string, string> gremlinQueries = new Dictionary<string, string>
    {
        { "Cleanup",        "g.V().drop()" },
        { "AddVertex 1",    "g.addV('person').property('id', 'thomas').property('firstName', 'Thomas').property('age', 44).property('pk', 'pk')" },
        { "AddVertex 2",    "g.addV('person').property('id', 'mary').property('firstName', 'Mary').property('lastName', 'Andersen').property('age', 39).property('pk', 'pk')" },
        { "AddVertex 3",    "g.addV('person').property('id', 'ben').property('firstName', 'Ben').property('lastName', 'Miller').property('pk', 'pk')" },
        { "AddVertex 4",    "g.addV('person').property('id', 'robin').property('firstName', 'Robin').property('lastName', 'Wakefield').property('pk', 'pk')" },
        { "AddEdge 1",      "g.V('thomas').addE('knows').to(g.V('mary'))" },
        { "AddEdge 2",      "g.V('thomas').addE('knows').to(g.V('ben'))" },
        { "AddEdge 3",      "g.V('ben').addE('knows').to(g.V('robin'))" },
        { "UpdateVertex",   "g.V('thomas').property('age', 44)" },
        { "CountVertices",  "g.V().count()" },
        { "Filter Range",   "g.V().hasLabel('person').has('age', gt(40))" },
        { "Project",        "g.V().hasLabel('person').values('firstName')" },
        { "Sort",           "g.V().hasLabel('person').order().by('firstName', decr)" },
        { "Traverse",       "g.V('thomas').out('knows').hasLabel('person')" },
        { "Traverse 2x",    "g.V('thomas').out('knows').hasLabel('person').out('knows').hasLabel('person')" },
        { "Loop",           "g.V('thomas').repeat(out()).until(has('id', 'robin')).path()" },
        { "DropEdge",       "g.V('thomas').outE('knows').where(inV().has('id', 'mary')).drop()" },
        { "CountEdges",     "g.E().count()" },
        { "DropVertex",     "g.V('thomas').drop()" },
    };
    
  • 使用以上 (第 52 行) 提供的參數,建立 GremlinServer 連線物件:Create a GremlinServer connection object using the parameters provided above (Line 52):

    var gremlinServer = new GremlinServer(hostname, port, enableSsl: true, 
                                                    username: "/dbs/" + database + "/colls/" + collection, 
                                                    password: authKey);
    
  • 建立新的 GremlinClient 物件 (第 56 行):Create a new GremlinClient object (Line 56):

    var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType);
    
  • 使用 GremlinClient 物件搭配非同步工作 (第 63 行),執行每個 Gremlin 查詢。Execute each Gremlin query using the GremlinClient object with an async task (Line 63). 這將從以上 (第 26 行) 定義的字典讀取 Gremlin 查詢:This will read the Gremlin queries from the dictionary defined above (Line 26):

    var results = await gremlinClient.SubmitAsync<dynamic>(query.Value);
    
  • 使用 Newtonsoft.Json 中的 JsonSerializer 類別,擷取結果並讀取已格式化為字典的值:Retrieve the result and read the values, which are formatted as a dictionary, using the JsonSerializer class from Newtonsoft.Json:

    foreach (var result in results)
    {
        // The vertex results are formed as dictionaries with a nested dictionary for their properties
        string output = JsonConvert.SerializeObject(result);
        Console.WriteLine(String.Format("\tResult:\n\t{0}", output));
    }
    

更新您的連接字串Update your connection string

現在,返回 Azure 入口網站以取得連接字串資訊,並將它複製到應用程式中。Now go back to the Azure portal to get your connection string information and copy it into the app.

  1. Azure 入口網站中,瀏覽至您的圖形資料庫帳戶。From the Azure portal, navigate to your graph database account. 在 [概觀] 索引標籤中,您可以看到兩個端點:In the Overview tab, you can see two endpoints-

    .NET SDK URI - 當您使用 Microsoft.Azure.Graphs 程式庫連線至圖形帳戶時,將會使用此值。.NET SDK URI - This value is used when you connect to the graph account by using Microsoft.Azure.Graphs library.

    Gremlin 端點 - 當您使用 Gremlin.Net 程式庫連線至圖形帳戶時,將會使用此值。Gremlin Endpoint - This value is used when you connect to the graph account by using Gremlin.Net library.

    複製端點

    若要執行此範例,請複製 [Gremlin 端點] 值,並刪除結尾處的連接埠號碼,使 URI 變成 https://<your cosmos db account name>.gremlin.cosmosdb.azure.comTo run this sample, copy the Gremlin Endpoint value, delete the port number at the end, that is the URI becomes https://<your cosmos db account name>.gremlin.cosmosdb.azure.com

  2. 在 Program.cs 中,將此值貼在第 19 行 hostname 變數中的 your-endpoint 上。In Program.cs paste the value over your-endpoint in the hostname variable in line 19.

    "private static string hostname = "<your cosmos db account name>.gremlin.cosmosdb.azure.com";

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

    "private static string hostname = "testgraphacct.gremlin.cosmosdb.azure.com";

  3. 接著,瀏覽至 [索引鍵] 索引標籤,並從入口網站複製 [主索引鍵] 值,然後將其貼在 authkey 變數中,並取代第 21 行的 "your-authentication-key" 預留位置。Next, navigate to the Keys tab and copy PRIMARY KEY value from the portal, and paste it in the authkey variable, replacing the "your-authentication-key" placeholder in line 21.

    private static string authKey = "your-authentication-key";

  4. 使用以上建立的資料庫資訊,將資料庫名稱貼在第 22 行的 database 變數內。Using the information of the database created above, paste the database name inside of the database variable in line 22.

    private static string database = "your-database";

  5. 同樣地,使用以上建立的容器資訊,將集合 (也是圖形名稱) 貼在第 23 行的 collection 變數內。Similarly, using the information of the container created above, paste the collection (which is also the graph name) inside of the collection variable in line 23.

    private static string collection = "your-collection-or-graph";

  6. 儲存 Program.cs 檔案。Save the Program.cs file.

您現已更新應用程式,使其具有與 Azure Cosmos DB 通訊所需的所有資訊。You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

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

按 CTRL + F5 來執行應用程式。Click CTRL + F5 to run the application. 此應用程式會在主控台中列印 Gremlin 查詢命令和結果。The application will print both the Gremlin query commands and results in the console.

主控台視窗會顯示將要新增至圖形的頂點和邊緣。The console window displays the vertexes and edges being added to the graph. 當指令碼完成時,請按 ENTER 以關閉主控台視窗。When the script completes, press ENTER to close the console window.

使用資料總管進行瀏覽Browse using the Data Explorer

您現在可以回到 Azure 入口網站中的 [資料總管],瀏覽及查詢新的圖形資料。You can now go back to Data Explorer in the Azure portal and browse and query your new graph data.

  1. 在 [資料總管] 中,新的資料庫會出現在 [圖形] 窗格中。In Data Explorer, the new database appears in the Graphs pane. 展開資料庫和容器節點,然後按一下 [圖形] 。Expand the database and container nodes, and then click Graph.

  2. 按一下 [套用篩選條件] 按鈕,以使用預設查詢來檢視圖形中的所有頂點。Click the Apply Filter button to use the default query to view all the vertices in the graph. 範例應用程式所產生的資料會顯示在 [圖形] 窗格中。The data generated by the sample app is displayed in the Graphs pane.

    您可以縮放圖形、展開圖形顯示空間、新增其他頂點,並在顯示介面上移動頂點。You can zoom in and out of the graph, you can expand the graph display space, add additional vertices, and move vertices on the display surface.

    在 Azure 入口網站的資料總管中檢視圖形

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