9

I am using node driver version 6 of arangodb to insert relations between two vertices as follows.

db.collection("starks").save({ 
    _from: "Starks/Lyanna-Stark", 
    _to: "Starks/Ned-Stark", 
    type: "married" 
});

This inserts relation married between Starks/Lyanna-Stark and Starks/Ned-Stark into the database. But when I run this query twice, it is inserting it two times with different relation key. I want to avoid this as only one entry should be present for a single relation. How can I achieve this ?

Dipti
  • 93
  • 4

2 Answers2

8

Just create a unique index for all the relations that you are creating. For example, if the name of your relation collection is relations, then run this query to make the combination of "_from", "_to", "type" as unique

db.relations.ensureIndex({ 
    type: "hash", 
    fields: [ "_from", "_to", "type" ], 
    unique: true 
});

Here is the link for reference https://docs.arangodb.com/3.0/Manual/Indexing/Hash.html#ensure-uniqueness-of-relations-in-edge-collections

molecule
  • 883
  • 1
  • 12
  • 25
  • Just a fix, if the collection name is ```relations``` then query should also be ```db.relations.ensureIndex({ ... }); ``` :P – Saif Ali Khan Aug 18 '18 at 14:37
0

You are facing this problem for the simple fact that Arango is creating a new ID for everytime you save the object. The uniqueness of an edge record is achieved by the "_key" key.

In order to do so, you can either provide the "_key" key yourself, or you can alter the logic of your code to check if the record is already present in the db or not.

Nicolas El Khoury
  • 3,421
  • 3
  • 14
  • 19