2
votes

I'm in starting neo4j and I'm using python3.5 and py2neo.

I had build two graph node with following code. and successfully create.[!

>>> u1 = Node("Person",name='Tom',id=1)
>>> u2 = Node('Person', name='Jerry', id=2)
>>> graph.create(u1,u2)

enter image description here

after that, I going to make a relation between 'Tom' and 'Jerry' Tom's id property is 1, Jerry's id property is 2.

So. I think, I have to point to existing two node using id property. and then I tried to create relation like below.

>>> u1 = Node("Person",id=1)
>>> u2 = Node("Person",id=2)
>>> u1_knows_u2=Relationship(u1, 'KKNOWS', u2)
>>> graph.create(u1_knows_u2)

above successfully performed. But the graph is something strange.

enter image description here

I don't know why unknown graph nodes are created. and why the relation is created between unknown two node.

3

3 Answers

6
votes

You can have two nodes with the same label and same properties. The second node you get with u1 = Node("Person",id=1) is not the same one you created before. It's a new node with the same label/property.

When you define two nodes (i.e. your new u1 and u2) and create a relationships between them, the whole pattern will be created.

To get the two nodes and create a relationship between them you would do:

# create Tom and Jerry as before
u1 = Node("Person",name='Tom',id=1)
u2 = Node('Person', name='Jerry', id=2)
graph.create(u1,u2)

# either use u1 and u2 directly
u1_knows_u2 = Relationship(u1, 'KKNOWS', u2)
graph.create(u1_knows_u2)

# or find existing nodes and create a relationship between them
existing_u1 = graph.find_one('Person', property_key='id', property_value=1)
existing_u2 = graph.find_one('Person', property_key='id', property_value=2)

existing_u1_knows_u2 = Relationship(existing_u1, 'KKNOWS', existing_u2)
graph.create(existing_u1_knows_u2)

find_one() assumes that your id properties are unique.

2
votes

Note also that you can use the Cypher query language with Py2neo:

graph.cypher.execute('''
   MERGE (tom:Person {name: "Tom"})
   MERGE (jerry:Person {name: "Jerry"})
   CREATE UNIQUE (tom)-[:KNOWS]->(jerry)
''')

The MERGE statement in Cypher is similar to "get or create". If a Person node with the given name "Tom" already exists it will be bound to the variable tom, if not the node will be created and then bound to tom. This, combined with adding uniqueness constraints allows for avoiding unwanted duplicate nodes.

2
votes

Check this Query,

MATCH (a),(b) WHERE id(a) =1 and id(b) = 2 create (a)-[r:KKNOWS]->(b) RETURN a, b