Neo4j:创建多个关系不起作用

时间:2017-09-05 17:44:14

标签: neo4j cypher

我在一个查询中创建多个关系。如果未找到第一个关系的匹配,则不会创建第二个关系。如果两个匹配都存在,则两个关系都有效

示例:

假设' MATCH1ID'以下不存在但是' MATCH2ID'确实。为什么会这样?

不工作

MERGE (NewRecord:OBJECTNAME { Id: 'ABZDEFG' })
SET NewRecord.name='NEWNAME'
WITH NewRecord
MATCH (a)
WHERE a.Id = 'MATCH1ID'
CREATE (a)-[ar:Relationship1]->(NewRecord)
WITH NewRecord MATCH (b)
WHERE b.Id = 'MATCH2ID'
CREATE (b)-[br:Relationship2]->(NewRecord) 

(如果我按照它的工作顺序切换存在的节点的顺序)

WORKS

MERGE (NewRecord:OBJECTNAME { Id: 'ABZDEFG' })
SET NewRecord.name='NEWNAME'
WITH NewRecord
MATCH (b)
WHERE b.Id = 'MATCH2ID'
CREATE (b)-[br:Relationship2]->(NewRecord)
WITH NewRecord
MATCH (a)
WHERE a.Id = 'MATCH1ID'
CREATE (a)-[ar:Relationship1]->(NewRecord)

1 个答案:

答案 0 :(得分:1)

您可以尝试使用OPTIONAL MATCH而不是简单的MATCH

MERGE (NewRecord:OBJECTNAME { Id: 'ABZDEFG' })
SET NewRecord.name='NEWNAME'
WITH NewRecord
OPTIONAL MATCH (a)
WHERE a.Id = 'MATCH1ID'

FOREACH(x IN (CASE WHEN a IS NULL THEN [] ELSE [1] END) | 
    CREATE (a)-[ar:Relationship1]->(NewRecord)
)

WITH NewRecord
OPTIONAL MATCH (b)
WHERE b.Id = 'MATCH2ID'

FOREACH(x IN (CASE WHEN b IS NULL THEN [] ELSE [1] END) | 
    CREATE (b)-[br:Relationship2]->(NewRecord) 
)

此外,此查询使用FORACHCASE WHEN的技巧来处理条件。在这种情况下,CREATE语句仅在ab变量不为空时执行。

请参阅Neo4j: LOAD CSV - Handling Conditionals