将neo4j中一个节点的全部关系移动到另一个节点上面,采用先建立新关系,之后删除原先的关系的方式
def move_relations(source_node_id,target_node_id,graph=None):
"""
将 source_node_id 上所有的关系移动到 target_node_id 上
"""
if source_node_id is None or target_node_id is None:
return
if graph is None:
graph = get_graph()
r_ids = []
match = "match (x)-[r]-(n) where id(x)=%s return r" % (source_node_id)
data = graph.run(match).data()
for d in data:
for tk,tv in d.items():
relations = tv.relationships
for r in relations:
if r.identity in r_ids:
continue
r_ids.append(r.identity) from_id = 0
to_id = 0
if r.start_node.identity == source_node_id:
from_id = target_node_id
to_id = r.end_node.identity
else:
from_id = r.start_node.identity
to_id = target_node_id
labels = ""
if r.types() is not None:
for la in r.types():
labels+=":" + la
fields = []
fields_str = ""
for k,v in r.items():
fields.append("%s:'%s'" % (k,v))
if len(fields) > 0:
fields_str = ",".join(fields)
fields_str = "{%s}" % fields_str
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)
result=graph.run(match).data()
if result is None or len(result)==0:
return False
match = "match ()-[r]-() where id(r)=%s delete r" % (r.identity)
graph.run(match)
return True return