0

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?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Spearfisher
  • 8,445
  • 19
  • 70
  • 124

1 Answers1

0

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'
}
doowb
  • 3,372
  • 1
  • 17
  • 25