17

How to create unique items in RethinkDB?

In MongoDb I used ensureIndex for this, eg:

userCollection.ensureIndex({email:1},{unique:true},function(err, indexName){
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
daslicht
  • 814
  • 10
  • 26

2 Answers2

20

RethinkDB does not currently support uniqueness constraints on fields other than the primary key.

You could use an auxiliary table where the unique field is stored as the primary key in order to check for uniqueness in your application explicitly.

Daniel Mewes
  • 1,876
  • 14
  • 16
  • Thank you very much! Essentially I just like to make one field unique. If I can solve that with the PrimaryKey it's ok for me! – daslicht Jul 22 '13 at 14:34
  • 6
    Is this still the best solution? This was posted 3 years ago. – chovy Jun 20 '16 at 06:38
  • 1
    @chovy probably, I think they decided to nix unique secondary keys to avoid the kind of gotcha as in MongoDB allowing unique secondary keys but not guaranteeing their uniqueness across shards. – Andy Jul 18 '16 at 19:34
0

A relatively easy alternative would be to use a secondary index. Thus not messing with auxiliary tables.

You can than do the check in your application with the get_all method (http://rethinkdb.com/api/#js:selecting_data-get_all).

Chris Spiegl
  • 345
  • 3
  • 8
  • 12
    The problem is that you cannot do this atomically. I.e. between the time where you check the secondary index and find that the key does not exist, and the time where you actually insert the document, somebody else could insert a document with the same key. – Daniel Mewes Dec 06 '13 at 19:41
  • This link is broken. I don't mind if it's not gauranteed atomic -- but can you provide example code? – chovy Jun 20 '16 at 07:18