Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RMR12: Ruby vs. SQL

Gordon Diggs
September 21, 2012

RMR12: Ruby vs. SQL

Gordon Diggs

September 21, 2012
Tweet

More Decks by Gordon Diggs

Other Decks in Programming

Transcript

  1. At first, I did this settings.fields.each do |field| occurrences[field] =

    {} Item.all.each do |item| value = item.send(field.robotize) if occurrences[field][value] occurrences[field][value] += 1 else occurrences[field][value] = 1 end end if (others = occurrences[field].select{|k,v| v==1}.size) > 1 occurrences[field].delete_if{|k,v| v==1} occurrences[field]["Other"] = others end end
  2. OK, fine. What do? Reduce the need to do it:

    cache the result, only recalculate when something changes
  3. But it's still slow! Find another way to do it.

    Step 1: ditch mongodb for postgres
  4. A new dawn awaits SQL has cool stuff, like counting

    and grouping (we want that, right?)
  5. The new solution settings.fields.each do |field| occurrences[field] = {} items

    = DataMapper.repository.adapter.select( "SELECT #{field.robotize} as \"col\", COUNT(*) as \"times\" FROM items GROUP BY #{field.robotize} ORDER BY \"times\" desc") items.each do |item| occurrences[field][item[:col]] = item[:times] end if (others = occurrences[field].select{|k,v| v==1}.size) > 1 occurrences[field].delete_if{|k,v| v==1} occurrences[field]["Other"] = others end end
  6. The Benefits • Can run it whenever I want without

    repercussions • Scales way better • Can stare at graphs all day
  7. The Takeaway • There are things that ruby does really

    well, and things that SQL does better.