Reputation: 7580
I am trying to execute conditional query in cypher Below is my sample query, but it does not create new conversation node even if condition is true.
WITH ["Ram", "Shyam", "Hari"] as names
WITH names, size(names) AS requiredCount
MATCH (u:User) WHERE u.name IN names
WITH u, requiredCount
MATCH (u)-[:IS_PARTICIPANT]->(c:Conversation)
WITH requiredCount, c, u, count(u) as matches
WHERE requiredCount = matches and size(()-[:IS_PARTICIPANT]->(c)) = requiredCount
WITH u, count(c) as conversationExists
CALL apoc.do.when(conversationExists < 1, 'MERGE (cc:Conversation {_id:
apoc.create.uuid(), createdAt: timestamp()}) RETURN cc', '', {u: u}) YIELD value
RETURN value
Upvotes: 0
Views: 984
Reputation: 30397
There are a couple things off here.
names
should be present in the WITH in the second line (I think you renamed it to userIDs
by mistake).
You have WITH requiredCount, c, u, count(u) as matches
, which isn't doing what you think it is. The aggregation function has context from the non-aggregation columns (which form the grouping key). It can help to read it out like this: "for each requiredCount, c, and u, give me the count of that u". There is only 1 u
per row, so matches
count will always be 1 for each row, so your query will always fail whenever you have names collection greater than 1. You can test it yourself by changing the WITH to RETURN for that line, and commenting out the rest. You're going to have to handle this differently, either by collecting u
or removing it from that line.
You also have to be careful about performing MATCHes that don't match something or using WHERE clauses on WITH clauses that evaluate to false, since if that wipes out all rows you won't be able to continue the query (basically if your MATCH and WHERE fails, you won't be able to reach this line at all: WITH u, count(c) as conversationExists
). You might try either using an OPTIONAL MATCH, or extracting out that WHERE clause as a boolean variable in your WITH clause.
Upvotes: 1