使用case语句在neo4j cypher中创建关系

时间:2017-03-24 23:26:54

标签: neo4j switch-statement cypher

我有下一种形式的JSON:

{ "conditions": [ { "id": "123", "type": "a", entities: ["529", "454"] },
                  { "id": "124", "type": "b", entities: ["530", "455"] }
  ]
} 

我想创建Condition节点与节点A实体或节点B实体之间的关系,基于类型属性,可以是A / B i假设这些实体已经存在于neo4j中。

我正在尝试类似下面的密码,但这不起作用。

WITH {json} as data
UNWIND data.conditions as condition 
MATCH (c:Condition { conditionId: condition.id})
CASE c.type 
    WHEN 'a' THEN FOREACH (sid IN condition.entities | 
        MERGE (s:NodeA {nr_serverId:sid}) MERGE (s)-[:ATTACHED_TO]->(c)
    )
    WHEN 'b' THEN FOREACH (aid IN condition.entities | 
       MERGE (a:NodeB {nr_appId: aid}) MERGE (a)-[:ATTACHED_TO]->(c)
    )
END;

任何人都可以帮我正确地做这件事吗?谢谢。

2 个答案:

答案 0 :(得分:2)

由于目前cypher中没有经典条件语句,您可以使用famous trick with foreach and case

WITH {json} as data
UNWIND data.conditions as condition 
MATCH (c:Condition { conditionId: condition.id})
FOREACH (ift in CASE WHEN c.type = 'a' THEN [1] ELSE [] END |
    FOREACH (sid IN condition.entities | 
        MERGE (s:NodeA {nr_serverId:sid}) MERGE (s)-[:ATTACHED_TO]->(c)
    )
)
FOREACH (ift in CASE WHEN c.type = 'b' THEN [1] ELSE [] END |
    FOREACH (aid IN condition.entities | 
       MERGE (a:NodeB {nr_appId: aid}) MERGE (a)-[:ATTACHED_TO]->(c)
    )
)

答案 1 :(得分:0)

APOC Procedures刚刚更新了对conditional cypher execution的支持。您需要3.1.3.7或更高版本(如果使用Neo4j 3.1.x)或版本3.2.0.3或更高版本(如果使用Neo4j 3.2.x)。

以下是使用这些新程序执行查询的示例:

WITH {json} as data
UNWIND data.conditions as condition 
MATCH (c:Condition { conditionId: condition.id})
CALL apoc.do.case([
  c.type = 'a', 
   "FOREACH (sid IN condition.entities | 
        MERGE (s:NodeA {nr_serverId:sid}) MERGE (s)-[:ATTACHED_TO]->(c))",
  c.type = 'b',
   "FOREACH (aid IN condition.entities | 
       MERGE (a:NodeB {nr_appId: aid}) MERGE (a)-[:ATTACHED_TO]->(c))"
], '', {condition:condition, c:c}) YIELD value