使用 Py2Neo 通过合并更新节点

Updating a node with merge using Py2Neo

我正在尝试使用 py2neo 库合并然后更新图形。我的代码看起来大致像

from py2neo import Graph, Node, Relationship

graph = Graph(host, auth=(user, password,))

tx = graph.begin()
alice = Node("Person", name="Alice")
bob = Node("Person", name="Bob")
KNOWS = Relationship(alice, "KNOWS", bob)
tx.create(KNOWS)
graph.commit(tx)

这会按预期创建节点和边

(:Person {name: "Alice"})-[:KNOWS]->(:Person {name: "Bob"})

如果我尝试在新交易中修改 alice,我没有得到任何改变

例如

new_tx = graph.begin()
alice["age"] = 32
new_tx.merge(alice, "Person", "name")
graph.commit(new_tx)

我怀疑我误解了 Transaction 在这里的工作原理。我希望以上内容等同于找到 Alice 并使用新 属性 更新或创建新节点。

更新:我发现了 Graph.push 方法,但仍希望获得有关最佳实践的建议。

您需要定义一个主键,让 MERGE 知道哪个 属性 用作主键。来自文档:

The primary property key used for Cypher MATCH and MERGE operations. If undefined, the special value of "id" is used to hinge uniqueness on the internal node ID instead of a property. Note that this alters the behaviour of operations such as Graph.create() and Graph.merge() on GraphObject instances.

为每个节点类型定义自定义 class 并在其中定义主键可能是最佳做法。

class Person(GraphObject):
    __primarykey__ = "name"

    name = Property()
    born = Property()

    acted_in = RelatedTo(Movie)
    directed = RelatedTo(Movie)
    produced = RelatedTo(Movie)