我在neo4j中有一个图,对于给定的节点N,我想找到一条路径,该路径在从N开始的P步之内就可以到达的所有节点,以及那组节点之间的所有链接。 Cypher或Traversal框架似乎都有可能实现;一个比另一个更好?我正在使用Java和嵌入式数据库进行此操作,并且需要对子图执行进一步的查询。我四处摸索,没有找到任何结论性的答案。

最佳答案

我认为cypher是获取所需数据,查询可变长度路径,进行一些收集和优化的最简洁的方法:

如果n是节点N的内部ID,而您的P为5:

START begin = node(n)             // or e.g. index lookup
MATCH p = (begin)<-[r*..5]-(end)  // match all paths of length up to 5
WITH distinct nodes(p) as nodes   // collect the nodes contained in the paths
MATCH (x)<-[r]-(y)                // find all relationships between nodes
WHERE x in nodes and y in nodes   // which were found earlier
RETURN distinct x,r,y             // and deduplicate as you find all pairs twice


这可能不是最有效的方法,但是至少http://console.neo4j.org/中的执行计划说明建议将y in nodes视为在MATCH (x)-[r]-(y)之前。

我想不出一种避免两次匹配关系的方法,因此在return语句中使用distinct

09-10 09:15
查看更多