I need a random query, but I don't know what's the best way to do this in the view.
CouchDB stores data as "documents", as one or more field/value pairs expressed as JSON. Field values can be simple things like strings, numbers, or dates; but ordered lists and associative arrays can also be used. Every document in a CouchDB database has a unique id and there is no required document schema.
Apache CouchDB (CouchDB (link resides outside IBM)) is an open source NoSQL document database that collects and stores data in JSON-based document formats.
CouchDB is an open source NoSQL database based on common standards to facilitate Web accessibility and compatibility with a variety of devices. NoSQL databases are useful for very large sets of distributed data, especially for the large amounts of non-uniform data in various formats that is characteristic of big data.
CouchDB is an open source project. Everything, from this website to the core of the database itself, has been contributed by helpful individuals.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With