尝试使用py2neo V3以事务方式添加节点和关系。 我想将此人和他们所有的电影添加为一个交易。
我无法让外部和内部循环中的节点在同一个事务中工作。我很自信这种关系不是以交易方式添加的,因为我正在调用tx1.graph。
Neo4j V3.0.7 Py2Neo v3.1.2
from py2neo import Graph,Node,Relationship,authenticate, watch
from py2neo.ogm import GraphObject, Property, RelatedTo, RelatedFrom
class Movie(GraphObject):
__primarykey__ = "title"
title = Property()
class Person(GraphObject):
__primarykey__ = "name"
name = Property()
acted_in = RelatedTo(Movie)
People = ["John","Jane","Tarzan"]
Movies = [["John","Movie1"],["John","Move2"],["Jane","Movie3"],["Jane","Movie4"],["Tarzan","Movie4"]]
graph = Graph("http://localhost:7474")
for p in People:
print(p)
tx = graph.begin()
p1 = Person()
p1.name = p
tx.merge(p1)
tx.commit()
for m in Movies:
if m[0] != p:
continue
print(m[1])
tx1 = graph.begin() #did not work using original tx transaction
m1 = Movie()
m1.title = m[1]
tx1.merge(m1)
p1.acted_in.add(m1)
#tx1.merge(p1) #did not create relationship
#tx1.create(p1) #did not create relationship
tx1.graph.push(p1) # worked in adding relationship, but can't guarantee was part of the transaction
tx1.commit()
答案 0 :(得分:1)
尝试以下循环,它为每个Person
及其关系使用单个事务:
for p in People:
print(p)
tx = graph.begin()
p1 = Person()
p1.name = p
tx.merge(p1)
for m in Movies:
if m[0] != p:
continue
print(m[1])
m1 = Movie()
m1.title = m[1]
tx.merge(m1)
p1.acted_in.add(m1)
tx.graph.push(p1)
tx.commit()
注意:使用单个事务处理多个人实际上会更有效。但是你不希望同时处理太多(取决于你的数据模型),因为这会使服务器内存不足。