Search code examples
pythonneo4jpy2neo

Create relationship on pre-existing node in py2neo


I am trying to create a simple graph in Neo4j. What I'm trying to do is create a node if it doesn't exist, and if it already exists, I want to connect a new node to it instead of creating a similar node.

One node is a User node, the others are restaurant name, cuisine, and location. if a restaurant serves a cuisine that already exists as a node, I want to connect that restaurant to the pre-existing cuisine node.

def add_restaurant(self, name, cuisine, location):
    user=self.find()
    restaurant = Node("Restaurant", id=str(uuid.uuid4()),name=name)
    #graph.create(restaurant)
    graph.create_unique(rel(user,"LIKES", restaurant))

    rest_type = Node("Cuisine", cuisine=cuisine)
    #graph.create(rest_type)
    graph.create_unique(rel(restaurant,"SERVES", rest_type))

    loc = Node("Location", location=location)
    #graph.create(loc)
    graph.create_unique(rel(restaurant, "IN", loc))

This code works, but it creates a new node every time a cuisine or location is added. Is there a way in py2neo to find an already existing node and build the relationship on it so I can have a more connected graph?


Solution

  • I think you are looking for the graph.merge_one() function:

    rest_type = graph.merge_one("Cuisine", "cuisine", cuisine)
    graph.create_unique(rel(restaurant,"SERVES", rest_type))
    loc = graph.merge_one("Location", "location", location)
    graph.create_unique(rel(restaurant, "IN", loc))
    

    This uses the MERGE function which acts as a "get or create" based on the Label and key,value specified for the property: if a matching Node exists it will return it, if not then it will be created and returned.