使用 apoc 在 neo4j 中进行条件查询

Conditional query in neo4j using apoc

我正在尝试在密码中执行条件查询下面是我的示例查询,但即使条件为真,它也不会创建新的对话节点。

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

这里有几件事。

names 应该出现在第二行的 WITH 中(我认为你错误地将它重命名为 userIDs)。

您有 WITH requiredCount, c, u, count(u) as matches,它并没有按照您的想法行事。聚合函数具有来自非聚合列(形成分组键)的上下文。像这样读出来会有帮助:"for each requiredCount, c, and u, give me the count of that u"。每行只有 1 u,因此每行的 matches 计数将始终为 1,因此只要您的名称集合大于 1,您的查询将始终失败。您可以通过更改WITH 到 RETURN 该行,并注释掉其余部分。你将不得不以不同的方式处理这个问题,要么收集 u 要么从该行中删除它。

您还必须小心执行不匹配的 MATCHes 或对计算结果为 false 的 WITH 子句使用 WHERE 子句,因为如果这会清除所有行,您将无法继续查询 (基本上,如果您的 MATCH 和 WHERE 失败,您将根本无法到达此行:WITH u, count(c) as conversationExists)。您可以尝试使用可选匹配,或将 WHERE 子句提取为 WITH 子句中的布尔变量。