0
votes

I have multiple incoming & outgoing relationships for a node (Neo4J).

Each relationship has a numeric property "weight"

I need to get the difference between the incoming & outgoing weights for the node.

I tried this query, but return 0 for both sums, even though sum of 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/doesnt 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

2

2 Answers

2
votes

It's probably because the property name "fweight" in your "Return" is not the same as the one "weight" that is actually used on 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 of the tuple (r, s) that would include many duplicate r, and duplicate s.

To get the exact sum, you can get the collection of the distinct r, and s, then sum over the collections like this,

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 shows the query with the direct sum over the properties of the "r" and "s" is here, http://console.neo4j.org/?id=cqs2h7

The console that shows the query with collection is here, http://console.neo4j.org/?id=9st2mq

You would notice that although both of them return the sums, the results of the first query with "RETURN sum(r.weight), sum(s.weight)" include the duplicated relationships "r" and "s" whereas the second query with collections removes the duplicates and returns the desired sum.

1
votes

On the exmple here (console.neo4j.org/?id=cqs2h7) you're getting each sum twice.

Each in and out is a unique combination, so you're getting every in against every out and it's all summed together.

If you change the RETURN to ID(r), ID(s), SUM(r.weight), SUM(s.weight) you'll see that the result set contains every ID(r) for every ID(s).

You can try this:

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're getting the SUM of the out rel first. Then you get the sum of the in rel.