11

Use IBM Graph from NodeJS

Embed Size (px)

Citation preview

IBM-GRAPH-CLIENThttps://www.npmjs.com/package/ibm-graph-client

SIGNUPONBLUEMIX.NETANDLOOKFORIBMGRAPH

CREATEANINSTANCE

INITSESSION # Change the credentials to reflect your `apiURL`, `username`, and `password` and test the code in your instance.{ "credentials": { "apiURL": "https://ibmgraph-alpha.ng.bluemix.net/a261eac3-6956-4185-a789-8e24c475e89b/g", "username": "575fd2b0-c011-4b94-82cf-43244b44f3a8", "password": "aca0d011-26f5-485d-a446-182750278a27" }};var ibmGraph= require('ibm-graph-client');var g = new ibmGraph(instance.credentials);g.session(function(err, data) { if (err) { console.log(err); } else { g.config.session = data; console.log("Your session token is " + data); }});

CREATEAGRAPH var graph; // graph nameg.graphs().create(function(err, data){ if (err) { console.log("Something went wrong: "); console.log(err); } else { graph = data.graphId; console.log('Graph created: ' + data.graphId); }});

GETALLGRAPHS g.graphs().get(function(err, data){ if (err) { console.log(err); } console.log(data);});

DEFINEASCHEMA var schema = { "propertyKeys": [ {"name": "name", "dataType": "String", "cardinality": "SINGLE"}, ], "vertexLabels": [ {"name": "person"}, ], "edgeLabels": [ {"name": "tweets", "multiplicity": "MULTI"}, ], "vertexIndexes": [ {"name": "vByName", "propertyKeys": ["name"], "composite": true, "unique": true}, ], "edgeIndexes" :[ {"name": "eByTime", "propertyKeys": ["time"], "composite": true, "unique": false} ]}

ADDASCHEMA #Point your config to the new graph you just createdg.config.url = g.config.url.substr(0, g.config.url.lastIndexOf('/') + 1) + graph;g.schema().set(schema, function(err, data){ if (err) { console.log(err); } console.log(JSON.stringify(data));});

CREATESOMEVERTEXESANDEDGES gremlin = { gremlin: "\ def david = graph.addVertex(T.label, 'person', 'name', 'David', 'verified', false);\ def browniesTweet = graph.addVertex(T.label, 'tweet', 'tweet', 'I love brownies #baking @Joseph', 'sentiment', 'loving', 'tone', 'excited' david.addEdge('tweets', browniesTweet);\ browniesTweet.addEdge('hashes', bakingHashtag);\ browniesTweet.addEdge('mentions', joseph);\ ", bindings: {}}g.gremlin(gremlin, function(err,data){ if (err) { console.log(err); } console.log(JSON.stringify(data));});

QUERYTHEGRAPH

gremlin = { "gremlin": "graph.traversal().V().hasLabel('person').has('name', name).outE('favorites').inV();", "bindings": { "name": "Kamal" }}g.gremlin(gremlin, function(err,data){ if (err) { console.log('Error: ' + err); } console.log(JSON.stringify(data));});