Question

I am following this tutorial to access neo4j db using python. According to this tutorial I have created 2 relations among 4 nodes. The code is given below

alice, bob, rel = graph_db.create(
                      {"name": "Alice"}, {"name": "Bob"},
                      (0, "KNOWS", 1))
dev, carol, rel = graph_db.create(
                      {"name": "Dev"}, {"name": "Carol Smith"},
                      (0, "KNOWS", 1))

How can I create relation between alice and carol without creating new node?

Following code snippet is given in that tutorial to create relation between existing node. Not sure how to use how to use this in above case.

ref_node = graph_db.get_reference_node()
alice, rel = graph_db.create(
                {"name": "Alice"}, (ref_node, "PERSON", 0))

When I try to execute

ref_node = graph_db.get_reference_node()

I get the following error.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'GraphDatabaseService' object has no attribute 'get_reference_node'

Any suggestion to solve this issue?

Was it helpful?

Solution

I tried the following and got the results I think you want:

from py2neo import neo4j, node, rel

graph = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")

alice, = graph.create(node(name="Alice")) # Comma unpacks length-1 tuple.
bob, = graph.create(node(name="Bob"))
carol, = graph.create(node(name="Carol Smith"))
dev, = graph.create(node(name="Dev"))

graph.create(rel(alice, "KNOWS", bob))
graph.create(rel(dev, "KNOWS", carol))
graph.create(rel(alice, "KNOWS", carol))

My graph now looks like this in the browser:

enter image description here

Alternatively, you can create the graph in one graph.create() statement:

from py2neo import neo4j, node, rel

graph = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")

graph.create(
    node(name="Alice"),       #0
    node(name="Bob"),         #1
    node(name="Carol Smith"), #2
    node(name="Dev"),         #3
    rel(0, "KNOWS", 1),
    rel(3, "KNOWS", 2),
    rel(0, "KNOWS", 2)
)

And the output is the same. Hope this helps.

OTHER TIPS

The reference node was a feature included in earlier versions of Neo4j and, by extension, py2neo. It has since been deprecated and removed so I should have also removed all traces from the py2neo documentation - it appears I've missed one!

Thanks for pointing this out, I'll add myself a task to get this page up to date.

In terms of creating a relationship, Nicole's answer is spot on and should have all the information you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top