Nicolas
Nicolas

Reputation: 1263

Neo4j - Find missing node to complete circle

I am trying to get a query that starting from a node, it returns the missing node that, when making a new relation to it, would complete a circle. Also it should respond which is the node that, if the circle is close, will end up having a relationship with the input node. Example:

Let's say I have B -> C and C -> A. In this case, if I pass A as input, I would like to receive { newRelationToMake: B, relationToInputNode: C } as a result, since connecting A -> B will result in a closed circle ABC and the relation that the node A will be having will come from C.

Ideally, this query should work for a maximum of n depths. For example for a depth of 4, with relations B -> C, C -> D and D -> A, and I pass A as input, I would need to receive { newRelationToMake: C, relationToInputNode: D} (since if I connect A -> C I close the ACD circle) but also receive {newRelationToMake: B, relationToInputNode: D }(since if I connect A -> B I would close the ABCD circle).

Is there any query to get this information?

Thanks in advance!

Upvotes: 0

Views: 186

Answers (1)

cybersam
cybersam

Reputation: 67009

You are basically asking for all distinct nodes on paths leading to A, but which are not directly connected to A.

Here is one approach (assuming the nodes all have a Foo label and the relationships all have the BAR type):

MATCH (f:Foo)-[:BAR*2..]->(a:Foo)
WHERE a.id = 'A' AND NOT EXISTS((f)-[:BAR]->(a))
RETURN DISTINCT f AS missingNodes

The variable-length relationship pattern [:BAR*2..] looks for all paths of length 2 or more.

Upvotes: 0

Related Questions