How to return the number of incoming and outgoing relationships for each Node

I want to calculate the number of incoming relationships and the number of outgoing relationships for each node (this gives some insight).

I can get the number of incoming (or outgoing) requests, for example:

MATCH outg=(a)-->(b)
RETURN a.name, labels(a) AS Stereotype,count(rels(outg)) AS out
ORDER BY out DESC

It works.

If, however, I try to add an incoming relationship:

MATCH outg=(a)-->(b), incom=(c)-->(a)
RETURN a.name, labels(a) AS Stereotype,count(rels(outg)) AS out, count(rels(incom)) AS in
ORDER BY out DESC

then it does not give what I expect. In this case, both the incoming and outgoing values ​​coincide and are much higher than on their own (therefore, some kind of multiplication occurs).

How to do this and what is wrong with the logic used in the second case?

+4
source share
4 answers

I voted for the answers of Nicole and Sam.

However, I think it is much simpler:

MATCH (a)
RETURN id(a), labels(a) as stereotype, 
size((a)-->()) as out, size((a)<--()) as in

id(a) , .

+14

. , :

MATCH (a)-[r]-(b)
RETURN COALESCE(a.name, a.title), LABELS(a) AS Label,
       SUM(CASE WHEN STARTNODE(r) = a THEN 1 ELSE 0 END) AS outgoing,
       SUM(CASE WHEN STARTNODE(r) = b THEN 1 ELSE 0 END) AS incoming
ORDER BY outgoing DESC

: http://console.neo4j.org/r/6ebvy8

+2

. .

MATCH (a)
OPTIONAL MATCH (a)-->(b)
WITH a, LENGTH(COLLECT(b)) AS out
OPTIONAL MATCH (c)-->(a)
RETURN a.name, labels(a) AS Stereotype, out, LENGTH(COLLECT(c)) AS in 
ORDER BY out DESC;

, .

, , , COUNT(), , ( ) .

+2
MATCH outg=(a)-[og]->(b), incom=(c)-[ic]->(a) RETURN id(a), labels(a) AS Stereotype,count(og) AS out, count(ic) AS in ORDER BY out DESC
0

All Articles