在cypher中使用'if'语法来执行不同的查询

时间:2015-03-12 18:01:05

标签: neo4j cypher

有没有办法为下一个任务编写一个查询。

I have (a:A)-[r:RELATES]->(b:B)
and if r.value = 1  with a
Match (c:C{id:a.id}) with c, a
Merge (c)-[q:RELATED_TO]->(a)
ON CREATE SET q.value = 1
and if r.value = 0
// I don't create relationship between c and a but if it exists i set q.value = 0
Match (c)-[q:RELATED_TO]->(a)
Set q.value = 0

我尝试使用FOREACH查询此任务

Match (a:A)-[r:RELATES]->(b:B) with a, r, b
Match (c:C{id:a.id}) with a, r, b, c
FOREACH(ignoreMe IN CASE WHEN r.value = 1 THEN [1] ELSE [] END | 
    Merge (c)-[q:RELATED_TO]->(a)
    ON CREATE SET q.value = 1
)
FOREACH(ignoreMe IN CASE WHEN NOT r.value = 1 THEN [1] ELSE [] END | 
    Match (c)-[q:RELATED_TO]->(a)
    ON CREATE SET q.value = 0
)

但我在FOREACH中获得了无效的MATCH使用。似乎可以通过两个查询完成,但我想知道是否可以使用一个

1 个答案:

答案 0 :(得分:1)

这似乎在逻辑上等同于你想要做的事情:

MATCH (a:A)-[r:RELATES]->(b:B), (c:C {id:a.id})
OPTIONAL MATCH (c)-[q:RELATED_TO]->(a)
WHERE r.value = 0
SET q.value = 0
WITH c, a, r
WHERE r.value = 1
MERGE (c)-[q:RELATED_TO]->(a)
ON CREATE SET q.value = 1;
  • 如果r.value0并且q关系已存在,请将q.value设为0
  • 如果r.value1,则必要时创建q关系;并且,如果以前不存在q,则将q.value设置为1