Search code examples
pythonneo4jpy2neo

(py2neo) How to check if a relationship exists?


Suppose I have the following code:

    link = neo4j.Path(this_node,"friends",friend_node) #create a link between 2 nodes
    link.create(graph_db) #add the link aka the 'path' to the database

But let's say later I call:

link2 = neo4j.Path(friend_node,"friends",this_node)
link2.create_or_fail(graph_db)

Basically, link.create_or_fail() would be a function that either adds the link2 path to the database or it fails if a path already exists.

In this case, when I called link = neo4j.Path(this_node,"friends",friend_node) , I already created a path between this_node and friend_node so link2.create_or_fail(graph_db) should do nothing. Is such a function possible?


Solution

  • What I have done for that is use the following function:

    def create_or_fail(graph_db, start_node, end_node, relationship):
        if len(list(graph_db.match(start_node=start_node, end_node=end_node, rel_type=relationship))) > 0:
            print "Relationship already exists"
            return None
        return graph_db.create((start_node, relationship, end_node))
    

    The method graph_db.match() looks for the relationship with the given filters.

    The following link helped me out to understand that.