简体   繁体   English

Neo4J Cypher-匹配节点的计数关系

[英]Neo4J Cypher - Count Relationships of Matched Nodes

I am working on a small project where I have to maintain follows between users like twitter. 我正在做一个小项目,我必须维护Twitter等用户之间的关注。 I am trying to make a query that returns the followers of a certain node, let's call it "X" node. 我正在尝试进行一个查询,以返回某个节点的关注者,我们称其为“ X”节点。 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. 因此,查询返回“ X”的跟随者和“ X”的跟随者的跟随者计数以及“ X”的跟随者正在跟随多少节点的计数,其中包括“ X”。 Sorry for the wordplay. 对不起,文字游戏。 Let's see an example with images: 让我们看一个带有图像的例子:

I have the following nodes: 我有以下节点:

节点

And I want to know all the followers of Node 2 and the counts I mentioned before of its followers. 我想知道节点2的所有关注者以及我之前提到的关注者的数量。 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;

But it fails in two values: The count of nodes the Node 1 follows and the count of nodes that follows Node 6: 但是它失败了两个值:节点1跟随的节点数和节点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). 我认为背对背进行两个可选匹配都会导致某些重复结果(请在每个阶段的输出中包含所涉及的变量...多个行匹配项,每个关注者针对谁的跟随者加上与所有行匹配项的叉积谁在关注每个关注者)。

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: 虽然您可以通过在每个可选匹配项之后组装数据(获取计数)来解决此问题,但是更好的方法是从使用可选匹配项切换,而直接使用SIZE函数获取关系数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM