NEO4J:查找断开连接的节点 [英] NEO4J: Finding disconnected nodes
问题描述
我有这个样本数据
使用示例查询
CREATE (a1:A {title: "a1"})
CREATE (a2:A {title: "a2"})
CREATE (a3:A {title: "a3"})
CREATE (b1:B {title: "b1"})
CREATE (b2:B {title: "b2"})
MATCH (a:A {title: "a1"}), (b:B {title: "b1"})
CREATE (a)-[r:LINKS]->(b)
MATCH (a:A), (b:B) return a,b
我要实现的目标:
What I am trying to achieve:
- 找到所有未连接到节点类型B的节点类型A(ans:a2,a3)
- 找到所有未连接到节点类型A(节点:b2)的节点类型B
- 这两个要求都应该是双向的,并且具有相同的查询模板.
我到达的地方
获取所有未连接到B的A:按预期方式获取a2和a3
Get all A not connected to B: gets me a2 and a3 as expected
MATCH path=(a:A)-[r]-(b:B)
WHERE (a)-[r]-(b)
WITH collect(a) as al
MATCH (c:A)
WHERE not c IN al
RETURN c
获取所有断开连接的B,同时得到不正确的b1和b2,并显示"al"表明该列表为空
Get all disconnected B, I get both b1 and b2 which is incorrect, and printing "al" revealed that the list is empty
MATCH path=(b:B)-[r]-(a:A)
WHERE (b)-[r]-(a)
WITH collect(b) as al
MATCH (c:B)
WHERE not c IN al
RETURN c
一些
WHERE (b)-[r]-(a) **!=** WHERE (a)-[r]-(b)
即使我将方向设为双向(未提及)
even if I have the the direction as bi-directional (not mentioned)
如果在第二个查询中将其更改为WHERE (a)-[r]-(b)
,则它可以工作,但是我需要一个通用的双向查询.
If I change it to WHERE (a)-[r]-(b)
in the second query then it works, but I want a generic bi-directional query.
推荐答案
Use the path pattern in where
:
MATCH (a:A) WHERE NOT (a)-[:LINKS]-(:B)
RETURN a;
MATCH (b:B) WHERE NOT (b)-[:LINKS]-(:A)
RETURN b;
或合并为一个查询:
OPTIONAL MATCH (a:A) WHERE NOT (a)-[:LINKS]-(:B)
WITH collect(a) AS aNodes
OPTIONAL MATCH (b:B) WHERE NOT (b)-[:LINKS]-(:A)
WITH aNodes,
collect(b) AS bNodes
RETURN aNodes, bNodes
更新:为什么原始查询会产生错误的结果?
Update: why the original query produces an incorrect result?
我认为这是一个错误.问题是,当您为where
中的关系使用变量时,即使未指定,模式也会隐式使用从左到右的方向:
I think this is a bug. The problem is that when you use a variable for a relationship in where
, the pattern implicitly uses the direction from left to right, even if it is not specified:
// Will return 0, but for test data should return 1
MATCH (b:B)-[r]-(a:A) WHERE (b)-[r]-(a)
RETURN COUNT(*);
// Will return 1
MATCH (b:B)-[r]-(a:A) WHERE (b)<-[r]-(a)
RETURN COUNT(*);
// Will return 1
MATCH (b:B)-[r]-(a:A) WHERE (b)--(a)
RETURN COUNT(*);
// Will return 1
MATCH (b:B)-[r]-(a:A) WHERE (a)-[r]-(b)
RETURN COUNT(*);
这篇关于NEO4J:查找断开连接的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!