incr() operation Michael was referring is available in the
2.x Java SDK as
See the doc here.
The idea is that Couchbase has the notion of
counter documents that can be incremented or decremented atomically.
So there’s no need for a view (which is less performant anyway), just use a separate counter document to generate your IDs (think of it like a
Sequence in RDBMS if you will). Construct an ID by appending the value obtained from the counter to other parts of the key as you see fit.
For example, to get the key “
//get relevant dynamic data (here the user's country code) from the `JsonObject` content you prepared:
String prefix = content.getString("countryCode"); //gives "FRA"
//append separator and "User" prefix:
prefix = prefix + "::User";
//atomically get the next sequence number:
// increment by 1, initialize at 0 if counter doc not found
long nextIdNumber = bucket.counter("idGeneratorForUsers", 1, 0); //gives 12345
String id = prefix + nextIdNumber; //gives "FRA::User12345"
//you're now ready to save your document: