How can property value of one node change simultaneously (automatically) when other node’s value changes?

Hi,

I wanna know how can I make property value of one node change simultaneously when other node’s value changes.

For example, I have three nodes called "Andy", "Michael" and "Family". "Andy" and "Michael" are couple, and they are both part of the "Family". Here are the codes:

CREATE (andy:Person { name: 'Andy', pay: 100 })

CREATE (michael:Person { name: 'Michael', pay: 200})

CREATE (Family:Person { name: 'Family', sum_pay: 0})
MATCH (a:Person),(b:Person)
WHERE a.name = 'Andy' AND b.name = 'Michael'
CREATE (a)-[r:FRIEND_OF]->(b)
RETURN *

MATCH (a:Person),(c:Person)
WHERE a.name = 'Andy' AND c.name = 'Family'
CREATE (a)-[r:PART_OF]->(c)
RETURN *

MATCH (b:Person),(c:Person)
WHERE b.name = 'Michael' AND c.name = 'Family'
CREATE (b)-[r:PART_OF]->(c)
RETURN *

Then, I wanna get the sum of pay from both Andy and Michael, and put the value into the "sum_pay" in "Family". So I use "set" to make "sum_pay = pay of Andy + pay of Michael". After that, I change the pay of Andy, however, the value of sum_pay does not change, which is supposed to change according to human understanding.

So, I wanna ask if there is any solution in Cypher that can help to change the value of sum_pay automatically while the value of pay of Andy and pay of Michael change. Many thanks!

Greetings!
Eve

Have a look at APOC triggers - they are intended for situations where you want to make changes to the graph that depend on a change that just arrived.

In your case, the trigger would execute on assignedNodeProperties, and the trigger code can just be regular cypher, so setting the sum on the family should be straightforward.

1 Like

Hi David,

Thanks for kind help! I just figured the solution out and share my steps here:

Firstly, enable apoc.trigger.enabled=true in $NEO4J_HOME/conf/apoc.conf.

Then, create nodes:

MERGE (s:Student {studentId: "10889",name:"eve"})
MERGE (math:Subject:Math {marks: 20})
MERGE (eng:Subject:English {marks: 20})
MERGE (physics:Subject:Physics {marks: 20})
MERGE (s)-[:HAS_SUBJECT]->(math)
MERGE (s)-[:HAS_SUBJECT]->(eng)
MERGE (s)-[:HAS_SUBJECT]->(physics)

Next, create trigger:

call apoc.trigger.add("cal_total","MATCH (s:Student)-[r:HAS_SUBJECT]->(sub:Subject)
WITH s, sum(sub.marks) as total
set s.mark = total",{phase:'before'});

Here, I make the property "mark" of student change with values of subjects' marks. Also, you can make it as a new node (see Need to create a trigger to Sum the node property).

At last, I get the results I want:D Hope it will also help others who need it!

Also thanks to the community!

Cheers!
Eve

1 Like