Neo4J Cypher-匹配节点的计数关系 [英] Neo4J Cypher - Count Relationships of Matched Nodes

查看:470
本文介绍了Neo4J Cypher-匹配节点的计数关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小项目,我必须维护Twitter等用户之间的关注。我正在尝试进行查询,以返回某个节点的关注者,我们将其称为 X节点。因此,查询返回 X的跟随者以及 X的跟随者的跟随者数以及 X的跟随者正在跟随的节点数,其中包括 X。对不起,文字游戏。让我们看一个带有图像的示例:

I am working on a small project where I have to maintain follows between users like twitter. I am trying to make a query that returns the followers of a certain node, let's call it "X" node. So the query returns the followers of "X" and the count of the followers of the followers of "X" and the count of how many nodes the followers of "X" are following, including "X" in that count. Sorry for the wordplay. Let's see an example with images:

我有以下节点:

我想知道节点2的所有关注者以及我之前提到的关注者的数量。我创建了下一个查询:

And I want to know all the followers of Node 2 and the counts I mentioned before of its followers. I created the next query:

MATCH (:User{id:2})<-[:Follows]-(followers)
OPTIONAL MATCH (followers)-[r1:Follows]->(:User)
OPTIONAL MATCH (:User)-[r2:Follows]->(followers)
RETURN followers.id, count(r1) AS Follows, count(r2) AS Following;

但是它失败了两个值:Node 1跟随的节点数和遵循节点6:

But it fails in two values: The count of nodes the Node 1 follows and the count of nodes that follows Node 6:

在这里您可以看到所有关系:

Here you can see all the relationships:

任何帮助将不胜感激。谢谢。

Any help will be appreciated. Thanks.

推荐答案

我认为背对背进行两个可选匹配都会产生一些重复的结果(请考虑每个输出)阶段,其中涉及到相关的变量...每个关注者跟随者的多个行匹配与每个关注者跟随者的所有行匹配的叉积)。

I think doing both of your OPTIONAL MATCHES back to back are resulting in some duplicate results (consider the output at each stage with the variables involved...multiple row matches for who each follower is following with a cross product to all the row matches of who is following each follower).

同时您可以通过在每个可选匹配项之后组合数据(获取计数)来解决此问题,更好的方法是从使用可选匹配项切换,而直接使用SIZE函数获取关系数:

While you could fix this by assembling your data (getting the count) after each OPTIONAL MATCH, a better approach is to switch from using OPTIONAL MATCHES and instead get the number of relationships directly with the SIZE function:

MATCH (:User{id:2})<-[:Follows]-(followers)
RETURN followers.id, SIZE((followers)-[:Follows]->()) AS Follows, SIZE(()-[:Follows]->(followers)) AS Following

这篇关于Neo4J Cypher-匹配节点的计数关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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