cancel
Showing results for 
Search instead for 
Did you mean: 

How to aggregate all relationships with same parents into one

Atakku
Node

Hi everyone, I'm new to neo4j and I've been trying to find out a way to do this on my own, but couldn't find a way.
For example if i have this dataset

CREATE (a:Address{id: 'a'})
CREATE (b:Address{id: 'b'})
CREATE (c:Address{id: 'c'})

CREATE (a)-[t:Transaction{value: '5'}]->(b)
CREATE (a)-[t:Transaction{value: '10'}]->(b)
CREATE (a)-[t:Transaction{value: '4'}]->(b)
CREATE (b)-[t:Transaction{value: '8'}]->(c)
CREATE (a)-[t:Transaction{value: '6'}]->(c)

How would one display without having hundreds of relationship arrows from one node to another, but rather a single arrow that sums 'value' into a single arrow, for each node.
Having two relationship arrows per pair of nodes (in and out) is fine, but if having a single relationship (subtracting from two and picking the largest left) is viable, that would be better, unless the speed is a concern.

2 REPLIES 2

alexandra
Node Link

Hi @Atakku,

First things first - in order not to create multiple relationships you should use MERGE instead of CREATE. What MERGE does is match an existing pattern and create it only in case if it doesn't exist.
Secondly, in order to sum values you need to convert your value property to integer.
It really depends on how you do your import, but this is the general idea:

MERGE (a:Address{id: 'a'})
MERGE (b:Address{id: 'b'})
MERGE (a)-[t:Transaction]->(b)
ON CREATE SET t.value = 0
ON MATCH SET t.value = t.value + <value_from_your_dataset>

Well I was doing it this way, but I was thinking about keeping the transactions in the database for different purpose.