UnitGraph
UnitGraph copied to clipboard
Add common graph use case example: friends recommendation
Would be good to have an out-of-the-box example of a friends recommendation engine. I've made a quick example here which could be used as a starting point. It could be extended to show things like recommendations based on interests etc.
graph_create.js
let ug = require('ug');
let graph = new ug.Graph();
let users = [
{ id: 1, name: 'Adam' },
{ id: 2, name: 'Beth' },
{ id: 3, name: 'Carl' },
{ id: 4, name: 'Dana' }
];
let locations = [
{ id: 1, name: 'Andora' },
{ id: 2, name: 'Brazil' },
{ id: 3, name: 'Chile' },
{ id: 4, name: 'Dublin' }
];
let likes = [
{ user_id: 1, location_id: 1 },
{ user_id: 1, location_id: 2 },
{ user_id: 2, location_id: 2 },
{ user_id: 2, location_id: 3 },
{ user_id: 3, location_id: 3 }
];
graph.nodes('user').createIndex('id');
graph.nodes('location').createIndex('id');
users.forEach(function (user) {
graph.createNode('user', user);
});
locations.forEach(function (location) {
graph.createNode('location', location);
});
likes.forEach(function (like) {
graph.createEdge('like').link(
graph.nodes('user').find(like.user_id),
graph.nodes('location').find(like.location_id)
).setDistance(2);
});
graph.save('./users.ugd', function () {
console.log('created ./users.ugd');
});
graph_load.js
let ug = require('ug');
let graph = new ug.Graph();
let users = [
{ id: 1, name: 'Adam' },
{ id: 2, name: 'Beth' },
{ id: 3, name: 'Carl' },
{ id: 4, name: 'Dana' }
];
graph.load('./users.ugd', function () {
users.forEach(function (user) {
let results = graph.closest(graph.nodes('user').find(user.id), {
compare: function (node) {
return node.entity === 'user';
},
minDepth: 3,
count: 1
}
);
let resultNodes = results.map(function (path) {
return path.end();
});
console.log(user.id, user.name);
console.log(resultNodes);
});
});