neo4jcypher

Create relationship only if node merge resulted in create


Say I have some Cypher:

MATCH (f:FirstNode {with:$parametersF})
WITH f
MERGE (s:SomeNode {with:$parametersS})
ON CREATE SET s.source=$source
MERGE (s)-[:IS_CONNECTED_TO]->(f)

I want to be able to move the second MERGE into the ON CREATE (and change the MERGE into a CREATE) - meaning that I only want it to create the relationship if the node was just created. So something like:

...
MERGE (s:SomeNode {with:$parametersS})
ON CREATE SET s.source=$source
ON CREATE CREATE (s)-[:IS_CONNECTED_TO]->(f)

But this isn't valid cypher. Is there a better way to do this? I'm trying to reduce lock acquisition on the relationship where I know it's not needed.


Solution

  • In ON CREATE you can set a temporary isNew property. Then, if isNew is true, CREATE the relationship and remove isNew.

    MATCH (f:FirstNode {with:$parametersF})
    MERGE (s:SomeNode {with:$parametersS})
    ON CREATE SET s.source=$source, s.isNew = TRUE
    WITH f, s
    WHERE s.isNew
    CREATE (s)-[:IS_CONNECTED_TO]->(f)
    REMOVE s.isNew