Cypher sum property for inbound and outbound relationships (Neo4j)

I have several inbound and outbound links for node (Neo4J).

Each relation has a numerical property "weight"

I need to get the difference between inbound and outbound weights for node.

I tried this query but return 0 for both sums, although the sum of the incoming weights is 20.

MATCH out=(n:Person)-[r:FRIEND]->(), in=(n:Person)<-[s:FRIEND]-() WHERE n.personid='12345' RETURN sum(r.fweight), sum(s.fweight); 

Also, I tried this ... and it crashes / doesn't return

 MATCH (n:Person)-[r:FRIEND]->() MATCH (n:Person)<-[s:FRIEND]-() WHERE n.personid='12345' RETURN sum(r.fweight) , sum(s.fweight) 

Any clue ???: D

0
neo4j cypher
source share
2 answers

Probably because the property name "fweight" in your "Return" does not match the name "weight", which is actually used for the relationship "r" or "s". It should work if you change it to

 RETURN sum(r.weight), sum(s.weight) 

But the result is the sum over all tuples (r, s), which will include many duplicates of r and duplicates of s.

To get the exact amount, you can get a collection of different r and s, and then summarize over such collections,

 RETURN reduce(sumr = 0, x in collect(distinct r)|sumr + x.weight) as sumr, reduce(sums = 0, x in collect(distinct s)|sums + x.weight) as sums 

The console that displays a direct sum query on the properties "r" and "s" is here, http://console.neo4j.org/?id=cqs2h7

The console that displays the collection request is located here http://console.neo4j.org/?id=9st2mq

You would notice that although both of them return amounts, the results of the first query with β€œsum RETURN (r.weight), sum (s.weight)” include duplicate relations β€œr” and β€œs”, while the second query with collections removes duplicates and returns the desired amount.

+2
source share

In this case (console.neo4j.org/?id=cqs2h7) you get each amount twice.

Each entry and exit is a unique combination, so you get everything in each, and it all adds up.

If you change RETURN to ID(r), ID(s), SUM(r.weight), SUM(s.weight) , you will see that the result set contains each identifier (r) for each identifier.

You can try the following:

 MATCH (n:Person)-[r:FRIEND]->() WHERE n.personid ='12345' WITH n, SUM(r.weight) AS sumR MATCH (n:Person)<-[s:FRIEND]-() RETURN sumR, SUM(s.weight) 

Now you first get the SUM from out rel. Then you get the amount in rel.

0
source share

All Articles