I need a random query, but I don't know what's the best way to do this in the view.
+2
A:
A basic strategy is:
Store a random value in the document
{ "_id": "7a36b03f3f2899064a1db5e0a6004204", "random": 0.875111079382808 }
You can either compute
random
when you store the document or use an_update
function to add it for you.Make a view keyed on that value, effectively shuffling them.
{ "_id": "_design/myapp", "comment": "Function left naked for clarity; it should be a string", "views": { "random_docs": { "map": function(doc) { if(doc.random) { emit(doc.random, doc); } } } } }
Choose a random number at query time, e.g. 0.4521, and GET
/db/_design/myapp/_view/random_docs?limit=1&startkey=0.4521
.
There is a chance (1 / total_rows) you choose a random number greater than any in the view. So if you need to be bulletproof, you should re-run the query if you get 0 rows.
jhs
2010-05-10 05:07:14
And perhaps, use an endkey parameter also, to avoid re-running the query.
Bart J
2010-06-11 09:45:02
Good point. Thanks!
jhs
2010-06-11 11:55:57
+3
A:
I've gotten by with using Math.random() in my view key. But you have to understand that it will be deterministic, so you can't use it for randomness in your app (just for things like sampling data, or splitting a database.)
J Chris A
2010-05-10 07:47:40
Perhaps an improvement would be to emit `doc._rev.match(/^\d+-(\w+)$/)[1]`, i.e. the checksum portion of the revision property?
jhs
2010-05-10 10:15:09