NodeJS / Levelgraph - 获取朋友的朋友

时间:2014-09-30 09:20:30

标签: node.js leveldb

我使用LevelGraph(https://github.com/mcollina/levelgraph)来存储连接的项目。我的项目按以下方式连接:

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 () {});

我想写一个函数来检索某个人的朋友的第一个朋友。例如,在这里,matteo的朋友的第6位朋友将是大卫。

我知道levelgraph有一个内置的搜索功能:

  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);
  });

在这里,我会得到一位朋友的第三名,但我不确定如何使用它来检索朋友的第一位朋友。

有没有办法优雅地复合搜索以检索第n个连接?

1 个答案:

答案 0 :(得分:0)

我是通过动态创建搜索和变量名来完成的:

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'
}