V_TS
V_TS

Reputation: 139

(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?

Upvotes: 3

Views: 3252

Answers (2)

AKJ
AKJ

Reputation: 328

If you have landed here searching for newer version pf py2neo then you can call match_one to check the relationship:

graph.match(nodes = nodeList, r_type = rtype)

where nodeList is a sequence of nodes for the relationship and rtype is relationship type.

Upvotes: 0

Salvador Medina
Salvador Medina

Reputation: 6621

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.

Upvotes: 5

Related Questions