hanzgs
hanzgs

Reputation: 1616

Create Relation based on value of the property Cypher neo4j

I have two nodes for Customers, C1, C2, if the transfer type is debit, then i want to create relation in one direction, if credit then i want the opposite direction.

Below, after getting C1 and C2, I tried using where clause

UNWIND nextHits as transfer
MERGE (C1:Customer {CusNo = transfer.CusNo })
MERGE (C2:Customer {CCusNo = transfer.CCusNo })
MERGE (C1)-[:Transfer]->(C2) WHERE transfer.type = 'Credit'
MERGE (C2)-[:Transfer]->(C1) WHERE transfer.type = 'Debit'
RETURN C1,C2

The above doesn't work

Upvotes: 0

Views: 21

Answers (1)

TheTeacher
TheTeacher

Reputation: 510

UNWIND nextHits as transfer
MERGE (C1:Customer {CusNo = transfer.CusNo })
MERGE (C2:Customer){CusNo = transfer.CusNo })
WITH C1,C2, CASE transfer.type = 'Credit' WHEN TRUE THEN [1] ELSE [] END as creditList,
CASE transfer.type = 'Debit' WHEN TRUE THEN [1] ELSE [] END as deditList
FOREACH(x IN creditList| MERGE (C1)-[:Transfer]->(C2))
FOREACH(x IN debitList| MERGE (C2)-[:Transfer]->(C1))
RETURN C1,C2

we are using CASE expression here to create an list with one element or No elements based on the condition . And we iterate through this list to create relationship . CASE transfer.type = 'Debit' implies transfer type is 'Credit' and so creditList will have one element and debitList will be empty . so , we merge credit type relation one time and debit zero times. hope this helps :)

Upvotes: 1

Related Questions