简体   繁体   English

neo4j cypher交织节点和关系

[英]neo4j cypher interleave nodes and relationships

How can I return nodes and relationships interleaved? 如何返回交错的节点和关系? Using the Matrix movie database the query 使用Matrix电影数据库查询

    MATCH p=(a1:Actor {name:"Keanu Reeves"})-[r *0..5]-(a2:Actor {name: "Carrie-Anne Moss"})
    return [n in nodes(p)|coalesce(n.title,n.name)], [rel in relationships(p)|type(rel)]

returns two columns, one with the nodes and one with the relationships 返回两列,一列包含节点,另一列包含关系

    Keanu Reeves, The Matrix, Laurence Fishburne, The Matrix Reloaded, Carrie-Anne Moss | ACTS_IN, ACTS_IN, ACTS_IN, ACTS_IN
    ...

but I want 但我想要

    Keanu Reeves, ACTS_IN, The Matrix, ACTS_IN, Laurence Fishburne, ACTS_IN, The Matrix Reloaded, ACTS_IN, Carrie-Anne Moss
    ...

This used to be easier, but they broke "the easy way" in 2.0-RC1 when they made Paths not Collections anymore, in Cypher. 这曾经更容易,但是当他们在Cypher中制作Paths not Collections时,他们打破了2.0-RC1中的“简单方法”。

match p= shortestPath((kevin)-[:ACTED_IN*]-(charlize))
where kevin.name="Kevin Bacon"
and charlize.name="Charlize Theron"
with nodes(p) as ns, rels(p) as rs, range(0,length(nodes(p))+length(rels(p))-1) as idx
return [i in idx | case i % 2 = 0 when true then coalesce((ns[i/2]).name, (ns[i/2]).title) else type(rs[i/2]) end];

The old way was: 旧的方式是:

match p= shortestPath((kevin)-[:ACTED_IN*]-(charlize))
where kevin.name="Kevin Bacon"
and charlize.name="Charlize Theron"
return [x in p | coalesce(x.name,x.title, type(x))]

The benefit of the change is that Paths are more type safe now, although it took a fair bit of convincing for me to agree with them. 改变的好处是Paths现在更加类型安全,虽然我同意它们有一点令人信服。 The real use case for this kind of query is far and few between. 这种查询的真实用例之间的差距很小。

Here's another solution: 这是另一个解决方案:

MATCH (kevin:Person {name="Kevin Bacon"}), (charlize:Person {name:"Charlize Theron"})
MATCH p= shortestPath( (kevin)-[:ACTED_IN*]-(charlize) )

WITH nodes(p)+rels(p) AS c, length(p) AS l 
RETURN reduce(r=[], x IN range(0,l) | r + (c[x]).name + type(c[l+x+1]))

Which re-aggregates the path into a collection and then just uses the path-length as an offset to access the second half. 将路径重新聚合到集合中,然后仅使用路径长度作为访问后半部分的偏移量。

Reduce is used to "flatten" the collection, if you don't need that, this also works. Reduce用于“展平”集合,如果你不需要,它也可以。

MATCH (kevin:Person {name="Kevin Bacon"}), (charlize:Person {name:"Charlize Theron"})
MATCH p= shortestPath( (kevin)-[:ACTED_IN*]-(charlize) )

WITH nodes(p)+rels(p) AS c, length(p) AS l 
RETURN [x IN range(0,l) | [c[x]).name + type(c[l+x+1])]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM