查询Neo4j中的家谱和婚姻信息

时间:2015-06-14 09:57:26

标签: database graph neo4j

我的Neo4j数据库中有这样的族树

db

如何从起始根节点(本例中为126)和每个节点的丈夫,妻子信息(类似于图像)查询树?

我后来需要在代码中提取类似于JSON格式的数据

root = {
  name: "...",
  children: [{
    name: "...",
    children: []
  }, {
    name: "...",
    children: []
  }],
  marriage: [{
    name: "first wife"
  }, {
    name: "second wife"
  }]
};

由于

1 个答案:

答案 0 :(得分:0)

在研究了更多关于密码的内容之后,我找到了解决方案,所以我将回答我自己的问题

这是密码查询。这将从root用户查询id为682

match p=(root:person {user_id: 682})-[:father_child|mother_child *1..5]->
      (child:person)<-[:father_child|mother_child]-(:person)
with nodes(p) as all_nodes, relationships(p) as all_relationships, p as p
return extract(n in all_nodes | n.user_id) as `path`,
       extract(r in all_relationships | type(r)) as `relation`,
       length(p) as `length`
order by `length`;

示例结果将如下所示

+-----------------------------------------------------------------------------+
| path              | relation                                       | length |
+-----------------------------------------------------------------------------+
| [682,687,683]     | ["father_child","mother_child"]                | 2      |
| [682,684,683]     | ["father_child","mother_child"]                | 2      |
| [682,688,683]     | ["father_child","mother_child"]                | 2      |
| [682,687,693,689] | ["father_child","father_child","mother_child"] | 3      |
| [682,684,690,685] | ["father_child","father_child","mother_child"] | 3      |
| [682,684,692,686] | ["father_child","father_child","mother_child"] | 3      |
+-----------------------------------------------------------------------------+

第一列包含一个数组。除最后一个值之外的数组是从根人到该子节点的路径,最后一个元素是该子节点的另一个父节点。我们有这最后一个要素的原因是因为一个人有很多妻子(或丈夫)。

第二列还包含一个数组。同样,数组是与第一列中的路径对应的关系。

从那里,您可以使用自己喜欢的编程语言轻松构建数据结构