create relationships in neo4j cypher using case statement

微笑、不失礼 提交于 2020-01-17 05:50:31

问题


I have a JSON in the next form:

{ "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.

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.


回答1:


Since at the moment there is no classical conditional statements in cypher, you can use the 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)
    )
)



回答2:


APOC Procedures just updated with support for conditional cypher execution. 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).

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


来源:https://stackoverflow.com/questions/43010726/create-relationships-in-neo4j-cypher-using-case-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!