Search code examples
arangodbarangojs

Duplicate documents getting inserted in edge collection


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 ?


Solution

  • 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: "persistent", 
        fields: [ "_from", "_to", "type" ], 
        unique: true 
    });
    

    Here is the link for reference https://docs.arangodb.com/3.11/index-and-search/indexing/index-basics/#ensuring-uniqueness-of-relations-in-edge-collections