使用Cypher批量更新Neo4J中的关系(包括删除和创建关系)。

huangapple go评论58阅读模式
英文:

Bulk update relations in Neo4J using Cypher (with deletion & creation of relations)

问题

我正在尝试批量更新两组节点之间的关系列表。

在此过程中,一些关系将被删除,一些将保留,而其他一些将被创建。

这是一个示例数据结构(左侧为之前,右侧为之后)。

要在单个查询中实现这一点,我找到了以下算法:

  1. 匹配(f:Foo)-[r]-(Bar),其中id(f)=1
  2. 设置r.delete = true
  3. 展开[2, 3, 4]作为$node_id
  4. 合并(f)-[r2]-(b:Bar),其中id(b)=$node_id
  5. 设置r2.delete = false
  6. 匹配(Foo)-[r3:{delete: true}]-()
  7. 删除r3

是否有更简洁/高效的方法来做到这一点?(我需要在一次操作中为单个Foo节点的多个关系执行此操作,这会导致一些相当繁重的查询)。我在apoc库中搜索过,但找不到可以执行此操作的函数。

英文:

I'm trying to bulk update a list of relations between 2 sets of nodes.

In the process, some relations are going to get deleted, some are going to remain, and others are going to be created.

This is an example data structure (left for before, right for after)

使用Cypher批量更新Neo4J中的关系(包括删除和创建关系)。

To achieve this in a single query, this is the algorithm I've found

 1. MATCH (f:Foo)-[r]-(Bar) WHERE id(f)=1
 2. SET r.delete = true
 3. UNWIND [2, 3, 4] as $node_id
 4.   MERGE (f)-[r2]-(b:Bar) WHERE id(b)=$node_id
 5.   SET r2.delete = false
 6. MATCH (Foo)-[r3:{delete: true}]-()
 7. DELETE r3

Is there a more concise / efficient way to do this ? (I need to do it for multiple relations from a single Foo node in one pass and that makes for some quite hefty queries). I searched for this in apoc library but could not find a function to do this.

答案1

得分: 1

你不需要delete属性。假设你传递了f的本机ID以及所需Bar节点的ID列表作为parameters $fId$barIds,你可以这样做:

MATCH (f:Foo) WHERE ID(f) = $fId
FOREACH(r IN [(f)-[rel:X]->(:Bar)|rel] |
  DELETE r
)
WITH f
MATCH (b:Bar) WHERE ID(b) IN $barIds
MERGE (f)-[:X]->(b)

请注意,关系的MERGE需要一个关系类型,所以我随意使用了X作为类型。

英文:

You do not need the spurious delete property. Assuming that you pass the native ID of f and a list of the IDs of the desired Bar nodes as the parameters $fId and $barIds, you can do this:

MATCH (f:Foo) WHERE ID(f) = $fId
FOREACH(r IN [(f)-[rel:X]->(:Bar)|rel] |
  DELETE r
)
WITH f
MATCH (b:Bar) WHERE ID(b) IN $barIds
MERGE (f)-[:X]->(b)

Note that the MERGE of a relationship requires a relationship type, so I arbitrarily used X as the type.

huangapple
  • 本文由 发表于 2023年5月10日 23:16:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定