使用CYPHER查找报告链外的节点

时间:2016-07-12 21:16:06

标签: neo4j match cypher

我添加了一张图片,使这个问题更容易解决。

我有一个CYPHER查询,我从经理A开始,我想找出:

a)所有工作人员:REPORTS_TO他们在报告链中。使用图表,答案:B,C,D,B1,B2,B11,D1,D2

b)谁是报告:知道谁不在报告链中。使用图表,回答:Z,W,X

我能够回答a)而不是b)而不包括C,D1和D2。 谁有人如何解决这个问题?

我曾尝试运行查询来查找报告,然后使用WITH子句将结果传递到第二个查询,但我无法排除C,D1和DC

Object network

1 个答案:

答案 0 :(得分:0)

我认为我找到了一个有效的查询,但它只返回报告链外的节点。在同一查询中返回a)和b)可能很困难。

首先,创建图形(应该与您的图表匹配,除了我使用的是小写):

merge (a:Person{name:"a"})
merge (b:Person{name:"b"})
merge (c:Person{name:"c"})
merge (d:Person{name:"d"})
merge (b1:Person{name:"b1"})
merge (b2:Person{name:"b2"})
merge (b11:Person{name:"b11"})
merge (d1:Person{name:"d1"})
merge (d2:Person{name:"d2"})
merge (z:Person{name:"z"})
merge (w:Person{name:"w"})
merge (x:Person{name:"x"})

merge (b)-[:REPORTS_TO]->(a)
merge (c)-[:REPORTS_TO]->(a)
merge (d)-[:REPORTS_TO]->(a)

merge (b1)-[:REPORTS_TO]->(b)
merge (b2)-[:REPORTS_TO]->(b)
merge (b11)-[:REPORTS_TO]->(b1)

merge (d1)-[:REPORTS_TO]->(d)
merge (d2)-[:REPORTS_TO]->(d)

merge (z)-[:KNOWS]->(b)
merge (z)-[:KNOWS]->(b11)

merge (b2)-[:KNOWS]->(w)
merge (b2)-[:KNOWS]->(c)
merge (b2)-[:KNOWS]->(d1)

merge (d1)-[:KNOWS]->(x)

merge (c)-[:KNOWS]->(d2)

现在查询

MATCH (:Person{name:"a"})<-[:REPORTS_TO*]-(reporter:Person)-[:KNOWS]-(other:Person)
WITH COLLECT(reporter) AS reporters, COLLECT(other) AS others
WITH FILTER (o IN others WHERE NOT o IN reporters) AS outsiders
UNWIND outsiders AS outsider
RETURN DISTINCT outsider

这将返回人Z,W和X.可能有一个更优雅的解决方案,但我还没有发现它。也许它隐藏在明显的视线中?