Search code examples
neo4jcypher

return a single path for each target node


I have a graph that looks like below

(:A {id:1}) -> (:B {id:1}) -> (:C {id:1}) -> (:D {id:1})
                           -> (:C {id:2})

(:A {id:2}) -> (:B {id:2}) -> (:C {id:3}) -> (:D {id:2})
                           -> (:C {id:4})
                           -> (:C {id:5})

I want to find paths between A and D. But if I simply do

match p=((:A)->(:B)->(:C)->(d:D))
with p, d as target
return p, target

it will give me 5 paths. What I need is 2 paths. Give me one of the paths from A1 to D1 and one of the paths from A2 to D2. How should i update my query?


Solution

  • You are getting 5 paths because each of your C nodes are linked to a D node. To get only one path, collect paths in a list and pick any one of them. Like this:

    match p=((a:A)-->(b:B)-->(:C)-->(d:D))
    with a, b, d, collect(p) AS paths
    return paths[0] AS p, d AS target