Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I generate a partially unique and sequential field in a couchdb document?

I'm very new to couchdb and I'm wondering how I can create ID's that look like.

Employee:DBX-**0001**-SP

the number portion 0001 must be unique and sequential. How can I achieve something like this in couchdb? I searched all over and I cannot find any simple solution.

It would be best if I can generate the sequential portion in couchdb and not on the client side to avoid collisions during replication.

The current solution I have is that I fetch a document I've stored that looks like this {"_id": "EmployeeAutoIncrement", value: 1} upon retrieval I increment the value and send it back to the server if those are successful then I return the new incremented value and use it as my Auto Increment Value to be part of the ID Employee:DBX-AUTO_INCREMENT_VALUE_HERE-SP

The issue with this is that if two people make a request to the EmployeeAutoIncrement at the same time and they both update it will it not cause conflicts? Also, if one person makes a request and they go offline then they come back online then wouldn't that also make a conflict?

like image 730
Mani Muridi Avatar asked Oct 17 '22 07:10

Mani Muridi


1 Answers

All of the requirements cannot be satisfied client-side when using multiple clients, some of which might be off-line.

Here is a process that results in a monotonically-increasing id:

  1. Each client saves a record with a unique id. The record should include a flag marking the record as temporary.
  2. Build an external process that listens to the changes feed for records marked as temporary. The changes feed outputs records in "time order of application".
  3. The external process should create a new record with the correct id, flagging it as permanent. Since only that process creates "permanent" records, it can read and write the EmployeeAutoIncrement value without collisions.
  4. The external process can then delete the temporary record.

The database will have double the number of records, so it will grow more quickly and need to be compacted sooner if space is an issue. Any views/queries on the employee records will need to check for the permanent flag, in case a query runs while the external process is adding a new record.

like image 164
tephyr Avatar answered Oct 21 '22 00:10

tephyr