PHP SDK version 2 - how do you know what the next document number should be?

#1

Hello there.
I’m coming from a postgresql background where we have a “DEFAULT” keyword that will automatically insert your record with the next available number… assuming your table was created using a PK that’s set to auto increment.
I’m wondering how to do something similar with couchbase. I’ve manually added some documents that are called “audit_1” and “audit_2” but I’d like a way to programmatically assign these document names. Or maybe I need a complete paradigm shift. ??

I’ve been reading this: http://developer.couchbase.com/documentation/server/4.1/sdks/php-2.0/documents.html
But there’s not enough information there about how one goes about choosing a document id / document name.

Any tips would be appreciated.
Thanks.

#2

If you leverage some of the KV capabilities along with N1QL, you can use an atomic ‘counter’ document as a place to maintain a sequence. It’s a bit different in that you’ll increment it first, but the cost is fairly cheap.

One other technique is to simply increment the number in the application and use the KV insert which will fail if the document already exists. This one is a bit more costly since if you have many PHP application servers and a high creation rate, you will use a lot of network IO. It’s fairly inexpensive on the server in processing, so this is a valid technique in situations where network IO is low-latency/high-throughput.

#3

In addition to what @ingenthr suggested, you can use the UUID() function in N1QL to generate a primary key.

#4

ok so, so far, I’ve been naming documents like this:

"automated_audit_1"
"automated_audit_2"
“automated_audit_3”

so perhaps I could do something like this:

  1. somehow select the latest record that matches the “automated_audit_?” pattern and then,
  2. parse the digit at the end. increment it by 1.
  3. use the integer from step 2 and use in with the “counter() method”… something like this:
    **counter(‘counter_id’, delta=1, initial=myvariable);

Does that sound reasonable?