性能 – 在neo4j中使用FOREACH时的DELETE关系

我需要删除迭代FOREACH的特定类型节点的关系.

详细地 ::

PROFILE MATCH (n:Label1)-[r1:REL1]-(a:Label2) 
WHERE a.prop1 = 2 
WITH n 
WITH COLLECT(n) AS rows 
WITH [a IN rows WHERE a.prop2 < 1484764200] AS less_than_rows, 
[b IN rows WHERE b.prop2 = 1484764200 AND b.prop3 < 2] AS other_rows 
WITH size(less_than_rows) + size(other_rows) AS count, less_than_rows, other_rows
FOREACH (sub IN less_than_rows | 
  MERGE (sub)-[r:REL2]-(:Label2) 
  DELETE r 
  MERGE(l2:Label2{id:540}) 
  MERGE (sub)-[:APPEND_TO {s:0}]->(l2) 
  SET sub.prop3=1, sub.prop2=1484764200) 
WITH DISTINCT other_rows, count 
FOREACH (sub IN other_rows | 
  MERGE(l2:Label2{id:540}) 
  MERGE (sub)-[:APPEND_TO {s:0}]->(l2) 
  SET sub.prop3=sub.prop3+1)
RETURN count

由于FOREACH不支持MATCH,我使用MERGE来实现它.但是当我执行它时它很慢(大约需要1分钟).
但是,如果我超越FOREACH(停止更新),它会给出大约1秒的时间.

问题::显然FOREACH或FOREACH内部操作的问题.
我想删除一个特定的关系,创建另一个关系并为节点设置一些属性.

注意::我显示了总查询,因为有没有其他方法可以达到相同的要求(在这个FOREACH之外,我尝试过CASE WHEN)

最佳答案 我注意到了一些关于原始查询的事情:

> MERGE(l2:Label2 {id:540})应该从两个FOREACH子句中移出,因为它只需要完成一次.这会降低查询速度.实际上,如果您希望节点已经存在,则可以使用MATCH.
> MERGE(sub) – [:APPEND_TO {s:0}] – >(l2)可能无法按预期执行,因为它只匹配s属性仍为0的现有关系.如果s不为0,你最终会建立一个额外的关系.为了确保存在单个关系并且其s值(重置为)0,您应该从模式中删除{s:0}测试并使用SET来设置s值;这也应该加速MERGE,因为它不需要进行属性值测试.

此版本的查询应该可以解决上述问题,并且速度更快(但您必须尝试一下才能看到更快):

PROFILE
MATCH (n:Label1)-[:REL1]-(a:Label2)
WHERE a.prop1 = 2
WITH COLLECT(n) AS rows
WITH
  [a IN rows WHERE a.prop2 < 1484764200] AS less_than_rows, 
  [b IN rows WHERE b.prop2 = 1484764200 AND b.prop3 < 2] AS other_rows 
WITH size(less_than_rows) + size(other_rows) AS count, less_than_rows, other_rows
MERGE(l2:Label2 {id:540}) 
FOREACH (sub IN less_than_rows | 
  MERGE (sub)-[r:REL2]-(:Label2) 
  DELETE r 
  MERGE (sub)-[r2:APPEND_TO]->(l2)
  SET r2.s = 0, sub.prop3 = 1, sub.prop2 = 1484764200) 
WITH DISTINCT l2, other_rows, count 
FOREACH (sub IN other_rows | 
  MERGE (sub)-[r3:APPEND_TO]->(l2) 
  SET r3.s = 0, sub.prop3 = sub.prop3+1)
RETURN count;

如果您只想在创建APPEND_TO关系时将s值设置为0,则使用ON CREATE子句而不是SET:

PROFILE
MATCH (n:Label1)-[:REL1]-(a:Label2)
WHERE a.prop1 = 2
WITH COLLECT(n) AS rows
WITH
  [a IN rows WHERE a.prop2 < 1484764200] AS less_than_rows, 
  [b IN rows WHERE b.prop2 = 1484764200 AND b.prop3 < 2] AS other_rows 
WITH size(less_than_rows) + size(other_rows) AS count, less_than_rows, other_rows
MERGE(l2:Label2 {id:540}) 
FOREACH (sub IN less_than_rows | 
  MERGE (sub)-[r:REL2]-(:Label2) 
  DELETE r 
  MERGE (sub)-[r2:APPEND_TO]->(l2)
  ON CREATE SET r2.s = 0
  SET sub.prop3 = 1, sub.prop2 = 1484764200) 
WITH DISTINCT l2, other_rows, count 
FOREACH (sub IN other_rows | 
  MERGE (sub)-[r3:APPEND_TO]->(l2)
  ON CREATE r3.s = 0
  SET sub.prop3 = sub.prop3+1)
RETURN count;
点赞