Reputation: 421
I want to get the start and end node for a list of relationships. In the example below, I start with a node and its related to the next node, and that next node to related to another node via the same relationship.
I tried the following cypher query, but it doesn't work.
start n=node:index('name:"iris"')
match n-[r:childof*]->parent
return startNode(r),endNode(r)
Any ideas? I would think a foreach on r will do the trick but cant seem to make the could work.
Upvotes: 2
Views: 4136
Reputation: 9952
As you don't say otherwise I'm assuming you are using current version (2.0) of Neo4j, and that "it doesn't work" means that startNode(r)
complains about r being a collection, not a relationship. To run a function or evaluate an expression for every member of a collection use extract or reduce (foreach is for write operations)
RETURN EXTRACT(rel IN r | [startNode(rel),endNode(rel)]) as nodePairCollection
which for a path like a-[:REL]->b-[:REL]->c-[:REL]->d
gives you a result like [[a,b],[b,c],[c,d]]
, or
RETURN REDUCE(acc = [], rel IN r | acc + startNode(rel) + endNode(rel)) as flattenedNodeCollectionWithDulicates
which gives [a,b,b,c,c,d]
, or yet do some filtering on one of these.
That's how to explicitly get start node and end node from a relationship. But for your particular type of query above, where all the relationships in r have the same direction, you may be able to make do with just retuning the nodes on the path since they will already be correctly ordered
MATCH path=n-[r:childof*]->parent
RETURN nodes(path)
which gives [a,b,c,d]
, but you can only trust this as representing relationship direction when you have explicitly included that in your pattern.
Upvotes: 3