fadanner
fadanner

Reputation: 158

Create a node within a foreach only on a given condition

For versioning purposes I wanna have VERSION node in my db. This node and its relationsship should only be created if the property size of a FILE node changes. The FILE node should always contain the current value for size. Since it isn't possible to use MATCH and WHERE in the foreach, how to make such a scenario work? Is there something like a "If-Clause" for using with foreach?

MERGE (root:FOLDER {fullpath: {newRoot}.fullpath})
ON CREATE SET root={newRoot}
FOR EACH (newFile IN {newFiles} | 
     MERGE (file:FILE {fullpath:newFile.fullpath}) ON CREATE SET file.guid = newFile.guid 
     SET file.visited = 1
     MERGE (root)-[:CONTAINS]->(file) 

And the following two lines should only execute if file.size != newFile.size (size changed)

    SET file.size = newFile.size 
    CREATE (file)-[:HASVERSION{v:1}]->(v:VERSION {size:newFile.size})

I hope you understand what I want to achieve. Please give advice if there are better solutions for Node versioning purposes.

Upvotes: 0

Views: 88

Answers (1)

Jim Biard
Jim Biard

Reputation: 2272

fadanner,

Here's what I found. This would work in the earlier answer I gave you as well (instead of the FOREACH).

MERGE (root:FOLDER {fullpath: {newRoot}.fullpath})
ON CREATE SET root={newRoot}
WITH root UNWIND {newFiles} AS newFile
MERGE (file:FILE {fullpath : newFile.fullpath})
ON CREATE SET file.guid = newFile.guid
SET file.visited = 1
MERGE (root)-[:CONTAINS]->(file)
WITH file, newFile
WHERE file.size <> newFile.size
CREATE (file)-[:HASVERSION {v : 1}]->(v:VERSION {size : newFile.size})

This is more complicated than the simple example that I tested, so there may be errors. But see if something like this won't solve your problem.

Grace and peace,

Jim

Upvotes: 2

Related Questions