Skip to content

Instantly share code, notes, and snippets.

@gugacavalieri
Last active July 23, 2020 18:58
Show Gist options
  • Save gugacavalieri/bf11b1b7da353731a81956a6c060a962 to your computer and use it in GitHub Desktop.
Save gugacavalieri/bf11b1b7da353731a81956a6c060a962 to your computer and use it in GitHub Desktop.
AWS Neptune - Gremlin - JS
const gremlin = require('gremlin');
const { traversal } = gremlin.process.AnonymousTraversalSource;
const { DriverRemoteConnection } = gremlin.driver;
const graph = traversal().withRemote(new DriverRemoteConnection('ws://graphdb:8182/gremlin', {}));
module.exports = { graph }
/* we use this object to reference vertex ID and vertex properties */
const { t: { id } } = gremlin.process;
const { cardinality: { single } } = gremlin.process;
/**
* create a new vertex with Id, Label and properties
* @param {String,Number} vertexId Vertex Id
* @param {String} label Vertex Label
*/
const createVertex = async (vertexId, label) => {
const vertex = await graph.addV(label)
.property(id, vertexId)
.property(single, 'name', 'John')
.property(single, 'lastname', 'Lennon')
.next();
return vertex.value;
};
/**
* find unique vertex with id and label
* @param {String,Number} vertexId
* @param {String} label
*/
const findVertex = async (vertexId, label) => {
const vertex = await graph.V(vertexId).hasLabel(label).elementMap().next();
return vertex.value;
};
/**
* List all vertexes in db
* @param {Number} limit
*/
const listAll = async (limit = 500) => {
return graph.V().limit(limit).elementMap().toList();
};
/* run methods */
const main = async () => {
/* create vertex */
const customId = Math.random() * 1000000;
console.log(await createVertex(customId, 'mylabel'));
/* update vertex */
console.log(await findVertex(customId, 'mylabel'));
console.log(await updateVertex(customId, 'mylabel', 'Ringo'));
console.log(await findVertex(customId, 'mylabel'));
/* should return null */
console.log(await findVertex(123412, 'mylabel'));
/* should print all nodes with limit = 10 */
console.log(await listAll(10));
};
main();
/* we use this object to reference vertex ID and vertex properties */
const { t: { id } } = gremlin.process;
const { cardinality: { single } } = gremlin.process;
/**
* Update Vertex Properties
* @param {String,Number} vertexId Vertex Id
* @param {String} label Vertex Label
* @param {String} name Vertex Name Property
*/
const updateVertex = async (vertexId, label, name) => {
const vertex = await graph.V(vertexId).property(single, 'name', name).next();
return vertex.value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment