Search code examples
pythonneo4jpy2neo

py2neo, neo4j: How to create relation between two existing node


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?


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.