Index document only if it is unique by property

(Dobromir) #1

Is there a way to index a document only if it is unique by property name for example.
I already have read about the opType options, but they force me to use ID when I index a document, and I don`t know to. My goal is to write something like this:

index: myIndex,
type: myType,
body: {name: 'TEST1', age: 42}


and if a document with name TEST1 already exists, this query to fail somehow.

(Mujtaba Hussain) #2

You can create the ID for the document using the name filed somehow! E.g.

Magical function f(x) -> uuid

f("Gollum") -> 12345
f("Smeagol") -> 12346

So given data d = {'name': 'TEST' ... }, when you do an insert, you can use _id: f(d['name']) and if the d['name']field is duplicate the index will fail as the _id field has to be unique.

Mind you, this will only work for index operation, not update.

(system) #3

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.