获取Neo4j中未连接到特定节点的节点

jexiocij  于 8个月前  发布在  其他
关注(0)|答案(2)|浏览(92)

我想得到所有没有连接到给定节点集的节点。假设我有5个节点A,B,C,D,E。现在A->B->C与:Is_Friend关系相连。现在我想得到所有没有连接到A的节点(即D和E)。
我尝试了这个查询,但它不工作

MATCH (a:Friend{name:"A"})-[:Is_Friend_Of*]->(b:Friend) 
MATCH (c:Friend) 
WHERE NOT (c)-[:Is_Friend_Of]->(b)
RETURN c

字符串

tquggr8v

tquggr8v1#

这个查询应该做你想做的事情,但是,我会提醒你,根据你数据库中不匹配的朋友数量的大小,你可能会得到很多匹配。

// match the single longest chain of friends in a :Is_Friend_Of relationship
// starting with 'A' that is possible
MATCH path=(a:Friend {name:"A"})-[:Is_Friend_Of*]->(b:Friend)
WHERE NOT (b)-[:Is_Friend_Of*]->()
WITH path

// then find the other friends that aren't in that path
MATCH (c:Friend) 
WHERE NOT c IN nodes(path)
RETURN c

字符串

htrmnn0y

htrmnn0y2#

试试这个查询:

match(a:Friend {name: "A"})-[:Is_Friend_Of*]-(b)
with collect(distinct b) as all_connected_to_a
match(n:Friend) where not n in all_connected_to_a return n;

字符串
它首先得到所有连接到(a:Friend {name: "A"})的节点的集合(包括节点a,因为模式-[:Is-Friend_Of*]-不是有向的)。然后返回所有不在该集合中的节点,即它们没有通过:Is_Friend_Of类型的关系连接到(a:Friend {name: "A"})

相关问题