How to get in Neo4j's Cypher the nodes that are connected to every other node within a set?

StackOverflow https://stackoverflow.com/questions/23536093

  •  17-07-2023
  •  | 
  •  

Question

I have as input 'N' Nodes, and i want to get 'M' Nodes such as:

'm' is a node that belongs to 'M' where 'm' is directly connected to every single node in 'N'.

how can i do that please?

Was it helpful?

Solution

Complex conditions on a path can be difficult to express in cypher. If the criterion is as simple as in your abstraction, you can collect the 'N' nodes and filter your matched 'M' nodes with ALL and a path predicate.

With a graph like

(:N)<--(m1:M)-->(:N)<--(m2:M)

you want to return (m1) but not (m2), correct? Try

MATCH (n:N)
WITH collect(n) AS nn
MATCH (m:M)
WHERE ALL (n IN nn 
       WHERE n--m)
RETURN m

See console: http://console.neo4j.org/?id=cqrrpe

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top