Neo4j - apply match to each result of previous mat

2019-05-18 04:27发布

问题:

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


  • Query 1: match p=(n {individual end node property})-[r: JOINS*1..5]-(m { joining node property }) return n.name, length(p) as len, m.name order by len limit 1
    -- this gives me the end node and the joining node (via shortest path)
  • Query 2: match node_list = (n {property of all end nodes})

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.

回答1:

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



回答2:

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


标签: neo4j cypher