views:

136

answers:

2

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:

  1. 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.

  2. 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);
            }
          }
        }
      }
    }
    
  3. 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
And perhaps, use an endkey parameter also, to avoid re-running the query.
Bart J
Good point. Thanks!
jhs
+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
Perhaps an improvement would be to emit `doc._rev.match(/^\d+-(\w+)$/)[1]`, i.e. the checksum portion of the revision property?
jhs