英文:
Bulk update relations in Neo4J using Cypher (with deletion & creation of relations)
问题
我正在尝试批量更新两组节点之间的关系列表。
在此过程中,一些关系将被删除,一些将保留,而其他一些将被创建。
这是一个示例数据结构(左侧为之前,右侧为之后)。
要在单个查询中实现这一点,我找到了以下算法:
- 匹配(f:Foo)-[r]-(Bar),其中id(f)=1
- 设置r.delete = true
- 展开[2, 3, 4]作为$node_id
- 合并(f)-[r2]-(b:Bar),其中id(b)=$node_id
- 设置r2.delete = false
- 匹配(Foo)-[r3:{delete: true}]-()
- 删除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)
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论