For that approach (shortestPath from each of the starting nodes to the closest node within a pre-matched set) you can use APOC path expander procedures. We have the concept of endNodes, where you can supply a list of possible nodes that you want to expand to and end upon, and we can also supply a limit for the number of paths to return per procedure call. We'll use apoc.path.spanningTree()
here, which uses a type of traversal uniqueness such that a single node is never visited more than once, and it also uses breadth-first for expansion. If you only needed nodes instead of paths, then you could use apoc.path.subgraphNodes()
instead.
Here's an example of usage:
// first match to and collect end nodes
MATCH (n:label2)
WITH collect(n) as endNodes
MATCH (n:label1)
// proc call will be executed per n node, finding the first shortest path found from n to one of the end nodes
CALL apoc.path.spanningTree(n, {endNodes:endNodes, limit:1}) YIELD path
RETURN n, path as shortestPath