我在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/中的执行计划解释建议在 MATCH (x)-[r]-(y)
之前考虑节点中的 y
。
我想不出一种方法来避免两次匹配关系,因此 return 语句中的 distinct
。
关于java - neo4j 中的诱导子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16943173/