How do I retrieve multiple random documents?


#1

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


#2

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


#3

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.


#4

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


#5

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

function (doc, meta) {
  emit();
}

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

<?php
$cluster = new CouchbaseCluster('http://127.0.0.1:8091');
$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
        var_dump($row['id']);
}