1

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).

vish4071
  • 5,135
  • 4
  • 35
  • 65

2 Answers2

1

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

logisima
  • 7,340
  • 1
  • 18
  • 31
1

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

Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
  • But in this case, for different properties also, I won't be able to make multiple edges, right? – vish4071 Jul 10 '17 at 19:00
  • If you use `unique: true` / `unique: :none` (both are the same), only one relationship of that relationship type will be created. If you specify `unique: :all`, it will always create a new relationship unless all of the attributes are the same. The `:on` option lets you specify properties more specifically – Brian Underwood Jul 11 '17 at 16:49
  • Yeah...Thanks. The documentation is super :) – vish4071 Jul 12 '17 at 07:16