How do I retrieve a random document in a view?

Hi. I'd like to create a view that will select a random document of a specified type. For example, let's say I have the following documents:

{
  "uid": 1,
  "name": "Bill",
  "company": "ABC"
}
 
{
  "uid": 2,
  "name":"Todd",
  "company":"ABC"
}
 
{
  "uid": 14,
  "name": "Sara",
  "company": "DEF"
}

I'd like to create a view that will get a single employee from company ABC, by random index. I'm new to Couchbase, so my logic may be way off, but I'm thinking I must first know the total number of documents with "company" equal to "ABC" (N), then generate a random number < N, and finally get the document in that index.

That seems complicated compared to how you'd get a random row, so I'm wondering if I'm missing something here. Is there a way to accomplish this in a view? If anyone could point me in the right direction, it would be greatly appreciated. Thanks!

1 Answer

« Back to question.

This can be made much simpler by choosing the right keying scheme for your documents. My approach to this would be to base the keys of a counter in Couchbase. In pseudo code this looks like this

counter = couchbase.incr("item-counter")
couchbase.add("items::" + counter, { "item": "foo", "description": "bar", "type": "item"})

now all you have todo to get a random document is read the counter state, generate a random number between 1-and the counter value, and do a get, again in pseudo code

counter_value = couchbase.get("item-counter")
random_counter = random(1, counter-value)
random_item = couchbase.get("items::" + random_counter)

Deciding on a good keying strategy is very important when using Couchbase and there are many options. A quick intro to it can be found in this Couchbase Webinar

Hope this helps