Find nodes in for a relationship recursively (deep relation)

Hi :wave:

Im trying to find all the nodes with a relationship recursively for a specific node and a specific relation type.

In my case I just got one type of relationship and one type of node. Note: There are cycles in the graph.

The query I use is:

MATCH (n: MyNode {Identifier: "test"})
WITH n
MATCH (n)<-[r:CHILD*]-(child: MyNode)
RETURN child.Identifier as identifier

The query never end ... I don't know what I could do.

If what I'm trying to do is not clear: I'm just trying to get the deep dependencies or children of children of children ... for a specific node.

  • Neo4j 4.1.0
  • Neo4j Desktop 1.3.4

Memory limits?

It's very likely that your [r:CHILD*] is trying to load your entire database.

Try an EXPLAIN first

An explain will estimate how many records it will operate on, which should give you a more clear picture of what is going on.

EXPLAIN MATCH (n: MyNode...

Take a Look

Instead of RETURN child.Indentifier, have the Browser show you the graph. That might also give you some insights as to what is going on:

MATCH (n: MyNode {Identifier: "test"})<-[r:CHILD*]-(child: MyNode)
RETURN n, r, child
LIMIT 500

Though, you might want to reduce how deep you're trying to look by changing [r:CHILD*] into [r:CHILD*1..5] or similar. On that note, while troubleshooting, just returning slices of depth might better clarify things as well:

MATCH (n: MyNode {Identifier: "test"})<-[r:CHILD*2]-(child: MyNode)
RETURN child.Identifier
LIMIT 500

Notes for testing

WITH range(1,19) as x  UNWIND x AS z MERGE (a:Test {name:z}) MERGE (b:Test {name:(z+1)}) MERGE (a)<-[:REL]-(b);

MATCH (a:Test {name:1})<-[r:REL*]-(b) RETURN b.name;
1 Like

If there are cycles in the graph Cypher requires more memory to keep all the distinct paths in memory.

You can use apoc.path.expandConfig to do this efficiently.

MATCH (n: MyNode {Identifier: "test"})
WITH n
CALL apoc.path.expandConfig(n, {
        relationshipFilter: '<CHILD',
        minLevel: 1,
        maxLevel: 40,
        uniqueness: 'NODE_GLOBAL'
    }) yield path
WITH last(nodes(path)) as child
RETURN child.Identifier as identifier 
3 Likes

Thanks guys for the answers ^^

It helps me a lot.

The query of @anthapu seems to work very nice ^^

I have to dig a bit on "EXPLAIN".

thanks ^^

cc @tony.chiboucas