Node.js

Updated at:

This topic describes how to connect to and interact with Graph Database (GDB) using the Node.js programming environment.

Important
  • Ensure that your Graph Database (GDB) instance can connect to the network of your runtime environment.
  • Ensure that Node.js version 8.11 or later is installed in your runtime environment.

Prerequisites

  1. Install Node.js version 8.11 or later. For Linux environments, you can install the binary package directly.
  2. Install the gremlin-javascript package.
    npm install gremlin
  3. Obtain the connection parameters for your GDB instance.

On the Instance Management > Basic Information page, you can view the internal network address and port of the instance. If public network access is enabled for the instance, you can also use the public network address and port.

# Internal network environment
endpoint = "${gdbID}.graphdb.rds.aliyuncs.com:8182"
# Public network environment
endpoint = "${gdbID}pub.graphdb.rds.aliyuncs.com:3734"
Important Ensure that the IP address of your runtime environment is added to the instance's whitelist.
On the Instance Management > Account Management page, you can query the instance account information. If you forget the password, click Reset Password.
cusername="${username}"
password="${password}"

Sample code

  1. Create a demo directory and add a test file.
    mkdir gdb_demo
    cd gdb_demo
    touch demo.js
  2. Write the test code. Replace your-username, your-password, and your-endpoint in the code with the account, password, and domain name of your instance.
    "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);
        });

    The preceding code snippet uses the GDB connection parameters to create an access client. The code snippet then queries the number of points, adds two points and one edge, deletes all points, and waits for a key press before exiting.

    Important When you interact using the script method, use templates for variable parameters in the Domain-Specific Language (DSL). This significantly improves performance.
  3. Copy the preceding code to demo.js and run the test program.
    # Install the gremlin dependency to the test project directory.
    npm install gremlin
    # Run the test program.
    node demo.js
  4. Connect to the Graph Database (GDB) instance. The following code block shows the output of the test program.
    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

Access Graph Database GDB using the bytecode method

In addition to the script method, you can also interact with GDB using the bytecode method. The following code snippet provides the same functionality as the code snippet in the previous section. You can run the code snippet using the same method to view the execution results.

You must also replace your-username, your-password, and your-endpoint in the following code with the account, password, and domain name of your GDB instance.

"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();

The preceding code snippet sequentially queries the number of points, adds two points and one edge, deletes all data, and then waits for a key press before exiting. This example provides code snippets for the script and bytecode methods that perform the same function. You can also embed GDB operations in asynchronous events.

Important When you use the bytecode method, you must add a terminal step

Best practices

  • GDB supports access using both the script and bytecode methods. We recommend that you use the script method.
  • When you access GDB using the script method, use templates for variable parameters in the DSL to achieve better performance.