1
votes

I have two nodes between which, same edge with same property is being created over and over again. How can I avoid this? If the edges have different properties, its ok and it needs to be kept but if the properties are same, there should be one edge only.

EDIT: I'm using rails and I want to do this through application and not Cypher query.

EDIT: Sharing some code for relevance:

dis = Disease.where(disease: params[:disease]).first
fac = Factor.where(factor: params[:factor])
dis.factors.create(fac, prop: "p1")

So, what I want is if I input same disease and factor, it not duplicate the edge (which it is currently doing) as property being set is also same. However, if in future, this p1 changes to p2, then the edge should be added.

Refer post Neo4j inconsistent behaviour of model classes for model classes (Disease and factor).

2

2 Answers

1
votes

You have two options. You could use the unique option on your association(s):

http://neo4jrb.readthedocs.io/en/8.1.x/ActiveNode.html#creating-unique-relationships

This allows you to specify anything from there being only one of that relationship type between two nodes (regardless of properties), to only creating unique nodes if all properties are exactly the same. If you create an ActiveRel model, you can also do the same thing with the creates_unique declaration:

http://neo4jrb.readthedocs.io/en/8.1.x/ActiveRel.html#creating-unique-relationships

1
votes

You need to use MERGE keyword in cypher : it Match a pattern or create it if it does not exist.

This is an example based on the movie graph :

MATCH (neo:Person { name:"Keanu Reeves"})
MATCH (matrix:Matrix { title:"The Matrix"})
MERGE (neo)-[:ACTED_IN {roles:['neo']}]->(matrix)

You can execute this query multi-times, you will only have one edge between Neo & Matrix.

Cheers