inersha
inersha

Reputation: 462

How to update a related node in a FOREACH loop?

I'm adding a bunch of nodes to my graph using FOREACH.

However, sometimes these nodes will refer to nodes that already exist (with an existing index), so in that case, I just add some properties to the node.

However, if the node does exist, I also want to update a node that it is related to.

Here's a diagram:

enter image description here

I have written a Cypher query that works:

FOREACH (item in [$list] |
    MERGE (check :label {index: item.index})

    MERGE (check)-[:r]->(related)
    ON CREATE SET
        check.value= item.value,
        check.property= item.stuff
    ON MATCH SET
        check.value= item.value,
        check.proprety= item.stuff,
        related.value = related.value + node.value     
)

However, it always creates an empty (check)-[:r]->(related) relationship on the (check) node. So the result of this query is this:

enter image description here

In summary, when MERGEing nodes in a FOREACH loop, how can I update related nodes that nodes in the loop may be connected to?

Upvotes: 1

Views: 683

Answers (1)

Tom Geudens
Tom Geudens

Reputation: 2666

Use an optional match instead of the second merge :

UNWIND $list AS item
MERGE (check :label {index: item.index})
ON CREATE SET
   check.value= item.value,
   check.property= item.stuff
ON MATCH SET
   check.value= item.value,
   check.property= item.stuff 

OPTIONAL MATCH (:label {index: item.index})-[:r]->(related)
SET related.value = related.value + item.value

Hope this helps, Tom

Upvotes: 2

Related Questions