Neo4j APOC trigger to store updated values

I have created trigger when property of node will update, But i want to log that updated properties or create Log node to store this updated Properties with old Key Values and new Key Values...

This is my APOC trigger

`CALL apoc.trigger.add('setLastUpdate',
'UNWIND keys($assignedNodeProperties) as k
UNWIND $assignedNodeProperties[k] AS map
with map.node as node, collect(map.key) as propertyList
match (n)
WHERE id(n) = id(node) AND NOT "lasts" in propertyList

  //  create (l:Log{id:"logId",nodeId:id(node),timestamp:timestamp()})

', {phase:'afterAsync'});`

Please help me to how do i store all updated old values and new values with key so i can save that updated properties in Log.

Please help

Sorry but in afterAsync the deleted values are no longer available.
You can try this in phase before or after.

Or use CDC change stream for that information that you can then write to an audit log / or back to the graph.

1 Like

@michael.hunger
As per you said i have replaced afterAsync by after and its working

But when i try to update more than one property it created two Log nodes

//Apoc Trigger to update values
<CALL apoc.trigger.add('setLastUpdate',
'UNWIND keys($assignedNodeProperties) as k
UNWIND $assignedNodeProperties[k] AS prop
with prop.node AS node, prop.key AS key, prop.old AS oldValue, prop.new AS newValue

    create (log:Log{id:"logId",nodeId:id(node),
    timestamp:timestamp(),
    name:"Log",
    nVal:newValue,
    key:key,
    oldVal:oldValue}) return log

    ', {phase:'after'});`>

I am new on neo4j i don't know how to handle this old and updated values
i stuck here from last two days..
please provide me code snippet so i can create single Log label with all properties.

Thank you

use MERGE instead of CREATE and create a constraint on Log(nodeId) or use the transaction-id as id.

merge (log:Log{nodeId:elementId(node)})
set log += {
    timestamp:timestamp(),
    name:"Log", // you probably don't need that as you have the label
    nVal:newValue,
    key:key,
    oldVal:oldValue}
return log

Thank you so much @michael.hunger for the help

As per you said to add constraint on Log (nodeId)
I tried your solution and its working

But I have one more concern that is when I am trying to set more than two values then these Log node shows only last values.

`CALL apoc.trigger.add('setLastUpdate',
'UNWIND keys($assignedNodeProperties) as k
UNWIND $assignedNodeProperties[k] AS prop
with prop.node AS node, prop.key AS key, prop.old AS oldValue, prop.new AS newValue

merge (log:Log{nodeId:elementId(node)})
set log += {
timestamp:timestamp(),
nVal:newValue,
key:key,
oldVal:oldValue
}
return log
', {phase:'after'});`

is there any options to set below line values as key in Log()
with prop.node AS node, prop.key AS key, prop.old AS oldValue, prop.new AS newValue

Or any other option please tell me

So I will have all old & updated values with keys

Eagerly wating for your solutions michael