Neo4J Cypher - Count Relationships of Matched Node

2020-04-21 02:10发布

问题:

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:

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. 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:

Here you can see all the relationships:

Any help will be appreciated. Thanks.

回答1:

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:

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