Hi, one quick question. Is it possible
Hi, one quick question. Is it possible to retrieve a random element from the DB? That it always returns a random one.
1 Reply
hey @Llabe! we don't have built in support for this, but it's possible to implement this with a random field. here's the idea:
in your schema, add a
randomKey
field and define an index on it. I'll use a messages
table as an example:
then, whenever you insert into it, use Math.random()
for randomKey
. for example,
then, we'll use the randomKey
index to pick a row randomly. we'll pick a random number and find the subsequent row in randomKey
order:
so long as you don't delete records in a pattern correlated with randomKey
, the values should remain uniformly distributed on [0, 1)
, and the sample should be uniform.
let me know if this works for you!
I'd like to actually prove uniformity mathematically but haven't gotten around to it yet 🙂