Markus
Markus

Reputation: 1016

How to insert an auto increment / sequential number value in CouchDB documents?

I'm currently playing with couchDB a bit and have the following scenario: I'm implementing an issue tracker. Requirement is that each issue document has (besides it's document _id) a unique numerical sequential number in order to refer to it in a more appropriate way.

My first approach was to have a view which simply returns the count of unique issue documents currently stored. Increment that value on the client side by 1, assign it to my new issue and insert that. Turned out to be a bad idea, when inserting multiple issues with ajax calls or having multiple clients adding issues at the same time. In latter case is wouldn't be even possible without communication between clients.

Ideally I want the sequential number to be generated on couch, which is afaik not possible due to conflicting states in distributed systems.

Is there any good pattern one could use (maybe on the client side) to approach this? I feel like this is a standard kind of use case (thinking of invoice numbers, etc).

Thanks in advance!

Upvotes: 3

Views: 2338

Answers (2)

Benjamin M
Benjamin M

Reputation: 24567

You could use a separate document which is empty, though it only consists of the id and rev. The rev prefix is always an integer, so you could use it as your auto incrementing number.

Just make a POST to your document, this will increase the rev and return it. Then you can use this generated value for your purpose.

Alternative way:

Create a separate document, consisting of value and lock. Then execute something like: "IF lock == true THEN return ELSE set lock = true AND increase value by 1", then do a GET to retrieve the new value and finally set lock = false.

Upvotes: 1

Hans
Hans

Reputation: 2910

I agree with you that using a view that gives you a document count is not a great idea. And it is the reason that couchdb uses a uuid's instead.

I'm not aware of a sequential id feature in couchdb, but think it's quite easy to write. I'd consider either:

  • An RPC (eg. with RabbitMQ) call to a single service to avoid concurrency issues. You can then store the latest number in a dedicated document on a specific non distributed couchdb or somewhere else. This may not scale particularly well, but you're writing a heck of an issue tracking system before this becomes an issue.
  • If you can allow missing numbers, set the uuid algorithm on your couch to sequential and you are at least good until the first buffer overflow. See more info at: http://couchdb.readthedocs.org/en/latest/config/misc.html#uuids-configuration

Upvotes: 0

Related Questions