How do I retrieve multiple random documents?

Is there a way to retrieve n documents from one bucket in a random manner? Where n > 1.

That is an interesting question!

What about creating a view where the key is an integer and in you app you grab it by random keys in that range?

Maybe that gives you a starting point

Thank you for your answer, @daschl .

Currently we retrieve a set of users that satisfies certain conditions and do the random selection from those users in our application layer. The question really refers to a Couchbase-native way of doing the random selection of users in a bucket that satisfy a given set of conditions.

There is no built-in command to load random documents - actually you are the first one I hear asking for it!

You can do this with the following view (or any view that emits every key in the bucket):

function (doc, meta) {

On the client side you would do the following (This example is using the new PHP 2.X client):

$cluster = new CouchbaseCluster('');
$bucket = $cluster->openBucket('beer-sample');
// Do a query to get the total number of docs in a view
$query = CouchbaseViewQuery::from('random', 'random')->skip(0)->limit(1);
$results = $bucket->query($query);
$max = $results['total_rows'];
// Generate a ramdon number between 0 and total number of docs
$rand = rand(0, $max);
// Get a random doc from the view.
$query = CouchbaseViewQuery::from('random', 'random')->skip($rand)->limit(1);
$results = $bucket->query($query);
foreach($results['rows'] as $row) {
        // Print the primary key of the doc

I have a pretty similar requirement where I need to pick a random no of id’s of couchbase records.
This is for very quick validation purpose.

@scalAnu and @citricn I know it’s been a while but I had the same exact issue it seems there are a few ways to go about this note I am using version 7.X.

First you can use a REST API (here I grab 10 random keys) as follows via curl:

curl -s -XGET -u ${CB_USERNAME}:${CB_PASSWORD} http://localhost:8091/pools/default/buckets/travel-sample/scopes/_default/collections/_default/localRandomKey?update_=[1-10] | jq .

Second you can look in some of the SDKs and utilize the function GetRandomDoc() for example look in for this function.

Now for a disclaimer this will work and I believe it is the basis for our N1QL INFER statement (but I would not bet the farm on high performance).

Also I believe both approaches it will only pull from in memory cache not disk.


Jon Strabala
Principal Product Manager - Server‌