0
votes

How to set a property as an iterative of related node properties on nodes that are a result of my statements in the foreach that follows an optional match?

I am replacing old nodes with new nodes, and accordingly changing the ID of nodes that were related to the old node. The ID is a concatenation of linked new nodes.

I tried with two subsequent optional matches but am scared that if the first comes back null, then the second will match ALL which would be mucho problem.

 MATCH (old), (new)
 ...bunch of stuff...
 WITH old, new
 OPTIONAL MATCH (old)-[oldrel:HAS]->(parent)
 FOREACH (o IN CASE WHEN parent IS NOT NULL THEN [parent] ELSE [] END|           
 MERGE (new)-[newrel:HAS]->(parent)
 DELETE oldrel
 SET parent.newID=[(parent)<-[:HAS]-(children) | REDUCE(iterate="", child IN children |  iterate + "," + child.Property1+child.Property2)] )

have also tried, but problematic when parent null...

 MATCH (old), (new)
 ...bunch of stuff...
 WITH old, new
 OPTIONAL MATCH (old)-[oldrel:HAS]->(parent)
 FOREACH (o IN CASE WHEN parent IS NOT NULL THEN [parent] ELSE [] END| MERGE (new)-[newrel:HAS]->(parent))
 DELETE oldrel
 WITH old, new, parent
 OPTIONAL MATCH (parent)<-[:HAS]-(children)
 SET parent.newID=REDUCE(iterate="", child IN children |  iterate + "," + child.Property1+child.Property2)

Desired outcome:

if oldchild 1 has property 1: 3 and property 2: X

and newchild 1 has property 1: 9 and property 2: Y

then parent ID1 switches from 3X,5Q to 5Q,9Y (ideally sorted this way)

and parent ID2 switches from 0P,3X,6S to 0P,6S,9Y (ideally sorted this way)

if old has no parent, then no nodes have IDs swapped

1

1 Answers

0
votes

This may work for you:

MATCH (old), (new)
...bunch of stuff...
WITH old, new
MATCH (old)-[oldrel:HAS]->(parent)
MERGE (new)-[newrel:HAS]->(parent)
DELETE oldrel
WITH parent, new
OPTIONAL MATCH (parent)<-[:HAS]-(child)
WHERE child <> new
WITH parent, COLLECT(child) + new AS children
SET parent.newID=
    REDUCE(iterate="", child IN children |
      iterate + "," + child.Property1+child.Property2)