ethrbunny
ethrbunny

Reputation: 10469

Neo4j - apply match to each result of previous match

Situation: graph with numerous end points each of which has one connection to the main graph. This connection may traverse several intervening node->relationship->node before joining the main graph. This final node where each connects has a specific property.

I have a query that walks down this path and finds the node that ultimately joins to the main graph. I have another query that returns a list of the end-point nodes. How would I use the list of nodes from query 2 to feed into query 1 so I could get the results of query 1 for every member of query 2?

Ideally I want something like FOREACH but that's out as query 1 begins with a match statement. It doesn't make any changes. Something akin to create outer_list -> each outer_list_member -> run next query and return single result -> repeat with next list_member


I can run query 1 and get the correct results if I manually specify the unique property ("id") of a given end node. I want to create a list of all end nodes and their connecting node.

Upvotes: 3

Views: 3759

Answers (2)

Michael Hunger
Michael Hunger

Reputation: 41676

Shortest Path returns exactly one path each.

match (n:Label {prop:value})
match p=shortestPath( (n)-[: JOINS*1..5]-(m:Label2 {prop2:value2}) 
return n.name, length(p) as len, m.name 

Otherwise you can also use paths as collection expressions and just return head((n1)-[*..5]-(n2))

expensive operation but you can oder by path length, then aggregate by start node and take the first element of a collect (shortest path is first in the list).

...
with n, p
order by length(p)
return n.name, head(collect(p))

Upvotes: 0

Brian Underwood
Brian Underwood

Reputation: 10856

Cypher's WITH clause is pretty useful for feeding one query into another. Maybe that would be useful?

http://neo4j.com/docs/stable/query-with.html

Upvotes: 2

Related Questions