(py2neo) How to check if a connection 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 me say later:
link2 = neo4j.Path(friend_node,"friends",this_node)
link2.create_or_fail(graph_db)
Basically, there link.create_or_fail()
will be a function that either adds the link2 path to the database, or fails if the 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)
shouldn't do anything. Is such a function possible?
source to share
For this I used 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 a relationship with these filters.
The following link helped me figure it out.
source to share