如何在Neo4j Cypher中的CASE WHEN THEN子句内执行密码查询

s4n0splo  于 2023-01-05  发布在  其他
关注(0)|答案(2)|浏览(214)

我有一个用例,我试图通过使用Cypher中的RETURN CASE WHEN THEN子句根据WHEN结果运行不同的查询来优化Neo4j数据库调用和代码。

MATCH (n {email: 'abc123@abc.com'}) 
RETURN  
CASE WHEN n.category='Owner' THEN  MATCH '(n)-[r:OWNS]->(m)'  
WHEN n.category='Dealer' THEN MATCH (n)-[r:SUPPLY_PARTS_FOR]->(m) 
WHEN n.category='Mechanic' THEN MATCH (n)-[r:SERVICE]-(m) END 
AS result;

我不确定这是否法律的,但这是我想要实现的。我遇到了语法错误,如无效输入'〉'。我如何才能以最佳方式实现这一点?编辑可能的APOC解决方案:这是我在发现FOREACH的局限性之前的计划...

MATCH (user:Person {email:{paramEmail}})
FOREACH (_ IN case when 'Owner' = {paramCategory} then [1] else [] end|
SET user:Owner, user += queryObj 
WITH user, {paramVehicles} AS coll
UNWIND coll AS vehicle
MATCH(v:Vehicles {name:vehicle}) 
CREATE UNIQUE (user)-[r:OWNS {since: timestamp()}]->(v)
SET r += paramVehicleProps 
)
FOREACH (_ IN case when 'Mechanic' = {Category} then [1] else [] end|
SET user:Owner, user += queryObj 
WITH user, {paramVehicles} AS coll
….
)
FOREACH (_ IN case when 'Dealer' = {paramCategory} then [1] else [] end|
SET user:Owner, user += queryObj 
WITH user, {paramVehicles} AS coll
…...

)
RETURN user,
CASE {paramCategory}

WHEN 'Owner' THEN [(n)-[r:OWNS]->(m) | m and r]
 WHEN 'Dealer' THEN [(n)-[r:SUPPLY_PARTS_FOR]->(m) | m] 
WHEN 'Mechanic' THEN [(n)-[r:SERVICE]-(m) | m]
 END AS result`,{
 paramQueryObj: queryObj,
 paramVehicles: makeVehicleArray,
 paramVehicleProps: vehiclePropsArray,
 paramSalesAgent: dealerSalesAgentObjarray,
 paramWarehouseAgent: dealerWarehouseAgentObjarray
}).....

有人知道用apoc.do.when()转换吗?注意我需要在第一个THEN中使用“m”和“r”。

yvgpqqbh

yvgpqqbh1#

您仍然应该在第一次匹配时使用标签,否则您将获得完整的数据库扫描,而不是通过电子邮件进行索引查找!!
对于您的查询,您可以使用模式解析:

MATCH (n:Person {email: 'abc123@abc.com'}) 
RETURN  
CASE n.category 
WHEN 'Owner'    THEN  [(n)-[r:OWNS]->(m) | m]
WHEN 'Dealer'   THEN [(n)-[r:SUPPLY_PARTS_FOR]->(m) | m] 
WHEN 'Mechanic' THEN [(n)-[r:SERVICE]-(m) | m] END 
AS result;
t9aqgxwy

t9aqgxwy2#

也可以使用apoc.do.case:https://neo4j.com/labs/apoc/4.4/overview/apoc.do/apoc.do.case/

CALL apoc.do.case([
  false,
  'CREATE (a:Node{name:"A"}) RETURN a AS node',
  true,
  'CREATE (b:Node{name:"B"}) RETURN b AS node'
  ],
  'CREATE (c:Node{name:"C"}) RETURN c AS node',{})
YIELD value
RETURN value.node AS node;

相关问题