Reputation: 1095
I'm using the neo4j python module neo4j-embedded to populate a neo4j graph. However I can't figure out how to make unique relationships between two nodes.
Currently I create a new relationship each time which is definitely not desired. The code below shows a simple example were I just create 9 nodes, and then look to connected them with the relationship "friendsWith", however currently these relationships are not unique and I end up with 153 relationships all but around 45 of which are redundant:
from neo4j import GraphDatabase
neo_db = GraphDatabase('../testdatabase/')
with neo_db.transaction:
person_idx = neo_db.node.indexes.create('people')
user_ids = [1,2,3,4,5,6,7,8,9]
for user in user_ids:
##########################################################################
## Check if user exists in neo4j,
## If not create it and save id, otherwise find the id.
##########################################################################
person_node = person_idx['name'][user].single
if person_node == None:
person_node = neo_db.node(name=user)
person_idx['name'][user] = person_node
for friend in user_ids:
##########################################################################
## Check if friend exists in neo4j,
## If not create it and save id, otherwise find the id.
##########################################################################
friend_node = person_idx['name'][friend].single
if friend_node == None:
friend_node = neo_db.node(name=friend)
person_idx['name'][friend] = friend_node
relationship = person_node.friendsWith(friend_node)
Is there any way of checking if a relationship of type "friendsWith" exists between two nodes using the python module mentioned above? Or a way of only creating the relationship if one of that type doesn't already exist.
I'm looking for a solution that preferable doesn't require querying the database using cypher and the query command.
Thanks for any help.
Edit:
I realise you can get the solution using cypher as follows, however I'm looking for a way that can be done using just python, ideally without any prior knowledge of cypher. Part of this being, I don't particularly want to have to write an ad-hoc query for functionality that I will be using extensively, just with different nodes and relationships.
result = neo_db.query("START n = node:people(name='%i'),m=node:people(name='%i') MATCH (n)-[r:friendsWith]-(m) RETURN r;"%(user,friend))
if result.single == None:
relationship = person_node.friendsWith(friend_node)
Upvotes: 1
Views: 429
Reputation: 41706
Why don't you want to use cypher?
If you want to avoid duplicates, you have to:
Otherwise you have to iterate over all rels on each create to check if the current to be added target node is already connected to the current source node.
Upvotes: 1