Jeevika
Jeevika

Reputation: 142

THEN ELSE condition statements in cypher query language in neo4j

I want to execute an CREATE statement in THEN and UPDATE in ELSE statement in cypher query language in Neo4j.

Here is my query:

MATCH (product:user_product) WHERE id(product) = 45
OPTIONAL MATCH (user:person) where id(user) = 90 
FOREACH (o IN CASE WHEN user IS NOT NULL THEN 
CREATE (user)<-[:HAS_USER]-(product)
ELSE 
set product.userStatus = 1
END)
return user, product

Upvotes: 4

Views: 2886

Answers (2)

Dave Bennett
Dave Bennett

Reputation: 11216

If either condition is true you could set a collection of one for the specific condition and then use FOREACH to loop through the condition if it is true. By combining them you optionally can perform one or the other.

MATCH (product:user_product) WHERE id(product) = 45
OPTIONAL MATCH (user:person) where id(user) = 90 
WITH CASE WHEN user IS NOT null THEN
  [1]
END as create_rel,
CASE WHEN user IS null THEN
  [1]
END as update_product, product, user
FOREACH (x in create_rel | 
  MERGE (user)<-[r:HAS_USER]-(product)
  ON CREATE set r.updated = 1
  ON MATCH set r.updated = r.updated + 1
)
FOREACH (x in update_product | 
  SET product.userStatus = 1
)
return user, product

Upvotes: 2

Frank Pavageau
Frank Pavageau

Reputation: 11705

You can collect the user to a list while grouping by product and user, a list which will have a size of 0 or 1 as it won't contain null.

Then,

  1. You can iterate on the list to do the CREATE part only when the user exists

  2. You can iterate 0 or 1 time to set the property (or not, in the case of 0), if the size of the user list is 1 or 0

The resulting query is this:

MATCH (product:user_product) WHERE id(product) = 45
OPTIONAL MATCH (user:person) WHERE id(user) = 90
WITH product, user, collect(user) AS users
FOREACH (u IN users | CREATE (u)<-[:HAS_USER]-(product))
FOREACH (i in range(1, 1 - size(users)) | SET product.userStatus = 1)
RETURN user, product

Upvotes: 2

Related Questions