Skip to content

Instantly share code, notes, and snippets.

@rm-rf-etc

rm-rf-etc/do_query.js

Last active Oct 24, 2019
Embed
What would you like to do?
Cayley Graph Database Example - Get user with friends
function predicatesToList(thingId) {
var thing = g.V(thingId);
var result = [];
thing.outPredicates().map(function(a){
if (!a) return;
thing.out(a.id).map(function(b){
result.push([a.id, b.id]);
});
});
return result;
}
function followLinks(options, data) {
if (options && Object.keys(options).length) {
Object.keys(options).forEach(function(key){
if (!key) return;
var action = key;
var predicate = options[key];
if (action === 'follow') {
data[predicate].forEach(function(nodeId, idx){
data[predicate][idx] = getThing(nodeId, { omit: '<friend>' });
});
}
else if (action === 'omit') {
delete data[predicate];
}
});
}
return data;
}
function collapseArray(arr) {
var result = {};
arr.forEach(function(item) {
var key = item[0];
var val = item[1];
if (key[0] === '<' && key.slice(-1) === '>') {
result[key] = result[key] || [];
result[key].push(val);
}
else {
result[key] = val;
}
});
return result;
}
function getThing(thingId, options) {
var asArray = predicatesToList(thingId);
var asObject = collapseArray(asArray);
var finalResults = followLinks(options, asObject);
finalResults.id = thingId;
return finalResults;
}
g.emit(getThing('uuid12345', { follow: '<friend>' }));
"uuid12345" "email" "jimjones@gmail.com" .
"uuid12345" "firstName" "Jim" .
"uuid12345" "lastName" "Jones" .
"uuid12345" "worksFor" "Corporation Inc." .
"uuid12345" <friend> "uuid12346" .
"uuid12345" <friend> "uuid12347" .
"uuid12346" "email" "joesmith@gmail.com" .
"uuid12346" "firstName" "Joe" .
"uuid12346" "lastName" "Smith" .
"uuid12346" "worksFor" "Apple" .
"uuid12346" <friend> "uuid12345" .
"uuid12347" "email" "alicecooper@gmail.com" .
"uuid12347" "firstName" "Alice" .
"uuid12347" "lastName" "Cooper" .
"uuid12347" "worksFor" "LinkedIn" .
"uuid12347" <friend> "uuid12345" .
{
"result": [
{
"<friend>": [
{
"email": "joesmith@gmail.com",
"firstName": "Joe",
"id": "uuid12346",
"lastName": "Smith",
"worksFor": "Apple"
},
{
"email": "alicecooper@gmail.com",
"firstName": "Alice",
"id": "uuid12347",
"lastName": "Cooper",
"worksFor": "LinkedIn"
}
],
"email": "jimjones@gmail.com",
"firstName": "Jim",
"id": "uuid12345",
"lastName": "Jones",
"worksFor": "Corporation Inc."
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.