简体   繁体   English

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

[英]create relationships in neo4j cypher using case statement

I have a JSON in the next form: 我有以下格式的JSON:

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

I want to create relation ship between the Condition node with node A Entities or node B entities based on type attribute which can be A/B i Assuming that these entities already exists in neo4j. 我想基于type属性(可以是A / B i)创建Condition节点与Node A实体或Node B实体之间的关系,假设这些实体已经存在于neo4j中。

I am trying something like the below cypher but that doesn't work. 我正在尝试类似下面的密码,但这是行不通的。

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;

Can anyone please help me with the correct way of doing this? 谁能帮我正确的方法吗? Thank you. 谢谢。

Since at the moment there is no classical conditional statements in cypher, you can use the famous trick with foreach and case : 由于目前在cypher中没有经典的条件语句,因此可以将foreachcase一起使用著名的技巧

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)
    )
)

APOC Procedures just updated with support for conditional cypher execution . 刚刚更新了APOC程序 ,以支持有条件的密码执行 You'll need version 3.1.3.7 or greater (if using Neo4j 3.1.x), or version 3.2.0.3 or greater (if using Neo4j 3.2.x). 您需要版本3.1.3.7或更高版本(如果使用Neo4j 3.1.x),或者版本3.2.0.3或更高版本(如果使用Neo4j 3.2.x)。

Here's an example of using these new procedures to execute your query: 这是使用这些新过程执行查询的示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM