Choose a random entry from mnesia

I have a mnesia table tthat contains records with one field x. How to choose a random value xfrom t?

To avoid the whole process of mathematical pedantry: I'm not interested in the details of generating random numbers, I just want my result to not be the same at all every time.

Thanks,
-tjw

+3
source share
2 answers

Using a function mnesia:all_keys/1(or dirty equivalent) and a module random.

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.

Remember to initialize the seed using random:seed/3.

+4
source

not very effective, but will work:

  • generate random integer X
  • get table size
  • , mnesia: first
  • X

:

  • ,
  • X
  • dirty X

:

  • int
  • random int

: , ..

+5

All Articles