Neo4j does not query for an absent match, but does not return an empty array

Given the following cypher request

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 am creating node C , which should have a relationship with 2 things, some node b and some users.

What happens, I get an empty array when u or b does not exist, but I would like neo4j to respond with a failure instead of an empty array. This makes it easier for me to know which node is missing. Is it possible to “force” a failure when the matching clause returns nothing?

+6
source share
1 answer

Here's how it works, if MATCH returns null, the request is not executed. That is why they have an OPTIONAL MATCH available, so it will not work if null is returned.

Edit: add a refund 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 go back to success, it means that the match found what it was looking for, if not, then it doesn’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 are making an optional match so that it does not crash when it has not been found. Then we execute the CASE statement and where both users and B exist, we create some relationships. And in the end, we return User and b and check if both of them exist, or if there is not one of them in either of them.

+7
source

Source: https://habr.com/ru/post/1015441/


All Articles