2015-04-16 65 views
3

我想在RethinkDB中随机订购文档。原因是我返回了文档组,并且每个组必须按顺序出现在结果中(因此属于一个组的所有文档都应该放在一起);我需要随机选择一个属于结果中第一组的文档(您不知道哪个是结果中的第一个组 - 第一个组可能是空的,因此没有为它们检索文档)。在RethinkDB中随机排序

我发现这个解决方案是在连接结果之前对每个组随机排序,然后总是从结果中选择第一个文档(因为它是随机的)。但我很难随机地订购这些组。如果有任何提示或甚至更好的解决方案,将不胜感激。

回答

2

如果您想随机订购一系列文件,只需使用.orderBy并使用r.random返回一个随机数。

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

如果这些文件在同一组中,你想他们随机组内,你可以调用orderBygroup语句之后。

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

如果你想随机化组的顺序,你可以叫orderBy后调用.ungroup

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

尼斯,我不知道,你可以使用'random'用'order_by'。也许你可以用这个事实来更新文档,这非常有帮助。感谢您的详细解答! – linkyndy

+0

我会通过这些建议。很高兴它是有用的! –

+0

你如何在python中做到这一点?这是js代码,因为它不在数据资源管理器中工作? – pregmatch

0

我没有得到这个工作。我试图随机排序的表,我发现了以下错误:

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

而且我的反思文档,这是不支持已经阅读。这是从rethinkdb排序依据的文件:

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.

如何得到这个工作有什么建议?

1

在这里接受的答案应该是不可能的,因为John提到的排序功能必须是确定性的,其中r.random()不是。

r.sample()函数可用于返回元素的随机顺序:

If the sequence has less than the requested number of elements (i.e., calling sample(10) on a sequence with only five elements), sample will return the entire sequence in a random order.

所以,算你有元素的数量,并设置数作为样本数,你会得到随机答复。

例子:

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