快速入门:使用 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 是世纪互联提供的多区域分布式多模型数据库服务。Azure Cosmos DB is 21Vianet's multiple-regionally 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 multiple-region 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.


如果尚未安装 Visual Studio 2019,可以下载并使用免费Visual Studio 2019 Community EditionIf 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 trial account before you begin.

创建数据库帐户Create a database account

  1. 在新浏览器窗口中,登录到 Azure 门户In a new browser window, sign in to the Azure portal.

  2. 在左侧菜单中,选择“创建资源” 。In the left menu, select Create a resource.

    在 Azure 门户中创建资源

  3. 在“新建”页上,选择“数据库” > “Azure Cosmos DB”。 On the New page, select Databases > Azure Cosmos DB.

    Azure 门户“数据库”窗格

  4. 在“创建 Azure Cosmos DB 帐户”页中,输入新 Azure Cosmos DB 帐户的设置 。On 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 name as Account Name
    选择“新建”。 Select Create new. 然后输入帐户的新资源组名称。Then enter a new resource group name for your account. 为简单起见,请使用与 Azure Cosmos DB 帐户名称相同的名称。For simplicity, use the same name as your Azure Cosmos DB account name.
    帐户名Account Name 输入唯一的名称Enter a unique name 输入标识此 Azure Cosmos DB 帐户的唯一名称。Enter a unique name to identify your Azure Cosmos DB account. 帐户 URI 将是追加到唯一帐户名称的“gremlin.cosmos.azure.cn” 。Your account URI will be gremlin.cosmos.azure.cn appended to your unique account name.

    帐户名称只能使用小写字母、数字及连字符 (-),必须为 3 到 31 个字符长。The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    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 创建单独的帐户。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.

    详细了解 Gremlin APILearn more about the Gremlin 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 的“新建帐户”页

  5. 创建帐户需要几分钟时间。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 Cosmos DB 帐户已创建”页

添加图形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
    数据库 IDDatabase 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.
    吞吐量Throughput 400 RU400 RUs 将吞吐量更改为每秒 400 个请求单位 (RU/s)。Change the throughput to 400 request units per second (RU/s). 如果想要减少延迟,以后可以增加吞吐量。If you want to reduce latency, you can scale up the throughput later.
    图形 IDGraph ID sample-graphsample-graph 输入“sample-graph” 作为新集合的名称。Enter sample-graph as the name for your new collection. 图形名称与数据库 ID 的字符要求相同。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 bash 之类的 git 终端窗口,并使用 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.

  • 跟踪上面创建的帐户设置连接参数:Set your connection parameters based on the account created above:

    private string EndpointUrl = Environment.GetEnvironmentVariable("EndpointUrl");
    private string PrimaryKey = Environment.GetEnvironmentVariable("PrimaryKey");
    private static int port = 443;
    private static string database = "your-database-name";
    private static string container = "your-container-or-graph-name";
  • 要执行的 Gremlin 命令列在字典中:The Gremlin commands to be executed are listed in a Dictionary:

    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()" },
  • 使用上面提供的参数创建新的 GremlinServerGremlinClient 连接对象:Create a new GremlinServer and GremlinClient connection objects using the parameters provided above:

    var gremlinServer = new GremlinServer(EndpointUrl, port, enableSsl: true, 
                                           username: "/dbs/" + database + "/colls/" + container, 
                                           password: PrimaryKey);
    using (var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
  • 通过将 GremlinClient 对象与异步任务配合使用来执行每一个 Gremlin 查询。Execute each Gremlin query using the GremlinClient object with an async task. 可以从上一步中定义的字典读取 Gremlin 查询,并执行它们。You can read the Gremlin queries from the dictionary defined in the previous step and execute them. 稍后使用 Newtonsoft.Json 包中的 JsonSerializer 类,获取结果并读取已格式化为字典的值:Later get the result and read the values, which are formatted as a dictionary, using the JsonSerializer class from Newtonsoft.Json package:

    foreach (var query in gremlinQueries)
       Console.WriteLine(String.Format("Running this query: {0}: {1}", query.Key, query.Value));
       // Create async task to execute the Gremlin query.
       var resultSet = SubmitRequest(gremlinClient, query).Result;
       if (resultSet.Count > 0)
           foreach (var result in resultSet)
               // The vertex results are formed as Dictionaries with a nested dictionary for their properties
               string output = JsonConvert.SerializeObject(result);
       // Print the status attributes for the result set.
       // This includes the following:
       //  x-ms-status-code            : This is the sub-status code which is specific to Cosmos DB.
       //  x-ms-total-request-charge   : The total request units charged for processing a request.

更新连接字符串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.cosmos.azure.cnTo 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.cosmos.azure.cn. 终结点值应类似于 testgraphacct.gremlin.cosmos.azure.cnThe endpoint value should look like testgraphacct.gremlin.cosmos.azure.cn

  2. 接下来,从 Azure 门户中导航到“密钥”选项卡并复制“主密钥”值。 Next, navigate to the Keys tab and copy the PRIMARY KEY value from the Azure portal.

  3. 复制帐户的 URI 和主键以后,请将其保存到运行应用程序的本地计算机的新环境变量中。After you have copied the URI and PRIMARY KEY of your account, save them to a new environment variable on the local machine running the application. 若要设置环境变量,请打开命令提示符窗口,并运行以下命令。To set the environment variable, open a command prompt window, and run the following command. 确保替换 <Your_Azure_Cosmos_account_URI> 和 <Your_Azure_Cosmos_account_PRIMARY_KEY> 值。Make sure to replace <Your_Azure_Cosmos_account_URI> and <Your_Azure_Cosmos_account_PRIMARY_KEY> values.

    setx EndpointUrl "https://<your cosmos db account name>.gremlin.cosmos.azure.cn"
    setx PrimaryKey "<Your_Azure_Cosmos_account_PRIMARY_KEY>"
  4. 打开 Program.cs 文件,将 "database" 和 "container" 变量更新为在上面创建的数据库和容器的名称(也是图形名称)。Open the Program.cs file and update the "database and "container" variables with the database and container (which is also the graph name) names created above.

    private static string database = "your-database-name"; private static string container = "your-container-or-graph-name";private static string database = "your-database-name"; private static string container = "your-container-or-graph-name";

  5. 保存 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

执行完应用和 Azure Cosmos DB 帐户的操作以后,可以删除所创建的 Azure 资源,以免产生更多费用。When you're done with your 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 Search bar, search for and select Resource groups.

  2. 从列表中选择为本快速入门创建的资源组。From the list, select the resource group you created for this quickstart.


  3. 在资源组“概览”页上,选择“删除资源组” 。On the resource group Overview page, 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.