问题
I am using LevelGraph (https://github.com/mcollina/levelgraph) to store connected items. My items are connected in the following way:
db.put([{
subject: "matteo",
predicate: "friend",
object: "daniele"
}, {
subject: "daniele",
predicate: "friend",
object: "bob"
}, {
subject: "bob",
predicate: "friend",
object: "marco"
}, {
subject: "marco",
predicate: "friend",
object: "fred"
}, {
subject: "fred",
predicate: "friend",
object: "joe"
}, {
subject: "joe",
predicate: "friend",
object: "david"
}], function () {});
I'd like to write a function to retrieve the nth-friend-of-friend of a particular person. For example here, the 6th-friend-of-a-friend of matteo would be david.
I know levelgraph has a search function built in:
db.search([{
subject: "matteo",
predicate: "friend",
object: db.v("x")
}, {
subject: db.v("x"),
predicate: "friend",
object: db.v("y")
}, {
subject: db.v("y"),
predicate: "friend",
object: db.v("z")
}], function(err, results) {
console.log(results);
});
Here, I would get the 3rd firend of a friend but I am not sure I get how to use it to retrieve the nth friend of a friend.
Is there a way to elegantly compound the search to retrieve the n-th connection?
回答1:
I've done this by dynamically creating the search and the variable names:
var start = "matteo";
var degrees = 6;
var i = 1;
var search = [{subject: start, predicate: "friend", object: db.v("d"+i)}];
for (; i < degrees; i++) {
search.push({subject: db.v("d"+i), predicate: "friend", object: db.v("d"+(i+1))}];
}
db.search(search, function(err, results) {
console.log(results);
});
Ouptut:
{
d1: 'daniele',
d2: 'bob',
d3: 'marco',
d4: 'fred',
d5: 'joe',
d6: 'david'
}
来源:https://stackoverflow.com/questions/26117128/nodejs-levelgraph-get-nth-friend-of-a-friend