3
votes

How can I return nodes and relationships interleaved? Using the Matrix movie database the query

    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
    ...
2

2 Answers

1
votes

This used to be easier, but they broke "the easy way" in 2.0-RC1 when they made Paths not Collections anymore, in Cypher.

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. The real use case for this kind of query is far and few between.

1
votes

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.

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])]]