快速入门:使用 Gremlin 控制台创建、查询和遍历 Azure Cosmos DB 图形数据库Quickstart: Create, query, and traverse an Azure Cosmos DB graph database using the Gremlin console

适用于: Gremlin API

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 帐户、数据库和图(容器),并使用 Apache TinkerPopGremlin 控制台处理 Gremlin API 数据。This quickstart demonstrates how to create an Azure Cosmos DB Gremlin API account, database, and graph (container) using the Azure portal and then use the Gremlin Console from Apache TinkerPop to work with Gremlin API data. 本教程将创建并查询顶点和边缘,更新顶点属性,查询顶点,遍历图形,然后删除顶点。In this tutorial, you create and query vertices and edges, updating a vertex property, query vertices, traverse the graph, and drop a vertex.

Apache Gremlin 控制台中的 Azure Cosmos DB

Gremlin 控制台基于 Groovy/Java,在 Linux、Mac 和 Windows 上运行。The Gremlin console is Groovy/Java based and runs on Linux, Mac, and Windows. 可以从 Apache TinkerPop 站点下载它。You can download it from the Apache TinkerPop site.


需要使用 Azure 订阅为本快速入门教程创建 Azure Cosmos DB 帐户。You need to have an Azure subscription to create an Azure Cosmos DB account for this quickstart.

如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin.

还需要安装 Gremlin 控制台You also need to install the Gremlin Console. 推荐的版本为 v3.4.3 或更早版本。The recommended version is v3.4.3 or earlier. (若要在 Windows 上使用 Gremlin 控制台,需安装 Java 运行时)。(To use Gremlin Console on Windows, you need to install Java Runtime).

创建数据库帐户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 门户“数据库”窗格


    如果在列表中没有看到“Azure Cosmos DB”,只需在页面顶部的搜索框中键入它,然后按 Enter 键即可。If you don't see Azure Cosmos DB in the list, just type it in the search box at the top of the page, and press Enter key.

  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.
    容量模式Capacity mode 预配吞吐量或无服务器Provisioned throughput or Serverless 选择“预配吞吐量”以在预配吞吐量模式下创建帐户。Select Provisioned throughput to create an account in provisioned throughput mode. 选择“无服务器”以在无服务器模式下创建帐户。Select Serverless to create an account in serverless mode.

    选择“查看 + 创建” 。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.

连接到应用服务/图Connect to your app service/Graph

  1. 在启动 Gremlin 控制台之前,请在 apache-tinkerpop-gremlin-console-3.2.5/conf 目录中创建或修改 remote-secure.yaml 配置文件。Before starting the Gremlin Console, create or modify the remote-secure.yaml configuration file in the apache-tinkerpop-gremlin-console-3.2.5/conf directory.

  2. 根据下表中的定义,填写 hostportusernamepasswordconnectionPoolserializer 配置:Fill in your host, port, username, password, connectionPool, and serializer configurations as defined in the following table:

    设置Setting 建议的值Suggested value 说明Description
    hostshosts [account-name.gremlin.cosmos.azure.cn][account-name.gremlin.cosmos.azure.cn] 请参阅下面的屏幕截图。See the following screenshot. 这是 Azure 门户的“概述”页上的“Gremlin URI”值,方括号中已删除尾部的 :443/。This is the Gremlin URI value on the Overview page of the Azure portal, in square brackets, with the trailing :443/ removed. 注意:请确保使用 Gremlin 值,并且 不是 以 [account-name.documents.azure.cn] 结尾的 URI,这可能会在稍后尝试执行 Gremlin 查询时导致“主机未及时响应”异常。Note: Be sure to use the Gremlin value, and not the URI that ends with [account-name.documents.azure.cn] which would likely result in a "Host did not respond in a timely fashion" exception when attempting to execute Gremlin queries later.
    portport 443443 设置为 443。Set to 443.
    usernameusername 用户名Your username 采用 /dbs/<db>/colls/<coll> 格式的资源,其中,<db> 是数据库名称,<coll> 是集合名称。The resource of the form /dbs/<db>/colls/<coll> where <db> is your database name and <coll> is your collection name.
    passwordpassword 主密钥Your primary key 请参阅下面的第二幅屏幕截图。See second screenshot below. 这是主密钥,可以从 Azure 门户的“密钥”页上的“主密钥”框中检索到。This is your primary key, which you can retrieve from the Keys page of the Azure portal, in the Primary Key box. 使用该框左侧的复制按钮可复制该值。Use the copy button on the left side of the box to copy the value.
    connectionPoolconnectionPool {enableSsl: true}{enableSsl: true} TLS 的连接池设置。Your connection pool setting for TLS.
    serializerserializer { className: org.apache.tinkerpop.gremlin.{ className: org.apache.tinkerpop.gremlin.
    config: { serializeResultToString: true }}config: { serializeResultToString: true }}
    请设置为此值,并在粘贴此值时删除所有 \n 换行符。Set to this value and delete any \n line breaks when pasting in the value.

    对于 Hosts 值,请从“概览”页复制“Gremlin URI”值 :For the hosts value, copy the Gremlin URI value from the Overview page:

    在 Azure 门户的“概览”页上查看和复制 Gremlin URI 值

    对于密码值,请从“密钥”页复制“主密钥” :For the password value, copy the Primary key from the Keys page:

    在 Azure 门户的“密钥”页中查看和复制主密钥

    remote-secure.yaml 文件应如下所示:Your remote-secure.yaml file should look like this:

    hosts: [your_database_server.gremlin.cosmos.azure.cn] 
    port: 443
    username: /dbs/your_database_account/colls/your_collection
    password: your_primary_key
    connectionPool: {
        enableSsl: true
    serializer: { className: org.apache.tinkerpop.gremlin.driver.   ser.GraphSONMessageSerializerV2d0, config: {    serializeResultToString: true }}

    确保将 hosts 参数的值括在括号 [] 中。make sure to wrap the value of hosts parameter within brackets [].

  3. 在终端中运行 bin/gremlin.batbin/gremlin.sh 启动Gremlin 控制台In your terminal, run bin/gremlin.bat or bin/gremlin.sh to start the Gremlin Console.

  4. 在终端中运行 :remote connect tinkerpop.server conf/remote-secure.yaml 连接到应用服务。In your terminal, run :remote connect tinkerpop.server conf/remote-secure.yaml to connect to your app service.


    如果收到错误No appenders could be found for logger,请确保已更新 remote-secure.yaml 文件中的序列化程序值,如步骤 2 中所述。If you receive the error No appenders could be found for logger ensure that you updated the serializer value in the remote-secure.yaml file as described in step 2. 如果配置正确,则可以安全地忽略此警告,因为它不应影响控制台的使用。If your configuration is correct, then this warning can be safely ignored as it should not impact the use of the console.

  5. 接下来运行 :remote console,将所有控制台命令重定向到远程服务器。Next run :remote console to redirect all console commands to the remote server.


    如果你不运行 :remote console 命令但希望将所有控制台命令重定向到远程服务器,则应在命令前添加 :> 前缀,例如,应该以 :> g.V().count() 形式运行命令。If you don't run the :remote console command but would like to redirect all console commands to the remote server, you should prefix the command with :>, for example you should run the command as :> g.V().count(). 此前缀是命令的一部分,在将 Gremlin 控制台与 Azure Cosmos DB 一起使用时非常重要。This prefix is a part of the command and it is important when using the Gremlin console with Azure Cosmos DB. 省略此前缀将指示控制台在本地执行命令,通常针对一个内存中图表执行。Omitting this prefix instructs the console to execute the command locally, often against an in-memory graph. 使用此前缀 :> 则指示控制台执行远程命令,在此示例中针对 Azure Cosmos DB(localhost 仿真器或 Azure 实例)执行。Using this prefix :> tells the console to execute a remote command, in this case against Azure Cosmos DB (either the localhost emulator, or an Azure instance).

很好!Great! 完成设置后,我们开始运行一些控制台命令。Now that we finished the setup, let's start running some console commands.

现在尝试一个简单的 count() 命令。Let's try a simple count() command. 在控制台的提示符下键入以下命令:Type the following into the console at the prompt:


创建顶点和边缘Create vertices and edges

首先为 Thomas、Mary Kay、Robin、Ben 和 Jack 添加五个人员顶点 。Let's begin by adding five person vertices for Thomas, Mary Kay, Robin, Ben, and Jack.

输入 (Thomas):Input (Thomas):

g.addV('person').property('firstName', 'Thomas').property('lastName', 'Andersen').property('age', 44).property('userid', 1).property('pk', 'pk')



输入 (Mary Kay):Input (Mary Kay):

g.addV('person').property('firstName', 'Mary Kay').property('lastName', 'Andersen').property('age', 39).property('userid', 2).property('pk', 'pk')


==>[id:0ac9be25-a476-4a30-8da8-e79f0119ea5e,label:person,type:vertex,properties:[firstName:[[id:ea0604f8-14ee-4513-a48a-1734a1f28dc0,value:Mary Kay]],lastName:[[id:86d3bba5-fd60-4856-9396-c195ef7d7f4b,value:Andersen]],age:[[id:bc81b78d-30c4-4e03-8f40-50f72eb5f6da,value:39]],userid:[[id:0ac9be25-a476-4a30-8da8-e79f0119ea5e|userid,value:2]]]]

输入 (Robin):Input (Robin):

g.addV('person').property('firstName', 'Robin').property('lastName', 'Wakefield').property('userid', 3).property('pk', 'pk')



输入 (Ben):Input (Ben):

g.addV('person').property('firstName', 'Ben').property('lastName', 'Miller').property('userid', 4).property('pk', 'pk')



输入 (Jack):Input (Jack):

g.addV('person').property('firstName', 'Jack').property('lastName', 'Connor').property('userid', 5).property('pk', 'pk')



接下来,为人员之间的关系添加边缘。Next, let's add edges for relationships between our people.

输入 (Thomas-> Mary Kay):Input (Thomas -> Mary Kay):

g.V().hasLabel('person').has('firstName', 'Thomas').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Mary Kay'))



输入 (Thomas-> Robin):Input (Thomas -> Robin):

g.V().hasLabel('person').has('firstName', 'Thomas').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Robin'))



输入 (Robin -> Ben):Input (Robin -> Ben):

g.V().hasLabel('person').has('firstName', 'Robin').addE('knows').to(g.V().hasLabel('person').has('firstName', 'Ben'))



更新顶点Update a vertex

使用新年龄 45 更新 Thomas 顶点。Let's update the Thomas vertex with a new age of 45.


g.V().hasLabel('person').has('firstName', 'Thomas').property('age', 45)



查询图形Query your graph

现在,我们针对图形运行各种查询。Now, let's run a variety of queries against your graph.

首先,我们尝试结合筛选器运行一个查询,以返回年龄超过 40 岁的人员。First, let's try a query with a filter to return only people who are older than 40 years old.

输入(筛选器查询):Input (filter query):

g.V().hasLabel('person').has('age', gt(40))



接下来,投影年龄超过 40 岁的人员的名字。Next, let's project the first name for the people who are older than 40 years old.

输入(筛选器 + 投影查询):Input (filter + projection query):

g.V().hasLabel('person').has('age', gt(40)).values('firstName')



遍历图形Traverse your graph

我们遍历图形,返回 Thomas 的所有朋友。Let's traverse the graph to return all of Thomas's friends.

输入(Thomas 的朋友):Input (friends of Thomas):

g.V().hasLabel('person').has('firstName', 'Thomas').outE('knows').inV().hasLabel('person')


==>[id:f04bc00b-cb56-46c4-a3bb-a5870c42f7ff,label:person,type:vertex,properties:[firstName:[[id:14feedec-b070-444e-b544-62be15c7167c,value:Mary Kay]],lastName:[[id:107ab421-7208-45d4-b969-bbc54481992a,value:Andersen]],age:[[id:4b08d6e4-58f5-45df-8e69-6b790b692e0a,value:39]]]]

接下来,获取下一个顶点层。Next, let's get the next layer of vertices. 遍历图形,返回 Thomas 的朋友的所有朋友。Traverse the graph to return all the friends of Thomas's friends.

输入(Thomas 的朋友的朋友):Input (friends of friends of Thomas):

g.V().hasLabel('person').has('firstName', 'Thomas').outE('knows').inV().hasLabel('person').outE('knows').inV().hasLabel('person')



删除顶点Drop a vertex

现在,我们从图形数据库中删除某个顶点。Let's now delete a vertex from the graph database.

输入(删除 Jack 顶点):Input (drop Jack vertex):

g.V().hasLabel('person').has('firstName', 'Jack').drop()

清除图形Clear your graph

最后,我们清除所有顶点和边缘的数据库。Finally, let's clear the database of all vertices and edges.



祝贺你!Congratulations! 你已完成“Azure Cosmos DB:Gremlin API”教程!You've completed this Azure Cosmos DB: Gremlin API tutorial!

在 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 帐户、使用数据资源管理器创建图形、创建顶点和边缘,以及使用 Gremlin 控制台遍历图形。In this quickstart, you've learned how to create an Azure Cosmos DB account, create a graph using the Data Explorer, create vertices and edges, and traverse your graph using the Gremlin console. 现可使用 Gremlin 构建更复杂的查询,实现功能强大的图形遍历逻辑。You can now build more complex queries and implement powerful graph traversal logic using Gremlin.