快速入门:使用 Azure Cosmos DB Gremlin API 帐户生成 Node.js 应用程序Quickstart: Build a Node.js application by using Azure Cosmos DB Gremlin API account

适用于: Gremlin API

在本快速入门中,你将通过 Azure 门户创建和管理 Azure Cosmos DB Gremlin(图形)API 帐户,并使用从 GitHub 克隆的 Node.js 应用来添加数据。In this quickstart, you create and manage an Azure Cosmos DB Gremlin (graph) API account from the Azure portal, and add data by using a Node.js app cloned from GitHub. Azure Cosmos DB 是一种多模型数据库服务,可让你通过多区域分布和水平缩放功能快速创建和查询文档、表、键/值和图数据库。Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with multiple-region distribution and horizontal scale capabilities.


创建数据库帐户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-nodejs-getting-started.git
  4. 在 Visual Studio 中打开解决方案文件。Open the solution file in Visual Studio.

查看代码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.

以下代码片段全部摘自 app.js 文件。The following snippets are all taken from the app.js file.

此控制台应用使用开源 Gremlin Node.js 驱动程序。This console app uses the open-source Gremlin Node.js driver.

  • 将创建 Gremlin 客户端。The Gremlin client is created.

    const authenticator = new Gremlin.driver.auth.PlainTextSaslAuthenticator(
    const client = new Gremlin.driver.Client(
            traversalsource : "g",
            rejectUnauthorized : true,
            mimeType : "application/vnd.gremlin-v2.0+json"

    配置均位于 config.js 中,可以在 以下部分中编辑该文件。The configurations are all in config.js , which we edit in the following section.

  • 将定义一系列函数以执行不同 Gremlin 操作。A series of functions are defined to execute different Gremlin operations. 以下是其中一个函数:This is one of them:

    function addVertex1()
        console.log('Running Add Vertex1'); 
        return client.submit("g.addV(label).property('id', id).property('firstName', firstName).property('age', age).property('userid', userid).property('pk', 'pk')", {
                age:44, userid: 1
            }).then(function (result) {
                    console.log("Result: %s\n", JSON.stringify(result));
  • 每个函数均通过 Gremlin 查询字符串参数执行 client.execute 方法。Each function executes a client.execute method with a Gremlin query string parameter. 下面是演示如何执行 g.V().count() 的示例:Here is an example of how g.V().count() is executed:

    function countVertices()
        console.log('Running Count');
        return client.submit("g.V().count()", { }).then(function (result) {
            console.log("Result: %s\n", JSON.stringify(result));
  • 然后在文件末尾,调用所有方法。At the end of the file, all methods are then invoked. 这将依次执行它们:This will execute them one after the other:

    .catch((err) => {
        console.error("Error running query...");
    }).then((res) => {
    }).catch((err) => 
        console.error("Fatal error:", err)

更新连接字符串Update your connection string

  1. 打开 config.js 文件。Open the config.js file.

  2. config.js 中,使用 Azure 门户中你的 Cosmos DB 帐户的“概述”页面中的“Gremlin 终结点”值填写 config.endpoint 密钥。 In config.js , fill in the config.endpoint key with the Gremlin Endpoint value from the Overview page of your Cosmos DB account in the Azure portal.

    config.endpoint = "https://<your_Gremlin_account_name>.gremlin.cosmos.azure.cn:443/";

    在 Azure 门户的“概述”页面中,查看并复制访问密钥

  3. config.js 中,使用 Azure 门户中你的 Cosmos DB 帐户的“密钥”页面中的“主密钥”值填写 config.primaryKey 值。 In config.js , fill in the config.primaryKey value with the Primary Key value from the Keys page of your Cosmos DB account in the Azure portal.

    config.primaryKey = "PRIMARYKEY";

    Azure 门户“密钥”边栏选项卡

  4. 输入数据库名称和图形(容器)名称作为 config.database 和 config.collection 的值。Enter the database name, and graph (container) name for the value of config.database and config.collection.

下面的示例展示了完成的 config.js 文件应该是什么样子的:Here's an example of what your completed config.js file should look like:

var config = {}

// Note that this must include the protocol (HTTPS:// for .NET SDK URI or wss:// for Gremlin Endpoint) and the port number
config.endpoint = "https://testgraphacct.gremlin.cosmos.azure.cn:443/"; 
config.primaryKey = "Pams6e7LEUS7LJ2Qk0fjZf3eGo65JdMWHmyn65i52w8ozPX2oxY3iP0yu05t9v1WymAHNcMwPIqNAEv3XDFsEg==";
config.database = "graphdb"
config.collection = "Persons"

module.exports = config;

运行控制台应用Run the console app

  1. 打开一个终端窗口,切换到(通过 cd 命令)项目中包括的 package.json 文件的安装目录。Open a terminal window and change (via cd command) to the installation directory for the package.json file that's included in the project.

  2. 运行 npm install,安装所需的 npm 模块,包括 gremlinRun npm install to install the required npm modules, including gremlin.

  3. 在终端中运行 node app.js,启动 node 应用程序。Run node app.js in a terminal to start your node application.

使用数据资源管理器浏览Browse with Data Explorer

现在可以返回到 Azure 门户中的数据资源管理器,查看、查询、修改以及使用新的图形数据。You can now go back to Data Explorer in the Azure portal to view, query, modify, and work with your new graph data.

在数据资源管理器中,新数据库会显示在“图形”窗格中。In Data Explorer, the new database appears in the Graphs pane. 展开数据库(后跟容器),然后选择“图形”。Expand the database, followed by the container, and then select Graph.

选择“应用筛选器”时,由示例应用生成的数据会显示在“图形”选项卡的下一窗格中。 The data generated by the sample app is displayed in the next pane within the Graph tab when you select Apply Filter.

尝试使用 .has('firstName', 'Thomas') 来完成 g.V(),对筛选器进行测试。Try completing g.V() with .has('firstName', 'Thomas') to test the filter. 请注意,值区分大小写。Note that the value is case sensitive.

在 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 your 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 帐户,使用数据资源管理器创建图形,以及运行 Node.js 应用来向图形中添加数据。In this article, you learned how to create an Azure Cosmos DB account, create a graph by using Data Explorer, and run a Node.js app to add data to the graph. 现可使用 Gremlin 生成更复杂的查询,实现功能强大的图形遍历逻辑。You can now build more complex queries and implement powerful graph traversal logic by using Gremlin.