Search code examples
neo4jcypher

neo4j turn paths into subgraph


Say I have the following graph

       Z
  /         \ 
 /           \  
A -> B -> C -> D
 \          /
  -> X -> Y 
   

I compute the paths

match p=((:A)-[*]->[:D])
return p

This will return three paths (rows): AZD, ABCD and AXYD

But I would like to return a subgraph that contains all the paths between A and D. so the result should be a subgraph. My understanding is that the only format for a subgraph return is nodes and relationships. So a query like below

// query logic
return nodes, relationships

What should I write in the query logic? NOTE:

  1. this is not the entire graph, there are other subgraphs in my graph, so returning the entire graph does not work
  2. A and D are just node types here, there will be many type A and type D nodes and there will be one or multiple paths between each A and D node pair.

Solution

  • One way to retrieve the unique set of nodes and relationships is using apoc

    MATCH p=((:A)-[*]->(:D))    
    RETURN apoc.coll.toSet(
                apoc.coll.flatten(
                     COLLECT(nodes(p))
                )
           ) AS nodes,
           apoc.coll.toSet(
                apoc.coll.flatten(
                     COLLECT(relationships(p))
                )
           ) AS relationships