Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Rails/AR: Fast random records for ActiveRecord
Ruby
branch: master

This branch is 3 commits ahead, 2 commits behind grosser:master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
spec
README.markdown
Rakefile.rb
VERSION
init.rb
random_records.gemspec

README.markdown

Database (e.g. MySql) :order=>'rand()' is slow.

Solution

MethodSpeedRandomnessDuplicates
1 cluster from random offsetfastsomewhatno
X times 1 record from random offsetslow for large Xtotalpossible
n clusters of m record from random offsetfastgoodpossible

INSTALL

  • As Rails plugin: script/plugin install git://github.com/grosser/random_records.git
  • As gem: sudo gem install random_records

USAGE

Find many in single random cluster (no duplicates)

Model.random(1) == [Model(id:322)]
Model.random(3) == [Model(id:113),Model(id:112),Model(id:114)]
Model.with_valid_email.random(3) == [Model(id:114),Model(id:112),Model(id:113)]

Find many in many random clusters

The smaller the slower (each cluster = 1 request)
May include duplicates so use .uniq on results. Model.random(3, :cluster_size=>1) == [Model(id:112),Model(id:98),Model(id:214)]

Find one random

Model.random == Model(id:234)
Model.with_valid_email.random == Model(id:123)

TODO

  • prevent duplicates when finding in clusters (searching 9 of 10 -> many requests or tracking which offsets where already fetched)

AUTHOR

Michael Grosser
grosser.michael@gmail.com
Hereby placed under public domain, do what you want, just do not hold me accountable...

Something went wrong with that request. Please try again.