Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

neo4j fail a query on a missing match instead of returning empty array

Tags:

neo4j

cypher

Given the below cypher query

  MATCH (u:User {id: {userId}}), (b:B {id: {bId})
  CREATE (c:C), (c)-[:HAS_USER]->(u), (b)-[:SOME_REL]->(c)

As you can see, I'm creating a node C that must have relationships with 2 things, some node b and some user.

What happens is I get an empty array when u or b does not exist, but I'd like neo4j to respond with a fail instead of an empty array. That makes things easier for me to know which node is missing. Is it possible to 'force' a fail when the match clause doesn't return anything?

like image 499
Terence Chow Avatar asked Mar 03 '17 14:03

Terence Chow


1 Answers

That is how it works, if the MATCH return null then the query fails. That is why they have OPTIONAL MATCH available so that it doesn`t fail if null is returned.

Edit: add return at the end like this

MATCH (u:User {id: {userId}}), (b:B {id: {bId})
CREATE (c:C), (c)-[:HAS_USER]->(u), (b)-[:SOME_REL]->(c)
RETURN 'success'

So if you get success back that means that match found what it was looking for if not then it didn't

edit 2:

OPTIONAL MATCH (u:User {id: {userId}}), (b:B {id: {bId})
with *,CASE when u is not null and b is not null then [1] else [] end as exists
FOREACH (x in exists | CREATE (c:C), (c)-[:HAS_USER]->(u), (b)-[:SOME_REL]->(c))

RETURN u,b

so now we do an optional match so it doesnt break down when not found. Then we do a CASE statement and where both User and B exist we create some relationships. And in the end we return User and b and check if both exists or whether there is a null in any of them.

like image 110
Tomaž Bratanič Avatar answered Nov 03 '22 02:11

Tomaž Bratanič