0
votes

I am trying to create a graph using some nodes and relationships using py2noe. say, I'm creating a family tree.

I am creating nodes using get_or_create() so that my script doesn't create duplicates if I supply the same value again.

How can I do the same for a relationship? I can't find any reference to a get_or_create() like function for a relationship.

I want to publish (Joe)-[:son]->(John) the first time it creates 2 nodes joe and john and a link between them. if I re run my script, as the nodes are unique, they aren't published but a new relationship is created.

This gives me a graph with 2 nodes and n relationships where n is the number of times I run the script.

I also tried using cypher and I get the same issue. It keeps on creating relationships.

Can anyone suggest me a way to solve this problem?

Thanks.

1

1 Answers

1
votes

I don't know py2neo (so there may be a wrapper for this function), but the way to achieve that would be using a Cypher MERGE which it looks like you have to run using the raw Cypher statement:

cypher_merge_result = neo4j.CypherQuery(graph_db, 
"MERGE (s:Person{name:Joe})-[:SON]->(f:Person{name:John})")

That will create 2 Person nodes and 1 SON relationship, no matter how many times that you run it.

Neo4J documentation is here and it is important to understand how it works as partial matches in the MERGE statement will cause the whole pattern to be created. So if your Person nodes already exist you should match them in advance to avoid duplicate Persons being created. i.e

cypher_merge_result = neo4j.CypherQuery(graph_db, 
"MATCH (s:Person{name:Joe}), (f:Person{name:John}) MERGE (s)-[:SON]->(f)")