在Neo4j Cypher查询中仅返回简单路径

15

给定以下查询:

START n = node(123)
MATCH p = n-[r:LIKES*..3]->x
RETURN p;

我使用上述查询得到的结果路径包含循环。

如何仅返回简单路径?

考虑以下示例

  • 我该如何避免出现重复节点的路径,例如:[Neo,Morpheus,Trinity,Morpheus,Neo]?

请注意,路径长度3是一个查询参数,可以更改。 - Marsellus Wallace
你有使用console.neo4j.org/usage.html的示例吗? - Peter Neubauer
@PeterNeubauer 刚刚添加了一个! - Marsellus Wallace
3个回答

16

指定路径的唯一性是Cypher计划中的一个功能。

因此,现在我们必须确定路径中没有重复的节点。

有一个ALL谓词,它必须对集合(即路径)的所有元素都成立。 而使用filter,您可以提取满足特定条件的集合元素。

START neo=node(1) 
MATCH path= neo-[r:KNOWS*..4]->other 
WHERE ALL(n in nodes(path) where 
          1=length(filter(m in nodes(path) : m=n))) 
RETURN neo, LENGTH(path) AS length, EXTRACT(p in NODES(path) : p.name), other 
ORDER BY length

所以我做的是:

  • 对于路径的所有节点n
  • 筛选出与n相等的节点
  • 确定该集合的长度
  • ALL断言每个n必须为1

参见:http://console.neo4j.org/r/dpalbl


嗨,Michael,有没有更好的方法来识别路径中的循环。你上面分享的解决方案虽然有效,但在时间和数据库访问方面代价高昂。你能否请再检查一下? - Hemant
在使用Neo4j 2.2.5时,我不得不将过滤器部分更改为filter(m in nodes(path) WHERE m=n)) - Daniel Olszewski
1
大家好。有人知道3.0版本中这方面的任何更新吗? - imran arshad
1
对于图形:create (n:ent {id:'a'})-[:rel]->(:ent {id:'b'})-[:rel]->(o:ent {id:'c'})-[:rel]->(p:ent {id:'d'})-[:rel]->(:ent {id:'e'})-[:rel]->(n),(p)-[:rel]->(o),查询 MATCH path=(ent{id:'a'})-[:rel*0..]->(ent) WHERE ALL(n in nodes(path) WHERE 1=length(filter(m in nodes(path)WHERE m=n))) RETURN path 出现了 key not found: UNNAMED25 错误! - Mahesha999

3
我的解决方法是:
START n = node(123), x=node(*)
MATCH p = shortestPath(n-[r:LIKES*..3]->x)
RETURN p;

see the example in console


1
这在给定的示例中可能有效,但我实际上对于在给定长度内没有重复节点的所有可能路径(而不仅仅是最短路径)感兴趣。谢谢。 - Marsellus Wallace

2
在2.3.0版本中,请使用以下内容:
MATCH path = (start {id:2})<-[*1..]-(end {id:3}) 
WHERE ALL(n in nodes(path) where 
          1 = size(filter(m in nodes(path) where m=n))) 
RETURN start, LENGTH(path) AS length, EXTRACT(p in NODES(path) | p.id), end
ORDER BY length

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接