在Cypher查询(Neo4j)中结合联合后的结果

时间:2016-06-28 13:02:39

标签: graph neo4j cypher

我正在处理图形数据库并编写了一些 Cypher查询

例如

以下查询的第一部分用于计算特定用户的每个人的喜欢总数,所有帖子和查询的其他部分也相似。

查询

match a=(p:FaceBookPost{auther_id:"1"})-[hv:HAVE_LIKE]-(l:FacebookLike)
return COUNT(l.auther_id) as total, (l.auther_id) as authers order by total DESC

UNION ALL

match a=(p:FaceBookPost{auther_id:"1"})-[hv:HAVE_COMMENT]-(l:FacebookComment)
return COUNT(l.auther_id) as total, (l.auther_id) as authers order by total DESC

UNION ALL

match a=(i:InstagramPost{person_id:"1"})-[il:INSTAGRAM_LIKE]-(l:InstagramLike)
return COUNT(i.person_id) as total, (l.person_id) as authers order by total DESC

UNION ALL

match a=(i:InstagramPost{person_id:"1"})-[ic:INSTAGRAM_COMMENT]-(c:InstagramComment)
return COUNT(c.person_id) as total, (c.person_id) as authers order by total DESC

外线:

   | total | authers
---+-------+---------
 1 |     4 | author 1
 2 |     3 | author 2
 3 |     1 | author 3
 4 |     2 | author 1
 5 |     1 | author 2
 6 |     1 | author 3
 . |     . | ........
 . |     . | ........
 . |     . | ........

需要输出:

   | total | authers
---+-------+---------
 1 |     6 | author 1
 2 |     4 | author 2
 3 |     2 | author 3

我已经尝试了不同的方法和不同的查询所需的输出。 但我无法得到任何解决方案。

Cypher有没有办法要求出局?

1 个答案:

答案 0 :(得分:3)

不幸的是,此时无法对UNION的结果进行后期处理。但是,有计划添加 - 请参阅https://github.com/neo4j/neo4j/issues/2725#issuecomment-227973992

但是,在您的示例中,您可以设法完全避免UNION的需要。这将更清楚地理解,更有效。

首先,可以立即组合其中一些MATCH条款:

MATCH (:FaceBookPost{auther_id:"1"})-[:HAVE_LIKE|:HAVE_COMMENT]-(l)
RETURN COUNT(*) as total, (l.auther_id) as authers order by total DESC

UNION ALL

MATCH (:InstagramPost{person_id:"1"})-[:INSTAGRAM_LIKE|:INSTAGRAM_COMMENT]-(l)
RETURN COUNT(*) as total, (l.person_id) as authers order by total DESC

这样做会更好,但仍然需要UNION ALL,因为有两个不同的起点 - 一个标记为:FaceBookPost,另一个标记为:InstagramPost。如果您可以更新您的模型,以便这两者共享一个额外的标签,例如:Post,然后您可以将其缩减为单个查询。

更新模型:

MATCH (p:FaceBookPost) SET p:Post;
MATCH (p:InstagramPost) SET p:Post;

然后查询:

MATCH (:Post{person_id:"1"})-[:HAVE_LIKE|:HAVE_COMMENT|:INSTAGRAM_LIKE|:INSTAGRAM_COMMENT]-(l)
RETURN COUNT(*) as total, (l.person_id) as authers order by total DESC

您可能还想分享关系类型,例如,仅使用:HAVE_LIKE替换:INSTAGRAM_LIKE:LIKED(同时将评论类型替换为:COMMENTED)。