I have the following Cypher query where I am creating multiple relationships between nodes. I would like to know how to count the number of relationships that are created in this query.
MATCH (task:Task {id: "$taskId"})
MATCH path = (task)-[:INITIAL_STEP]->(initialPhase:Phase)
(()<-[:PREVIOUS_PHASE]-(nextPhase:Phase) WHERE NOT EXISTS { (nextPhase)<-[:COMPLETED]-(task) })*
(currentPhase:Phase)
WITH task, currentPhase
MERGE (task)-[:PROGRESSES_TO]->(currentPhase)
UNION
MATCH path = (task)-[:COMPLETED]->(finalPhase:Phase)
(()-[:PREVIOUS_PHASE]->(followingPhase:Phase) WHERE NOT EXISTS { (followingPhase)<-[:INITIAL_STEP | PROGRESSES_TO | COMPLETED]-(task) })*
(currentPhase:Phase)
WHERE currentPhase <> finalPhase AND followingPhase <> finalPhase
WITH task, currentPhase
MERGE (task)-[:PROGRESSES_TO]->(currentPhase)
I want to track the number of :PROGRESSES_TO relationships that get created by the MERGE operations in both parts of the query. How can I modify the query to count the number of these relationships?
MATCH (task:Task {id: "$taskId"})
CALL (task) {
MATCH (task)-[:INITIAL_STEP]->(initialPhase:Phase)
(()<-[:PREVIOUS_PHASE]-(nextPhase:Phase) WHERE NOT EXISTS { (nextPhase)<-[:COMPLETED]-(task) })*
(currentPhase:Phase)
WITH task, currentPhase
WHERE NOT EXISTS ((task)-[:PROGRESSES_TO]->(currentPhase))
CREATE (task)-[:PROGRESSES_TO]->(currentPhase)
RETURN 1 as rel_exists
UNION ALL
MATCH (task)-[:COMPLETED]->(finalPhase:Phase)
(()-[:PREVIOUS_PHASE]->(followingPhase:Phase) WHERE NOT EXISTS { (followingPhase)<-[:INITIAL_STEP | PROGRESSES_TO | COMPLETED]-(task) })*
(currentPhase:Phase)
WHERE currentPhase <> finalPhase AND followingPhase <> finalPhase
WITH task, currentPhase
WHERE NOT EXISTS((task)-[:PROGRESSES_TO]->(currentPhase))
CREATE (task)-[:PROGRESSES_TO]->(currentPhase)
RETURN 1 as rel_exists
}
RETURN SUM(rel_exists) as num_of_relationships_created
Since the relationships created in each branch of the UNION are the same, you can simplify as follows:
MATCH (task:Task {id: "$taskId"})
CALL (task) {
MATCH (task)-[:INITIAL_STEP]->(initialPhase:Phase)
(()<-[:PREVIOUS_PHASE]-(nextPhase:Phase) WHERE NOT EXISTS { (nextPhase)<-[:COMPLETED]-(task) })*
(currentPhase:Phase)
RETURN currentPhase
UNION
MATCH (task)-[:COMPLETED]->(finalPhase:Phase)
(()-[:PREVIOUS_PHASE]->(followingPhase:Phase) WHERE NOT EXISTS { (followingPhase)<-[:INITIAL_STEP | PROGRESSES_TO | COMPLETED]-(task) })*
(currentPhase:Phase)
WHERE currentPhase <> finalPhase AND followingPhase <> finalPhase
RETURN currentPhase
}
WITH task, currentPhase
WHERE NOT EXISTS ((task)-[:PROGRESSES_TO]->(currentPhase))
CREATE (task)-[:PROGRESSES_TO]->(currentPhase)
RETURN COUNT(*) as num_of_relationships_created