SegFault
SegFault

Reputation: 2190

NEO4J - find all incoming and outgoing edges from a node

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?

Upvotes: 4

Views: 2496

Answers (2)

Brian Underwood
Brian Underwood

Reputation: 10856

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

Upvotes: 0

Christophe Willemsen
Christophe Willemsen

Reputation: 20185

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

Upvotes: 4

Related Questions