我想不出比查找每个类型对、检查它们是否未连接到其他类型、然后将每个子查询与UNION 结合起来更好的查询。这会导致一个相当大的查询。也许其他人可以想到一个更动态的查询。
MATCH (n1:Type1)--(n2:Type2)
OPTIONAL MATCH (n2)--(n3:Type3)
OPTIONAL MATCH (n3)--(n4:Type4)
OPTIONAL MATCH (n4)--(n5:Type5)
WITH n1, n2, n3, n4, n5
WHERE n3 IS NULL
RETURN n1, n2, n3, n4, n5
UNION
MATCH (n2:Type2)--(n3:Type3)
OPTIONAL MATCH (n2)--(n1:Type1)
OPTIONAL MATCH (n3)--(n4:Type4)
OPTIONAL MATCH (n4)--(n5:Type5)
WITH n1, n2, n3, n4, n5
WHERE n1 IS NULL AND n4 IS NULL
RETURN n1, n2, n3, n4, n5
UNION
MATCH (n3:Type3)--(n4:Type4)
OPTIONAL MATCH (n3)--(n2:Type2)
OPTIONAL MATCH (n2)--(n1:Type1)
OPTIONAL MATCH (n4)--(n5:Type5)
WITH n1, n2, n3, n4, n5
WHERE n2 IS NULL AND n5 IS NULL
RETURN n1, n2, n3, n4, n5
UNION
MATCH (n4:Type4)--(n5:Type5)
OPTIONAL MATCH (n4)--(n3:Type3)
OPTIONAL MATCH (n3)--(n2:Type2)
OPTIONAL MATCH (n2)--(n1:Type1)
WITH n1, n2, n3, n4, n5
WHERE n3 IS NULL
RETURN n1, n2, n3, n4, n5
更新:
无需返回NULL,查询可以缩短:
MATCH (n1:Type1)--(n2:Type2)
WHERE NOT (n2)--(:Type3)
RETURN n1, n2
UNION
MATCH (n1:Type2)--(n2:Type3)
WHERE NOT (n1)--(:Type1) AND NOT (n2)--(:Type4)
RETURN n1, n2
UNION
MATCH (n1:Type3)--(n2:Type4)
WHERE NOT (n1)--(:Type2) AND NOT (n2)--(:Type5)
RETURN n1, n2
UNION
MATCH (n1:Type4)--(n2:Type5)
WHERE NOT (n1)--(:Type3)
RETURN n1, n2