NAME

VERSION

version 0.50

INTRODUCTION

The only unique constraint available in Elasticsearch is the document ID. Typically, if you want a document to be unique, you use the unique value as the ID.

However, sometimes you don't want to do this. For instance, you may want to use the email address as a unique constraint for your user accounts, but you also want to be able to link to a user account without exposing their email address, and let the user change their email address without having to update the ID of their user account wherever it is used.

In this case, we want the ID of the user document to be auto-generated, but we also want the value of the email attribute to be unique.

STORING UNIQUE KEYS

Elastic::Model adds support for unique constraints other than the ID. Your unique attributes are tracked in a special index which defaults to "unique_key", but which can be specified in your Model class:

APPLYING UNIQUE CONSTRAINTS

The unique_key value will be used as the type in the unique keys index. For instance, if the email is john@foo.com, then the unique entry for this document will be stored in index:myapp_uniques, under type:myapp_email with id:john@foo.com.

The unique_key can only be used once in a doc class. You can't have (eg) the attributes email_1 and email_2 both using a unique_key of myapp_email.

COMPOUND KEYS

It is easy to make a compound key a unique constraint. For instance, to combine the attributes account_type and account_name you could do:

The $failed hashref will contain a hashref whose keys are the name of the unique_keys that have conflicts, and whose values are the values of those keys which already exist, and so cannot be overwritten. For instance:

{
account_key => 'facebook:joe_bloggs'
}

INCOMPATIBILITIES

$doc->overwrite()

You can't overwrite a doc with unique keys that hasn't already been loaded from Elasticsearch. For instance, you can do:

The reason for this is that, if that user already exists, then overwriting that doc will leave any old unique keys in place. "save()" in Elastic::Model::Role::Doc will handle the old unique values correctly.