NodeJs
本文介绍如何基于Node.js
编程环境连接和操作图数据库GDB,这也是以常驻服务形式操作图数据库GDB的常用形式。
注意
- 进行以下操作时请确保图数据库GDB实例与您运行环境网络联通。
- 确保运行环境已经安装有Node.js,且版本不低于8.11
环境准备
安装Node.js,版本8.11或更高版本,Linux环境可以直接安装二进制包
安装
gremlin-javascript
程序包npm install gremlin
- 获取图数据库GDB连接参数
在’实例管理’->’基本信息’页面,可以查看实例内网地址和内网端口,如果开通外网访问实例,也可以使用外网地址和外网端口
注意 确保运行环境在实例白名单配置的可访问范围内
# 内网环境
endpoint = "${gdbID}.graphdb.rds.aliyuncs.com:8182"
# 外网环境
endpoint = "${gdbID}pub.graphdb.rds.aliyuncs.com:3734"
在’实例管理’->’账号管理’页面,可以查询实例账号信息,如果忘记密码,请’重置密码’
cusername="${username}"
password="${password}"
示例代码
- 新建一个demo目录,并添加测试文件
mkdir gdb_demo
cd gdb_demo
touch demo.js
- 编写测试代码,将下面
your-endpoint
替换为您的GDB实例内网环境或外网环境的endpoint,your-username
和your-password
也替换为您的GDB账号信息
"use strict";
const gremlin = require('gremlin');
const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator('your-username', 'your-password');
const client = new gremlin.driver.Client(
'ws://your-endpoint/gremlin',
{authenticator}
);
function countVertices()
{
console.log('Running Vertex Count');
return client.submit("g.V().count()", { })
.then((result) => {
console.log("Vertex Count Result: %s\n", JSON.stringify(result));
});
}
function addVertex1()
{
console.log('Running Add Vertex 1');
return client.submit("g.addV(GDB___label).property(id, GDB___id).property(GDB___pk, GDB___pv)",{
GDB___id: "gdb_vertex_test_id_1",
GDB___label: "gdb_vertex_test_label",
GDB___pk: "name",
GDB___pv: "Jack"
}).then(data => {
console.log("Add Vertex 1 Result: %s\n", JSON.stringify(data));
});
}
function addVertex2()
{
console.log('Running Add Vertex 2');
return client.submit("g.addV(GDB___label).property(id, GDB___id).property(GDB___pk, GDB___pv)",{
GDB___id: "gdb_vertex_test_id_2",
GDB___label: "gdb_vertex_test_label",
GDB___pk: "name",
GDB___pv: "Lucy"
}).then(data => {
console.log("Add Vertex 2 Result: %s\n", JSON.stringify(data));
});
}
function addEdge()
{
console.log('Running Add Edge');
return client.submit("g.addE(GDB___label).from(V(GDB___from)).to(V(GDB___to)).property(id, GDB___id).property(GDB___pk, GDB___pv)",{
GDB___id: "gdb_edge_test_id",
GDB___label: "gdb_edge_test_label",
GDB___from: "gdb_vertex_test_id_1",
GDB___to: "gdb_vertex_test_id_2",
GDB___pk: "relation",
GDB___pv: "lover"
}).then(data => {
console.log("Add Edge Result: %s\n", JSON.stringify(data));
});
}
function dropVertices()
{
console.log('Running Drop');
return client.submit('g.V().drop()', { })
.then((result) => {
console.log("Drop Result: %s\n", JSON.stringify(result));
});
}
client.open()
.then(countVertices)
.then(addVertex1)
.then(addVertex2)
.then(addEdge)
.then(dropVertices)
.catch((error) => {
console.error("Error running query...");
console.error(error);
}).then((res) => {
client.close()
console.log("Finished, Press any key to exit")
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));
}).catch((err) => {
console.error("Fatal error:", err);
});
上述代码使用图数据库GDB连接参数新建访问client,然后查询点数量,再添加两个点和一个边,接着删除所有点,最后等待用户键入退出
注意 使用
script
方式交互时,最好将DSL中可变参数模版化,对性能提升有显著帮助
- 复制上述代码到demo.js,运行测试程序
# 安装gremlin依赖到测试工程目录
npm install gremlin
# 运行测试程序
node demo.js
- 连接新创建的图数据库GDB实例,以下是测试程序的输出
Running Vertex Count
Vertex Count Result: {"_items":[0],"attributes":{},"length":1}
Running Add Vertex 1
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}
Running Add Vertex 2
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}
Running Add Edge
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}
Running Drop
Drop Result: {"_items":[],"attributes":{},"length":0}
Finished, Press any key to exit
使用bytecode
方式访问图数据库GDB
除上述script
方式与图数据库GDB交互外,您也可以使用bytecode
方式与GDB交互,以下直接给出与上一节相同功能的代码,您可以直接用相同方法运行查看执行结果。
同样您也需要替换图数据库GDB实例对连接参数到下面代码中。
"use strict";
const gremlin = require('gremlin');
const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection;
const Graph = gremlin.structure.Graph;
const __ = gremlin.process.statics;
const t = gremlin.process.t;
const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator('your-username', 'your-password');
const graph = new Graph();
const g = graph.traversal().withRemote(
new DriverRemoteConnection(
'ws://your-endpoint/gremlin',
{authenticator}
));
function vertexCount()
{
console.log('Running Vertex Count');
return g.V().count().next().
then(data => {
console.log("Vertex Count Result: %s", JSON.stringify(data));
});
}
function addVertex1()
{
console.log('Running Add Vertex 1');
return g.addV('gdb_vertex_test_label')
.property(t.id, 'gdb_vertex_test_id_1')
.property('name','Jack').toList()
.then(data => {
console.log("Add Vertex 1 Result: %s", JSON.stringify(data));
});
}
function addVertex2()
{
console.log('Running Add Vertex 2');
return g.addV('gdb_vertex_test_label')
.property(t.id, 'gdb_vertex_test_id_2')
.property('name','Lucy').toList()
.then(data => {
console.log("Add Vertex 2 Result: %s", JSON.stringify(data));
});
}
function addEdge()
{
console.log('Running Add Edge');
return g.addE('gdb_edge_test_label')
.from_(__.V('gdb_vertex_test_id_1'))
.to(__.V('gdb_vertex_test_id_2'))
.property(t.id, 'gdb_edge_test_id')
.property('relation','lover').toList()
.then(data => {
console.log("Add Edge Result: %s", JSON.stringify(data));
});
}
function dropVertex()
{
console.log('Running Drop');
return g.V().drop().iterate();
}
function finish()
{
console.log("Finished, Press any key to exit")
process.stdin.resume();
process.stdin.on('data', process.exit.bind(process, 0));
}
async function allTasks()
{
await vertexCount();
await addVertex1();
await addVertex2();
await addEdge();
await dropVertex();
await finish();
}
allTasks();
以上示例使用顺序串行的方式依次完成点数量查询,添加两个点和一个边,再删除所有数据,最后等待用户键入退出。示例只是演示script
和bytecode
完成相同功能的代码片段,同时也推荐您在异步事件中嵌入GDB的操作代码。
注意使用
bytecode
方式需要在DSL末尾添加一个终结符,这样DSL前面的操作才会提交到GDB服务端执行。
最佳实践
- GDB支持
script
和bytecode
两种方式访问,但更推荐使用script
方式 - 使用
script
方式访问GDB时,最好将DSL中可变参数模版化,可以获得较好的性能
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。
评论