Reputation: 155
I want to create relationship between two existing nodes of different type in py2neo v3, can this only be done using the Cypher execution or is there a function(perhaps merge) that should do this?
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"))
The point is if alice has many many friends, and I make them all ahead of time because they have various other properties in a dictionary that I want have already looped over and made the nodes, how do I connect alice with those friends without create additional alices? I think merge would work but I don't understand its syntax.
Upvotes: 2
Views: 3866
Reputation: 1830
V3 has been giving me fits too, no examples out there yet. This is what worked for me. For merge to work you need to setup unique constraints.I do not use py2neo for setting up my database constraints. Here is the cypher command to run one time on you database.
Cypher Code to run once in Neo4j (also run one at a time if using browser)
CREATE CONSTRAINT ON (r:Role)
ASSERT r.name IS UNIQUE
CREATE CONSTRAINT ON (p:Person)
ASSERT p.name IS UNIQUE
Python code for application
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()
Upvotes: 6