密码找到关系方向

时间:2013-07-17 15:23:17

标签: neo4j cypher

如何找到关于包含路径的关系方向?我需要这个进行加权图搜索,考虑关系方向(用0称量“错误”方向,另见评论)。

让我们说:

START a=node({param})
MATCH a-[*]-b
WITH a, b
MATCH p = allshortestpaths(a-[*]-b)
RETURN extract(r in rels(p): flows_with_path(r)) as in_flow

,其中 flows_with_path = 1如果sp = (a)-[*0..]-[r]->[*0..]-(b),则为0 {{1}}

编辑:更正后的查询

1 个答案:

答案 0 :(得分:1)

所以,这是使用现有cypher函数的方法。我不保证它的表现非常出色,但请试一试。我们使用reduce构建我们的集合,使用带有集合的累加器元组和我们查看的最后一个节点,因此我们可以检查它是否已连接到下一个节点。这需要2.0的大小写/何时语法 - 可能有一种方法可以在1.9中完成它但它可能更复杂。

START a=node:node_auto_index(name="Trinity") 
MATCH a-[*]-b 
WHERE a <> b
WITH distinct a,b 
MATCH p = allshortestpaths(a-[*]-b) 
RETURN extract(x in nodes(p): x.name?), // a concise representation of the path we're checking
  head(
    reduce(acc=[[], head(nodes(p))], x IN tail(nodes(p)): // pop the first node off, traverse the tail
      CASE WHEN ALL (y IN tail(acc) WHERE y-->x)  // a bit of a hack because tail(acc)-->x doesn't parse right, so I had to wrap it so I can have a bare identifier in the pattern predicate
           THEN [head(acc) + 0, x]    // add a 0 to our accumulator collection
           ELSE [head(acc) + 1, x]    // add a 1 to our accumulator collection 
      END )) AS in_line

http://console.neo4j.org/r/v0jx03

输出:

+---------------------------------------------------------------------------+
| extract(x in nodes(p): x.name?)                               | in_line   |
+---------------------------------------------------------------------------+
| ["Trinity","Morpheus"]                                        | [1]       |
| ["Trinity","Morpheus","Cypher"]                               | [1,0]     |
| ["Trinity","Morpheus","Cypher","Agent Smith"]                 | [1,0,0]   |
| ["Trinity","Morpheus","Cypher","Agent Smith","The Architect"] | [1,0,0,0] |
| ["Trinity","Neo"]                                             | [1]       |
| ["Trinity","Neo",<null>]                                      | [1,1]     |
+---------------------------------------------------------------------------+

注意:感谢@boggle进行头脑风暴会议。