vishal patel
vishal patel

Reputation: 832

Neo4j Creating a relationship conditionally based on one of the property of node

I need to create two different type of relationship between two nodes. Type of relationship depends upon one of the property of the node.

For Example,

I have two nodes USER and EVENT. I have two relationships to create between them. 1. invite 2. requestToInvite

Even node has property inviteOnly.

Create a "Invite" relationship if inviteOnly is true. Otherwise create "requestToInvite" relationship.

This is what i am trying:

MATCH (u:User)
WHERE ID(u) = 13
WITH u
MATCH (e:Events)
WHERE ID(e) = 0
WITH u,e
CREATE (u)-[:inviteONLYTrue]->(e) WHERE e.inviteOnly = true
CREATE (u)-[:inviteONLYFALSE]->(e) WHERE e.inviteOnly = false
WITH u,e
RETURN u,e

Upvotes: 4

Views: 2642

Answers (2)

InverseFalcon
InverseFalcon

Reputation: 30417

APOC Procedures just updated with support for conditional cypher execution, but in this particular case all you'll need is a way to create a relationship with a dynamic relationship type. APOC has a procedure for this too. Here's an example:

MATCH (u:User)
WHERE ID(u) = 13
WITH u
MATCH (e:Events)
WHERE ID(e) = 0
WITH u,e, CASE WHEN e.inviteOnly THEN 'inviteONLYTrue' ELSE 'inviteONLYFALSE' END as relType
CALL apoc.create.relationship(u, relType, {}, e) YIELD rel
RETURN u,e

Upvotes: 2

Michael Hunger
Michael Hunger

Reputation: 41706

Currently there is no conditional but you can work around it by iterating over a zero or one-element list which is created by a CASE statement.

MATCH (u:User) WHERE ID(u) = 13
MATCH (e:Events) WHERE ID(e) = 0
FOREACH (_ in case e.inviteOnly when true then [1] else [] end |
  CREATE (u)-[:inviteONLYTrue]->(e) )
FOREACH (_ in case e.inviteOnly when false then [1] else [] end |
  CREATE (u)-[:inviteONLYFALSE]->(e) )
RETURN u,e

Upvotes: 6

Related Questions