Neo4j技术问询:查找未与对应类型节点关联的节点
Hey there, based on your sample graph data (where a1 is linked to b1, while a2/a3 have no connections to any B nodes, and b2 has no connections to any A nodes), here are the exact Cypher queries to meet your two requirements:
You can use either of these two approaches—both will return a2 and a3 as expected:
Using
WHERE NOT EXISTS(explicit check for missing relationships)MATCH (a:A) WHERE NOT EXISTS((a)-[:LINKS]->(:B)) RETURN a.title AS unlinked_A_nodesThis query matches every A node, then filters out any that have a
LINKSrelationship to a B node. The remaining nodes are exactly the ones with no associations to B.Using
OPTIONAL MATCH+WHERE(check for missing matches)OPTIONAL MATCH (a:A)-[r:LINKS]->(:B) WHERE r IS NULL RETURN a.title AS unlinked_A_nodesHere, we try to match a
LINKSrelationship from each A node to a B node. If no such relationship exists,rwill beNULL—we filter for those cases to get our target nodes.
Similarly, we can apply the same logic in reverse to get b2:
Using
WHERE NOT EXISTSMATCH (b:B) WHERE NOT EXISTS((:A)-[:LINKS]->(b)) RETURN b.title AS unlinked_B_nodesThis matches every B node, then excludes any that have an incoming
LINKSrelationship from an A node.Using
OPTIONAL MATCH+WHEREOPTIONAL MATCH (:A)-[r:LINKS]->(b:B) WHERE r IS NULL RETURN b.title AS unlinked_B_nodesWe attempt to match an incoming
LINKSrelationship from an A node to each B node. Nodes where no such relationship exists (sorisNULL) are our desired results.
内容的提问来源于stack exchange,提问作者Srinath Ganesh

