Reputation: 5376
I have a path with node,relation,node,relation,... collection. I would like to find node/nodes that have relation to all nodes in this path.
Can someone give example query in Cypher?
For now I have
START startNode=node(3), endNode=node(5)
MATCH path=startNode-[:CONNECT*]->endNode
WITH path, relationships(path) AS connections, nodes(path) AS nodes
And the problem is I don't know how to use nodes collection to find a node/nodes with have relation to all nodes in this collection. The relation is typed :CONTAINS and it goes from searched node to node in node collection. All of the nodes in collection must have relation to searched node.
Upvotes: 1
Views: 506
Reputation: 2592
This is the query that should return the collection of the nodes that have the relationship [:CONTAINS] to the nodes "midNode" on the path with the specified starting and ending point. It groups the desired "searchedNode" by the path.
START startNode=node(3), endNode=node(5)
Match path=startNode-[:Connect*]->midNode-[:Connect*]->endNode, searchedNode-[:CONTAINS]->midNode
Return distinct path, collect(searchedNode) as searchedNodes
Update: It is to be noted that the identifier 'midNode' represents every node on the path between the two specified starting and ending nodes because of the variable length relationships [:Connect*] that connects it to the starting and ending points. Concretely, it represents the node('m1') one step away from the starting node as in this case startNode-[:Connect]->m1-[:Connect]->...->endNode; and 'm2' that is two steps away from the starting node as in this case startNode-[:Connect]-()-[:Connect]->m2-[:Connect]->...->endNode. As a matter of fact, the matched paths would be a collection of paths each of which corresponds to one node between the startNode and the endNode. Since we only want one path for all of the middle nodes on the path, the DISTINCT is used to remove the duplicate paths, and the searchedNode would be grouped by the key that is the path, so the collection of the searchedNode would be the collection of all the nodes that are related to all the nodes on the path between the startNode and the endNode.
Upvotes: 1