Order randomly from RethinkDB

I want to arrange documents randomly in RethinkDB. The reason for this is that I am returning n

groups of documents and each group should appear in order (so all documents belonging to a group should be put together); and I need to randomly select a document belonging to the first group in the results (you don't know which one is the first in the results - the first ones might be empty, so no documents are obtained for them).

The solution I found is to randomly order each of the groups before agreeing with the result, then always select the first document from the results (since it will be random). But I find it difficult to arrange these groups randomly. Any hint, or even a better solution, if any, would be appreciated.

+3


source to share


3 answers


If you want to order the selection of documents randomly, you can simply use .orderBy

and return a random number using r.random

.

r.db('test').table('table')
  .orderBy(function (row) { return r.random(); })

      

If this document is in a group and you want to randomize them within a group, you can simply call orderBy

after the instruction group

.



r.db('test').table('table')
  .groupBy('property')
  .orderBy(function (row) { return r.random(); })

      

If you want to randomize the order of the groups, you can simply call orderBy

after by calling.ungroup

r.db('test').table('table')
  .groupBy('property')
  .ungroup()
  .orderBy(function (row) { return r.random(); })

      

+2


source


The accepted answer is not possible here, as John pointed out that the sort function must be deterministic, which r.random () is not.

The r.sample () function can be used to return a random order of elements:

If the sequence has less than the requested number of elements (that is, calling pattern (10) in a sequence with only five elements), the pattern will return the entire sequence in random order.



So, count the number of items you have and set that number as the example number and you will get a randomized answer.

Example:

var res = r.db("population").table("europeans")
              .filter(function(row) { 
                  return row('age').gt(18) 
              });
var num = res.count();
res.sample(num)

      

+1


source


I am not making this work. I tried to sort the table randomly and I get the following error:

e: Sorting by a non-deterministic function is not supported in: r.db("db").table("table").orderBy(function(var_33) { return r.random(); })

Also I read in the rethink documentation that this is not supported. This is from the rethinkdb orderBy documentation:

Sorting functions passed to orderBy must be deterministic. You cannot, for instance, order rows using the random command. Using a non-deterministic function with orderBy will raise a ReqlQueryLogicError.

Any suggestions on how to get this to work?

0


source







All Articles