将neo4j的一个节点上的关系移动到另一个节点上

将neo4j中一个节点的全部关系移动到另一个节点上面,采用先建立新关系,之后删除原先的关系的方式

 

 1 def move_relations(source_node_id,target_node_id,graph=None):
 2     """
 3     将 source_node_id 上所有的关系移动到 target_node_id 上
 4     """
 5     if source_node_id is None or target_node_id is None:
 6         return
 7     if graph is None:
 8         graph = get_graph()
 9     r_ids = []
10     match = "match (x)-[r]-(n) where id(x)=%s return r" % (source_node_id)
11     data = graph.run(match).data()
12     for d in data:
13         for tk,tv in d.items():
14             relations = tv.relationships
15             for r in relations:
16                 if r.identity in r_ids:
17                     continue
18                 r_ids.append(r.identity)
19 
20                 from_id = 0
21                 to_id = 0
22                 if r.start_node.identity == source_node_id:
23                     from_id = target_node_id
24                     to_id = r.end_node.identity
25                 else:
26                     from_id = r.start_node.identity
27                     to_id = target_node_id
28                 labels = ""
29                 if r.types() is not None:
30                     for la in r.types():
31                         labels+=":" + la
32                 fields = []
33                 fields_str = ""
34                 for k,v in r.items():
35                     fields.append("%s:'%s'" % (k,v))
36                 if len(fields) > 0:
37                     fields_str = ",".join(fields)
38                     fields_str = "{%s}" % fields_str
39                 match = "match (x),(y) where id(x)=%s and id(y)=%s create (x)-[r%s%s]->(y) return id(r)" % (from_id,to_id,labels,fields_str)
40                 result=graph.run(match).data()
41                 if result is None or len(result)==0:
42                     return False
43                 match = "match ()-[r]-() where id(r)=%s delete r" % (r.identity)
44                 graph.run(match)
45                 return True
46 
47     return

 

posted @ 2019-10-12 09:16  mzyn22  阅读(722)  评论(1)    收藏  举报