1
votes

For a graph like this sample

Graph Sample

If we know a starting point on one of the child nodes under a specific account, how can we traverse all related nodes regardless of direction up to the Customer node, but not traverse back down to another account, so basically always stop at the Customer (using Cypher in Neo4j)

I currently have a query like this, but i dont know how to make it stop after getting to the customer node, but still keep traversing the links of any nodes below

MATCH (p:Customer{key:'Customer:1011'})-[*8]-(connected) RETURN distinct(connected.key)

Basically i want to have a generic query that can take any label/key that uniquely identifies a starting node below the Customer node, and traverse all children excluding paths that go to other accounts

1

1 Answers

0
votes

Welcome to StackOverflow! Yes, you can do this by specifying the label the last node in the path must have - let's walk through it.

First, let's create that sample graph - I've invented some plausible relationship names:

MERGE (cus1: Customer { id: 1 })
MERGE (acc1: Account { id: 1 })
MERGE (acc2: Account { id: 2 })
MERGE (con1: Contract { id: 1 })
MERGE (con2: Contract { id: 2 })
MERGE (bui1: Building { id: 1 })
MERGE (bui2: Building { id: 2 })
MERGE (sp1: ServicePoint { id: 1 })
MERGE (sp2: ServicePoint { id: 2 })
MERGE (b1: Bill { id: 1 })
MERGE (b2: Bill { id: 2 })
MERGE (b3: Bill { id: 3 })
MERGE (b4: Bill { id: 4 })
MERGE (cus1)-[:HOLDS]->(acc1)
MERGE (cus1)-[:HOLDS]->(acc2)
MERGE (acc1)-[:CONTAINS]->(con1)
MERGE (acc2)-[:CONTAINS]->(con2)
MERGE (bui1)-[:COVERED_BY]->(con1)
MERGE (bui2)-[:COVERED_BY]->(con2)
MERGE (sp1)-[:BELONGS_TO]->(con1)
MERGE (sp2)-[:BELONGS_TO]->(con2)
MERGE (b1)-[:RELATES_TO]->(sp1)
MERGE (b2)-[:RELATES_TO]->(sp1)
MERGE (b3)-[:RELATES_TO]->(sp2)
MERGE (b4)-[:RELATES_TO]->(sp2)

enter image description here

Now let's say we're starting at a Bill - Bill 2:

MATCH path=(b: Bill { id: 2 })-[*]-(c: Customer)
RETURN path

enter image description here

We've asked for all paths of any length that start at Bill 2 and end with any Customer node. Neo won't return the branch containing Account 1 because it isn't part of any path between Bill 2 and Customer 1. However, we have also not returned Bill 1 for the same reason, even though it's connected to the account we end up at.

If you want the whole subgraph for the matching account, you can do it in two hops - work your way back up to the customer and the account, then work back down to all nodes connected to the account:

MATCH (b: Bill { id: 2 })-[*]-(a: Account)-[]-(c: Customer)
MATCH path=(c)-[]->(a)-[*]-()
RETURN path

enter image description here