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

问题描述 投票:0回答:2

我想获取所有未连接到给定节点集的节点。假设我有 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
neo4j cypher
2个回答
2
投票

此查询应该执行您想要的操作,但是,我要提醒您,根据数据库中不匹配的朋友数量的大小,您可能会获得很多匹配项。

// 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

0
投票

尝试这个查询:

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*]-
不是有方向的)。 然后它返回不在该集合中的所有节点,即它们没有通过
(a:Friend {name: "A"})
类型的关系连接到
:Is_Friend_Of

© www.soinside.com 2019 - 2024. All rights reserved.