如何在Cypher中汇总Union的结果? [英] How to aggregate result of Union in Cypher?

查看:373
本文介绍了如何在Cypher中汇总Union的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何在Cypher中汇总Union的结果. 以下示例可以在在线代码段中执行:

I am trying to figure out how to aggregate the result of Union in Cypher. The following example can be executed in Cypher snippets live:

MATCH (n:Crew)-[r:KNOWS]->m
WHERE n.name='Neo'
RETURN n AS name,m
UNION
MATCH (n:Crew)-[r:KNOWS]->m
WHERE n.name='Morpheus'
RETURN n AS name,m

此查询显示三行结果,因为Neo认识一个人,Morpheus认识两个人(请注意查询中的定向链接).假设我们要汇总已知人员.我们可以做这样的事情:

This query shows three rows as result because Neo knows one person and Morpheus two (note the directional link in the query). Let's say that we want to aggregate the known people. We can do something like this:

MATCH (n:Crew)-[r:KNOWS]->m
WHERE n.name='Neo'
RETURN n AS name,count(m) AS c
UNION
MATCH (n:Crew)-[r:KNOWS]->m
WHERE n.name='Morpheus'
RETURN n AS name,count(m) AS c

到目前为止,我们还可以.但是,如果我们要聚合的内容(隐藏的Group By)在第一个查询和第二个查询中,我都不知道如何解决该问题.由于在以前的情况下不会发生这种情况,因此,为了解释起见,我们假设我们有以下查询:

So far we are Ok. However, I don't know how to solve the problem if what we want to aggregate (the hidden Group By) is in both the first and second query. Since this doesn't happen in the previous case, let's assume for the sake of the explanation that we have the following queries:

MATCH (n:Label1)-[:label3]->(:label4)
RETURN n.name as name, n.age as value

MATCH (m:Label2)-[:label5]->(:label6)
RETURN m.surname as name, m.k as value

返回

John, 12

Sam, 17

John, 78

Tim, 12

是否可以做类似的事情

(
MATCH (n:Label1)-[:label3]->(:label4)
RETURN n.name as name, n.age as value
UNION ALL
MATCH (m:Label2)-[:label5]->(:label6)
RETURN m.surname as name, m.k as value
)
RETURN name, sum(value)

要获得下面的结果?

John, 90
Sam, 17
Tim, 12

很明显,我已经尝试过这样的查询,并且它不能编译.因此,我想知道是否存在类似的东西.

Obviously, I already tried such a query and it doesn't compile. Hence, I am wondering if there is something similar.

推荐答案

到目前为止,您无法对UNION的组合结果集进行任何聚合.

As of today you cannot do any aggregation on the combined result set of a UNION.

唯一的方法是通过避免使用UNION来支持更复杂的WHERE:

The only way is to trick around it by avoiding the UNION in favour of a more complex WHERE:

MATCH (n)-[r:label3|label5]->(m)
WHERE ((type(r)='label3') AND ("Label1" in labels(n)) AND ("label4" in labels(m))) OR
((type(r)='label5') AND ("Label2" in labels(n)) AND ("label6" in labels(m)))
RETURN n.name as name, sum(n.age)

这篇关于如何在Cypher中汇总Union的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆