12
votes

I am trying to retrieve a unique set of elements linked to a given graph node. I have some nodes loaded into a Neo4j graph database, which are connected using a 'TO' relationship (e.g. node 6 connects 'TO' node 7). I have been able to retrieve all paths between my start node and others linked by the 'TO' relationship using:

    start a = node(6)
    match p = (a)-[r:TO*..]->(b)
    return distinct EXTRACT(n in nodes(p): n);

This gives me output paths that are distinct, but still have duplicate node values, e.g.:

    +-------------------------------------------------------+
    | p                                                     |
    +-------------------------------------------------------+
    | [Node[6]{},:TO[5] {},Node[7]{}]                       |
    | [Node[6]{},:TO[5] {},Node[7]{},:TO[9] {},Node[11]{}]  | 
    etc...

How can I combine these paths into a single list containing unique path values? I have tried using COLLECT but this just results in a nested version of the above results:

    start a = node(6) 
    match p = (a)-[r:TO*..]->(b) 
    return collect(distinct p);

    [[Node[6]{},:TO[5] {},Node[7]{}],[Node[6]{},:TO[5] {},Node[7]{},:TO[9] {}, ... ]    
1

1 Answers

23
votes

I'm confused about exactly the result you want (can you give an example if this isn't right?). Do you want paths or do you want nodes? If you want nodes, then maybe you just want:

start a = node(6)
match (a)-[:TO*]->(b)
return collect(distinct b);