Neo4j: return error if no matching nodes found when creating a relationship?

862 Views Asked by At

Apologies if this has already been asked, but I was unable to find the answer

I would like to error when trying to create a relationship between nodes, where one or both of the nodes do not exist

For example, the following code just returns no results, but I would like it to raise an error to let me know that these nodes do not exist, so that I can surface that error to my application:

MATCH (user1: User{uuid: '123'}), (user2: User{uuid: '456'})
CREATE (user1)-[:LIKES]->(user2)

Please assume that the database is empty and therefore no nodes were matched

I tried to add a constraint, but I didn't know how to approach it and if this is possible - are you able to help please?

2

There are 2 best solutions below

1
On

I think something like this would work:

OPTIONAL MATCH (user1: User{uuid: '123'})
WITH user1, CASE WHEN user1 IS NULL THEN true ELSE FALSE END AS nodeNotFound
CALL apoc.util.validate(nodeNotFound,'User 1 with given property and label not found!', [404]) 
OPTIONAL MATCH (user2: User{uuid: '456'})
WITH user1, user2, CASE WHEN user2 IS NULL THEN true ELSE FALSE END AS nodeNotFound
CALL apoc.util.validate(nodeNotFound,'User 2 with given property and label not found!', [404])
WITH user1,user2
MERGE (user1)-[:LIKES]->(user2)
0
On

Instead of an error, your query can just return something (like the new relationship) when it successfully finds both nodes. If the query returns nothing, then that means one or both nodes do not exist.

For example:

MATCH (user1: User{uuid: '123'}), (user2: User{uuid: '456'})
CREATE (user1)-[r:LIKES]->(user2)
RETURN r;