Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by Rand - How can I do in CouchDB?

Tags:

random

couchdb

I need a random query, but I don't know what's the best way to do this in the view.

like image 626
Lucas Renan Avatar asked May 09 '10 21:05

Lucas Renan


People also ask

How CouchDB stores data?

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.

Is CouchDB a NoSQL?

Apache CouchDB (CouchDB (link resides outside IBM)) is an open source NoSQL document database that collects and stores data in JSON-based document formats.

What type of database is CouchDB?

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.

Is CouchDB open source?

CouchDB is an open source project. Everything, from this website to the core of the database itself, has been contributed by helpful individuals.


2 Answers

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

like image 143
J Chris A Avatar answered Oct 01 '22 17:10

J Chris 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.

like image 25
JasonSmith Avatar answered Oct 01 '22 15:10

JasonSmith