理解 Py2neo 上的合并问题

Ben*_*ire 2 merge neo4j py2neo

我想在 py2neo v3 中创建两个不同类型的现有节点之间的关系,这只能使用 Cypher 执行来完成还是有一个函数(也许是合并)应该这样做?

例如

from py2neo import Graph, Path, authenticate, GraphObject
from py2neo import Node, Relationship
from py2neo.ogm import *

a = Node("type1",name = "alice")
graph.create(a)
b = Node("type2",name = "bob")
graph.create(b)

#now I want to make a relationship of these nodes without using a, b or Relationship
#Hence something like:
graph.merge(Node("type1",name = "alice"),"FRIENDS_WITH",Node("type2",name = "bob"))
Run Code Online (Sandbox Code Playgroud)

关键是如果 alice 有很多朋友,我提前把他们都做了,因为他们在我想要的字典中有各种其他属性已经循环并制作了节点,我如何将 alice 与这些朋友联系起来而不创建额外的爱丽丝?我认为合并会起作用,但我不明白它的语法。

Eri*_*lfs 6

V3 也给了我适合,还没有例子。这对我有用。要使合并工作,您需要设置唯一约束。我不使用 py2neo 来设置我的数据库约束。这是在您的数据库上运行一次的 cypher 命令。

在 Neo4j 中运行一次的 Cypher 代码(如果使用浏览器,也一次运行一个)

CREATE CONSTRAINT ON (r:Role)
ASSERT r.name IS UNIQUE

CREATE CONSTRAINT ON (p:Person)
ASSERT p.name IS UNIQUE
Run Code Online (Sandbox Code Playgroud)

应用程序的 Python 代码

from py2neo import Graph,Node,Relationship,authenticate
n1 = Node("Role",name="Manager")
n2 = Node("Person",name="John Doe")
n2['FavoriteColor'] = "Red" #example of adding property
rel = Relationship(n2,"hasRoleOf",n1) #n2-RelationshipType->n1
graph = Graph()
tx = graph.begin()
tx.merge(n1,"Role","name") #node,label,primary key
tx.merge(n2,"Person","name") #node,label,pirmary key
tx.merge(rel)
tx.commit()
Run Code Online (Sandbox Code Playgroud)