I have the following query, where I want to optimise it more. Since it deletes and create relationships for all records. My intention is to , if action_code is
"A" -> Only want to create relationship
"U" -> Delete & Create Relationship
"NU" -> Neither Delete nor Create Relationship.
How to incorporate this to the existing query?
neo4j.topic.cypher.kafka_car =
WITH event
CALL {
WITH event
MERGE (n:Manufacturer {id: event.id})
ON CREATE SET n += event
ON MATCH SET n += event
WITH n
FOREACH ( _ IN CASE WHEN n.Make = 'BMW' THEN [1] ELSE [] END | SET n:Country:Make:Color:Bmw:Germany)
FOREACH ( _ IN CASE WHEN n.Make = 'Mercedes' THEN [1] ELSE [] END | SET n:Country:Make:Color:Mercedes:Germany)
FOREACH ( _ IN CASE WHEN n.Make = 'Land Rover' THEN [1] ELSE [] END | SET n:Country:Make:Color:LandRover:England)
FOREACH ( _ IN CASE WHEN n.Make = 'Tesla' THEN [1] ELSE [] END | SET n:Country:Make:Color:Tesla:America:Black)
FOREACH ( x IN [(n)-[r]-()|r] | DELETE x)
FOREACH ( q IN [(q:Manufacturer {ParentName: n.Name})-[*0]-() | q] | MERGE (n)-[:Parent_To]->(q))
FOREACH ( w IN [(w:Engine {Chasis: n.SerialNumber})-[*0]-() | w] | MERGE (n)-[:Has_Engine]->(w))
}
You can clean up your existing query using the COLLECT subquery and the new ability to set labels with variables in 5.24.
WITH {id: 10, name: 'M4', SerialNumber:'ksfkjsdffs', Make:'BMW'} as event
CALL {
WITH event
MERGE (n:Manufacturer {id: event.id})
ON CREATE SET n += event
ON MATCH SET n += event
WITH n,
CASE
WHEN n.Make = 'BMW' THEN "Country:Make:Color:Bmw:Germany"
WHEN n.Make = 'Mercedes'THEN "Country:Make:Color:Mercedes:Germany"
WHEN n.Make = 'Land Rover' THEN "Country:Make:Color:LandRover:England"
WHEN n.Make = 'Tesla' THEN "Country:Make:Color:Tesla:America:Black"
END as newLabels,
COLLECT {match (m:Manufacturer {ParentName: n.Name}) return m} as manufacturers,
COLLECT {match (e:Engine {Chasis: n.SerialNumber}) return e} as engines
SET n:$(newLabels)
FOREACH (x IN [(n)-[r]-()|r] | DELETE x)
FOREACH (q IN manufacturers | MERGE (n)-[:Parent_To]->(q))
FOREACH (w IN engines | MERGE (n)-[:Has_Engine]->(w))
}
You can use a structure like the following to allow you to conditionally perform your actions:
with "A" as action
call (action) {
with action
where action = 'A'
//create relationship
}
call (action) {
with action
where action = 'U'
// Delete & Create Relationship
}
call (action) {
with action
where action = 'NU'
// Neither Delete nor Create Relationship
}