Search code examples
neo4jcypherneo4j-apoc

In Neo4j how do i iteratively traverse the nodes and relationships paths obtained from the startnode till particular relationship property is reached?


Consider I have to obtain all the nodes in the subgraph of n:Customer with customer_id = 4. Starting from this node i have to traverse each node in the path originating with n and break or stop traversing down the path when a relationship with Action property is set to ODC. Each relationship has the property Action with value either ODC or ODSN.

enter image description here

After breaking from one path I have to check the other paths originating from this node n. I have to repeat this process till all paths are traversed and return the relevant nodes. In the image I have provided I have expanded two paths out of the 14 nodes connected to n:Customer (blue node). Each of the purple nodes connected to the blue can be further expanded similar to the other two paths.

I am required to store these nodes in a data structure in Java. Any guidance on how to approach this would be very helpful. Thanks


Solution

  • For Neo4j 5.9+

    To return the subgraph up to but excluding any nodes beyond any relationships with Action = 'ODC':

    MATCH (:Customer {customer_id: 4})-[r WHERE r.Action <> 'ODC']-*(n)
    RETURN DISTINCT n
    

    To return the subgraph up to and including those nodes:

    MATCH path = (:Customer {customer_id: 4})-[r WHERE r.Action <> 'ODC']-*
                   ()-[{Action: 'ODC'}]-()
    UNWIND nodes(path) AS n
    RETURN DISTINCT n
    

    For Neo4j < 5.9

    To return the subgraph up to but excluding any nodes beyond any relationships with Action = 'ODC':

    MATCH (:Customer {customer_id: 4})-[r*0..]-(n)
    WHERE all(rel IN r WHERE rel.Action <> 'ODC')
    RETURN DISTINCT n
    

    To return the subgraph up to and including those nodes:

    MATCH path = (:Customer {customer_id: 4})-[r*0..]-()-[{Action: 'ODC'}]-()
    WHERE all(rel IN r WHERE rel.Action <> 'ODC')
    UNWIND nodes(path) AS n
    RETURN DISTINCT n