Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select random record from mnesia

I have an mnesia table t that contains records with a single field x. How can I select a random value x from t?

To avoid the entire of process of mathematical pedantry: I don't care about the details of the random number generation, I just want my result to generally not be the same every time.

Thanks,
-tjw

like image 636
Travis Webb Avatar asked Feb 22 '26 17:02

Travis Webb


2 Answers

not really efficient but will work:

  1. generate random integer X
  2. get table size
  3. get pointer using mnesia:first
  4. iterate X times to random record
  5. lookup record

more sophisticated:

  1. create extra field containing integer
  2. integer is incremented on ever set
  3. create index over extra field
  4. random number X
  5. dirty read indexed row with X as a Key

one more:

  1. use int as primary key
  2. random int
  3. retrieve the row

Each of those solution has important faults: concurrent write performance, read overhead etc.

like image 84
user425720 Avatar answered Feb 25 '26 15:02

user425720


By using the mnesia:all_keys/1 (or dirty equivalent) function and the random module.

random_value(Table) ->
    Keys = mnesia:dirty_all_keys(Table),
    Key = lists:nth(random:uniform(length(Keys)), Keys),
    [#record{x = X}] = mnesia:dirty_read({Table, Key}),
    X.

Don't forget to initialize your seed using random:seed/3.

like image 42
Adam Lindberg Avatar answered Feb 25 '26 16:02

Adam Lindberg