ID Initialization

First you have to setup the counter-id, this can be done on app initialization.
There are some alternatives depending on the SDK you are using.

# initialize the counter
c =		# => setup default connection
c.set("user::count", 0)		# => initialize counter

Increment on Create

Each time you want to create a new item, you increment the counter-id and use it as a component of the key.

Follow the variable new_id through this Ruby code to see how it is initialized, and used as a value, and used in the document key.

# retrieve the latest (so you see incr adds one...)
c.get("user::count")				# => 3

# increment the counter-id
new_id = c.incr("user::count")			# => new_id = 4

# store the counter-id as a self-reference
user_hash = {
	:uid => new_id, 
	:username => "jsmith", 
	:firstname => "John", 
	:lastname => "Smith" 

# create the document with the counter-id and hash
c.add("user::#{new_id}", user_hash)		# => save new user, with document key = "user::4"

Get the Document by ID

Retrieve the document based on the ID.
In this case we are just getting the latest user created, but it could be anywhere from counter-id = 1 to the current value of the counter-id (in this case 4).

# retrieve the latest
latest_user = c.get("user::count")		# => latest_user = 4

# retrieve the document with the index
user_info = c.get("user::#{latest_user}")	# => retrieve user document

puts user_info
# => { "uid" => 4, "username" => "jsmith", "firstname" => "John", "lastname" => "Smith" }

Many Uses for this Pattern

Creating an index based list
This list has individual items that are keyed based on the counter-id, useful for things like comments, users, products, and any other list of items that grows infinitely, or where an array would grow too big.
Globally Referenced Documents
Each document keyed with the atomic counter has a unique key, so it can be used as a reference in other documents, this is also why it functions differently than an array of items stored in json.
Guaranteed Unique Key
By using an always-incrementing atomic counter, each key generated using it is guaranteed to be unique. Atomic counters are the fastest to get/set/incr/decr, and their operations are always executed in order.
Combined with the Lookup Pattern, it can be the basis for many different models.

Q&A and Comments


Q&A and Comments

comments powered by Disqus