Joe
Joe

Reputation: 33

Neo4j: Creating Multiple Relationships Not Working

I am creating multiple relationships in one query. If a match is not found for the first relationship the second one is not created. If both matches exist then both relationships work.

Example:

Assume that 'MATCH1ID' below does not exist but 'MATCH2ID' does. Why does this happen?

DOES NOT WORK

MERGE (NewRecord:OBJECTNAME { Id: 'ABZDEFG' })
SET NewRecord.name='NEWNAME'
WITH NewRecord
MATCH (a)
WHERE a.Id = 'MATCH1ID'
CREATE (a)-[ar:Relationship1]->(NewRecord)
WITH NewRecord MATCH (b)
WHERE b.Id = 'MATCH2ID'
CREATE (b)-[br:Relationship2]->(NewRecord) 

(If I switch the order of the node that does exist to be first in the order it works)

WORKS

MERGE (NewRecord:OBJECTNAME { Id: 'ABZDEFG' })
SET NewRecord.name='NEWNAME'
WITH NewRecord
MATCH (b)
WHERE b.Id = 'MATCH2ID'
CREATE (b)-[br:Relationship2]->(NewRecord)
WITH NewRecord
MATCH (a)
WHERE a.Id = 'MATCH1ID'
CREATE (a)-[ar:Relationship1]->(NewRecord)

Upvotes: 3

Views: 375

Answers (1)

Bruno Peres
Bruno Peres

Reputation: 16373

You can try using a OPTIONAL MATCH instead of a simple MATCH:

MERGE (NewRecord:OBJECTNAME { Id: 'ABZDEFG' })
SET NewRecord.name='NEWNAME'
WITH NewRecord
OPTIONAL MATCH (a)
WHERE a.Id = 'MATCH1ID'

FOREACH(x IN (CASE WHEN a IS NULL THEN [] ELSE [1] END) | 
    CREATE (a)-[ar:Relationship1]->(NewRecord)
)

WITH NewRecord
OPTIONAL MATCH (b)
WHERE b.Id = 'MATCH2ID'

FOREACH(x IN (CASE WHEN b IS NULL THEN [] ELSE [1] END) | 
    CREATE (b)-[br:Relationship2]->(NewRecord) 
)

Also, this query uses a trick with FORACH and CASE WHEN to handle conditions. In this case, the CREATE statement is executed only when a or b variables are not null.

See Neo4j: LOAD CSV - Handling Conditionals.

Upvotes: 1

Related Questions