4
votes

I want to find the difference between the number of all the outgoing edges and the number of all incoming edges to the same node. Nodes are cities and relationships are transfers between them.

I've tried to do this:

MATCH ()-[i:TRANSFERS]->(n:City {name:"London"}),(n:City {name:"London"})-[o:TRANSFERS]->() 
RETURN distinct n.name, count(i) AS incoming, count(o) as outgoing, count(o)-count(i) AS difference
ORDER BY outgoing - incoming DESC

and this:

MATCH ()-[i:TRANSFERS]->(n:City {name:"London"})
OPTIONAL MATCH (n:City {name:"London"})-[o:TRANSFERS]->() 
RETURN distinct n.name, count(i) AS incoming, count(o) as outgoing, count(o)-count(i) AS difference
ORDER BY outgoing - incoming DESC

but they seem not working. Any idea?

2

2 Answers

3
votes

You can use size on the relationship pattern for both incoming and outgoing connections :

MATCH (city:City {name:"London"})
WITH size((city)-[:TRANSFERS]->()) as out, 
     size((city)<-[:TRANSFERS]-()) as in,
     city
RETURN city, in, out, (out - in) as diff
ORDER BY diff DESC
0
votes

I think you need to match the in and out separately (stealing Christophe's answer here):

MATCH (city:City {name:"London"})
WITH city, size((city)-[:TRANSFERS]->()) as out
WITH city, out, size((city)<-[:TRANSFERS]-()) as in,
RETURN city, in, out, (out - in) as diff
ORDER BY diff DESC