在多跳Cypher查询中为每个当前节点获取父节点的最佳方法是什么?

时间:2013-10-28 12:19:09

标签: neo4j cypher

我有一个文件和文件夹的图表,我本质上想要一个查询 - 给定folderId - 以递归方式返回整个子目录结构,包括每个节点的parentId

我提出了这个解决方案(注意:Cypher 2.0):

match p = (f:folder)-[:CONTAINS*0..]->c 
where f._id = 3 
return case when c._id = f._id then null 
          else nodes(p)[length(p)-1]._id end as parentId, c;

这似乎有效。但我觉得必须有一个更清洁的方式。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

另一种方法是明确标识路径上的父节点,

Match f:Folder-[:CONTAINS*0..]->parent-[:CONTAINS]->c
where f._id = 3
Return parent._id as parent, c._id as current

结果不包括给定起始文件夹f的行。但由于它是一个固定值,如果你真的需要在查询结果中包含它,你可以随时将它附加到结果中,如下所示,

Match f:Folder-[:CONTAINS*0..]->parent-[:CONTAINS]->c
where f._id = 3
Return parent._id as parent, c._id as current
Union
Return null as parent, 3 as current
相关问题