理解Py2neo上的合并有问题

时间:2016-08-04 14:46:08

标签: merge neo4j py2neo

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

E.g。

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"))

关键是如果爱丽丝有很多朋友,而且我提前制作它们因为他们在字典中有各种其他属性我想要已经循环并制作节点,我如何与这些朋友连接alice没有创造额外的灵气?我认为合并会起作用,但我不理解它的语法。

1 个答案:

答案 0 :(得分:3)

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

Cypher Code在Neo4j中运行一次(如果使用浏览器,也一次运行一次)

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

CREATE CONSTRAINT ON (p:Person)
ASSERT p.name IS UNIQUE

应用程序的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()