通过模式理解来减少/避免在空节点上进行可选匹配

时间:2019-05-07 16:20:42

标签: neo4j cypher

由于在可选匹配之后的foreach中我的语句的结果,如何设置属性作为节点上相关节点属性的迭代?

我要用新节点替换旧节点,并相应地更改与旧节点相关的节点的ID。该ID是链接的新节点的串联。

我尝试了两个后续的可选匹配项,但害怕如果第一个匹配项返回null,那么第二个匹配项将匹配ALL,这将是很多问题。

 MATCH (old), (new)
 ...bunch of stuff...
 WITH old, new
 OPTIONAL MATCH (old)-[oldrel:HAS]->(parent)
 FOREACH (o IN CASE WHEN parent IS NOT NULL THEN [parent] ELSE [] END|           
 MERGE (new)-[newrel:HAS]->(parent)
 DELETE oldrel
 SET parent.newID=[(parent)<-[:HAS]-(children) | REDUCE(iterate="", child IN children |  iterate + "," + child.Property1+child.Property2)] )

也曾尝试过,但是当父级null出现问题时...

 MATCH (old), (new)
 ...bunch of stuff...
 WITH old, new
 OPTIONAL MATCH (old)-[oldrel:HAS]->(parent)
 FOREACH (o IN CASE WHEN parent IS NOT NULL THEN [parent] ELSE [] END| MERGE (new)-[newrel:HAS]->(parent))
 DELETE oldrel
 WITH old, new, parent
 OPTIONAL MATCH (parent)<-[:HAS]-(children)
 SET parent.newID=REDUCE(iterate="", child IN children |  iterate + "," + child.Property1+child.Property2)

所需结果:

如果长子1具有属性1:3和属性2:X

新子1具有属性1:9和属性2:Y

然后,父ID1从3X,5Q切换到5Q,9Y(以这种方式进行理想排序)

父ID2从0P,3X,6S切换到0P,6S,9Y(按这种方式进行理想排序)

如果old没有父节点,则没有节点交换ID

1 个答案:

答案 0 :(得分:0)

这可能对您有用:

MATCH (old), (new)
...bunch of stuff...
WITH old, new
MATCH (old)-[oldrel:HAS]->(parent)
MERGE (new)-[newrel:HAS]->(parent)
DELETE oldrel
WITH parent, new
OPTIONAL MATCH (parent)<-[:HAS]-(child)
WHERE child <> new
WITH parent, COLLECT(child) + new AS children
SET parent.newID=
    REDUCE(iterate="", child IN children |
      iterate + "," + child.Property1+child.Property2)