1
votes

Given the following data set in Neo4j:

(A)-flows->(B)-flows->(C)-flows->(D)-flows->(Z)
(A)-flows->(E)-flows->(F)-flows->(Z)
(A)-flows->(G)-flows->(Z)

How can I return the subgraph (nodes B, C, D, E, F, G their relationships between each other and the relationships to A and Z) with a Cypher query when only A and Z is known.

Pseudo code:

Match(a)-[rels*](nodes*)-(z)
where a.Id = '123' and z.Id = '456'
return a,rels,nodes,z
1

1 Answers

1
votes

Save the (A)->...->(Z) subgraph to a named path then use the nodes and relationships functions to extract a list of nodes and relationships:

MATCH p=(a {Id: '123'})-[:flows*]->(z {Id: '456'})
RETURN a, nodes(p), relationships(p), z

As pointed out in the comments, nodes(p) also returns a and z. If you do not want those nodes to be returned, omit the first and last elements of the list. Thanks to Bruno Peres and cybersam for their inputs.

MATCH p=(a {Id: '123'})-[:flows*]->(z {Id: '456'})
RETURN a, nodes(p)[1..-1], relationships(p), z

Remark #1. It is also possible to UNWIND these lists to their content process one-by-one.

Remark #2. Depending on the driver your using, you can simply return p and process it in the client's code. For example, the Java driver allows use to return a Path object that has nodes() and relationships() methods returning Iterables.