推特 阿里云技术文档正文

NodeJs_SDK参考_图数据库GDB

admin 阿里云技术文档 2020-02-11 191 0
阿里云服务器优惠

NodeJs

本文介绍如何基于Node.js编程环境连接和操作图数据库GDB,这也是以常驻服务形式操作图数据库GDB的常用形式。

注意

  • 进行以下操作时请确保图数据库GDB实例与您运行环境网络联通。
  • 确保运行环境已经安装有Node.js,且版本不低于8.11

环境准备

  • 安装Node.js,版本8.11或更高版本,Linux环境可以直接安装二进制包

  • 安装gremlin-javascript程序包

    1. npm install gremlin
  • 获取图数据库GDB连接参数

在’实例管理’->’基本信息’页面,可以查看实例内网地址和内网端口,如果开通外网访问实例,也可以使用外网地址和外网端口

注意 确保运行环境在实例白名单配置的可访问范围内

  1. # 内网环境
  2. endpoint = "${gdbID}.graphdb.rds.aliyuncs.com:8182"
  3. # 外网环境
  4. endpoint = "${gdbID}pub.graphdb.rds.aliyuncs.com:3734"

在’实例管理’->’账号管理’页面,可以查询实例账号信息,如果忘记密码,请’重置密码’

  1. cusername="${username}"
  2. password="${password}"

示例代码

  • 新建一个demo目录,并添加测试文件
  1. mkdir gdb_demo
  2. cd gdb_demo
  3. touch demo.js
  • 编写测试代码,将下面your-endpoint替换为您的GDB实例内网环境或外网环境的endpoint,your-usernameyour-password也替换为您的GDB账号信息
  1. "use strict";
  2. const gremlin = require('gremlin');
  3. const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator('your-username', 'your-password');
  4. const client = new gremlin.driver.Client(
  5. 'ws://your-endpoint/gremlin',
  6. {authenticator}
  7. );
  8. function countVertices()
  9. {
  10. console.log('Running Vertex Count');
  11. return client.submit("g.V().count()", { })
  12. .then((result) => {
  13. console.log("Vertex Count Result: %s\n", JSON.stringify(result));
  14. });
  15. }
  16. function addVertex1()
  17. {
  18. console.log('Running Add Vertex 1');
  19. return client.submit("g.addV(GDB___label).property(id, GDB___id).property(GDB___pk, GDB___pv)",{
  20. GDB___id: "gdb_vertex_test_id_1",
  21. GDB___label: "gdb_vertex_test_label",
  22. GDB___pk: "name",
  23. GDB___pv: "Jack"
  24. }).then(data => {
  25. console.log("Add Vertex 1 Result: %s\n", JSON.stringify(data));
  26. });
  27. }
  28. function addVertex2()
  29. {
  30. console.log('Running Add Vertex 2');
  31. return client.submit("g.addV(GDB___label).property(id, GDB___id).property(GDB___pk, GDB___pv)",{
  32. GDB___id: "gdb_vertex_test_id_2",
  33. GDB___label: "gdb_vertex_test_label",
  34. GDB___pk: "name",
  35. GDB___pv: "Lucy"
  36. }).then(data => {
  37. console.log("Add Vertex 2 Result: %s\n", JSON.stringify(data));
  38. });
  39. }
  40. function addEdge()
  41. {
  42. console.log('Running Add Edge');
  43. return client.submit("g.addE(GDB___label).from(V(GDB___from)).to(V(GDB___to)).property(id, GDB___id).property(GDB___pk, GDB___pv)",{
  44. GDB___id: "gdb_edge_test_id",
  45. GDB___label: "gdb_edge_test_label",
  46. GDB___from: "gdb_vertex_test_id_1",
  47. GDB___to: "gdb_vertex_test_id_2",
  48. GDB___pk: "relation",
  49. GDB___pv: "lover"
  50. }).then(data => {
  51. console.log("Add Edge Result: %s\n", JSON.stringify(data));
  52. });
  53. }
  54. function dropVertices()
  55. {
  56. console.log('Running Drop');
  57. return client.submit('g.V().drop()', { })
  58. .then((result) => {
  59. console.log("Drop Result: %s\n", JSON.stringify(result));
  60. });
  61. }
  62. client.open()
  63. .then(countVertices)
  64. .then(addVertex1)
  65. .then(addVertex2)
  66. .then(addEdge)
  67. .then(dropVertices)
  68. .catch((error) => {
  69. console.error("Error running query...");
  70. console.error(error);
  71. }).then((res) => {
  72. client.close()
  73. console.log("Finished, Press any key to exit")
  74. process.stdin.resume();
  75. process.stdin.on('data', process.exit.bind(process, 0));
  76. }).catch((err) => {
  77. console.error("Fatal error:", err);
  78. });

上述代码使用图数据库GDB连接参数新建访问client,然后查询点数量,再添加两个点和一个边,接着删除所有点,最后等待用户键入退出

注意 使用script方式交互时,最好将DSL中可变参数模版化,对性能提升有显著帮助

  • 复制上述代码到demo.js,运行测试程序
  1. # 安装gremlin依赖到测试工程目录
  2. npm install gremlin
  3. # 运行测试程序
  4. node demo.js
  • 连接新创建的图数据库GDB实例,以下是测试程序的输出
  1. Running Vertex Count
  2. Vertex Count Result: {"_items":[0],"attributes":{},"length":1}
  3. Running Add Vertex 1
  4. Add Vertex 1 Result: {"_items":[{"id":"gdb_vertex_test_id_1","label":"gdb_vertex_test_label","properties":{"name":[{"id":"gdb_vertex_test_id_1","label":"name","value":"Jack","key":"name"}]}}],"attributes":{},"length":1}
  5. Running Add Vertex 2
  6. Add Vertex 2 Result: {"_items":[{"id":"gdb_vertex_test_id_2","label":"gdb_vertex_test_label","properties":{"name":[{"id":"gdb_vertex_test_id_2","label":"name","value":"Lucy","key":"name"}]}}],"attributes":{},"length":1}
  7. Running Add Edge
  8. Add Edge Result: {"_items":[{"id":"gdb_edge_test_id","label":"gdb_edge_test_label","outV":"gdb_vertex_test_id_1","inV":"gdb_vertex_test_id_2","properties":{"relation":"lover"}}],"attributes":{},"length":1}
  9. Running Drop
  10. Drop Result: {"_items":[],"attributes":{},"length":0}
  11. Finished, Press any key to exit

使用bytecode方式访问图数据库GDB

除上述script方式与图数据库GDB交互外,您也可以使用bytecode方式与GDB交互,以下直接给出与上一节相同功能的代码,您可以直接用相同方法运行查看执行结果。

同样您也需要替换图数据库GDB实例对连接参数到下面代码中。

  1. "use strict";
  2. const gremlin = require('gremlin');
  3. const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection;
  4. const Graph = gremlin.structure.Graph;
  5. const __ = gremlin.process.statics;
  6. const t = gremlin.process.t;
  7. const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator('your-username', 'your-password');
  8. const graph = new Graph();
  9. const g = graph.traversal().withRemote(
  10. new DriverRemoteConnection(
  11. 'ws://your-endpoint/gremlin',
  12. {authenticator}
  13. ));
  14. function vertexCount()
  15. {
  16. console.log('Running Vertex Count');
  17. return g.V().count().next().
  18. then(data => {
  19. console.log("Vertex Count Result: %s", JSON.stringify(data));
  20. });
  21. }
  22. function addVertex1()
  23. {
  24. console.log('Running Add Vertex 1');
  25. return g.addV('gdb_vertex_test_label')
  26. .property(t.id, 'gdb_vertex_test_id_1')
  27. .property('name','Jack').toList()
  28. .then(data => {
  29. console.log("Add Vertex 1 Result: %s", JSON.stringify(data));
  30. });
  31. }
  32. function addVertex2()
  33. {
  34. console.log('Running Add Vertex 2');
  35. return g.addV('gdb_vertex_test_label')
  36. .property(t.id, 'gdb_vertex_test_id_2')
  37. .property('name','Lucy').toList()
  38. .then(data => {
  39. console.log("Add Vertex 2 Result: %s", JSON.stringify(data));
  40. });
  41. }
  42. function addEdge()
  43. {
  44. console.log('Running Add Edge');
  45. return g.addE('gdb_edge_test_label')
  46. .from_(__.V('gdb_vertex_test_id_1'))
  47. .to(__.V('gdb_vertex_test_id_2'))
  48. .property(t.id, 'gdb_edge_test_id')
  49. .property('relation','lover').toList()
  50. .then(data => {
  51. console.log("Add Edge Result: %s", JSON.stringify(data));
  52. });
  53. }
  54. function dropVertex()
  55. {
  56. console.log('Running Drop');
  57. return g.V().drop().iterate();
  58. }
  59. function finish()
  60. {
  61. console.log("Finished, Press any key to exit")
  62. process.stdin.resume();
  63. process.stdin.on('data', process.exit.bind(process, 0));
  64. }
  65. async function allTasks()
  66. {
  67. await vertexCount();
  68. await addVertex1();
  69. await addVertex2();
  70. await addEdge();
  71. await dropVertex();
  72. await finish();
  73. }
  74. allTasks();

以上示例使用顺序串行的方式依次完成点数量查询,添加两个点和一个边,再删除所有数据,最后等待用户键入退出。示例只是演示scriptbytecode完成相同功能的代码片段,同时也推荐您在异步事件中嵌入GDB的操作代码。

注意使用bytecode方式需要在DSL末尾添加一个终结符,这样DSL前面的操作才会提交到GDB服务端执行。

最佳实践

  • GDB支持scriptbytecode两种方式访问,但更推荐使用script方式
  • 使用script方式访问GDB时,最好将DSL中可变参数模版化,可以获得较好的性能
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

评论

-----