Rails 3 Database Indexes and other Optimization

↘锁芯ラ 提交于 2019-11-29 20:29:24
CharlesJHardy

It is always a good idea to add index's to your all ID's and data you 'find_by' on more then a few occasions e.g. email_address. Likewise you can safely assume that ID will never go into negative, so making ID columns Unsigned will benefit in the long run. Speak to any DBA (Database Administrator) and they will, more times than not tell you to do this.

Currently you most likely have something like this for all your ID Columns...

t.integer :column_name, :null => false

or...

t.references :column_name, :null => false

By simply changing this to...

t.column :column_name, 'integer unsigned', :null => false

You will see a tiny increase.

Index's are simple...

add_index :reviews, [:column_id, :column_type] # Polymorphic
add_index :reviews, :column_id # Standard

The Rails API should give you all you need to know.

Peepcode have a really get tutorial video that was a great insight to me and well worth the $12 and 37 minutes of your time. There are Gems like MetaWhere which may be able to help you as well.

Most importantly, in Rails 3 and above, is ActiveRelations. This is where Queries are only executed when required. For example instead off User.all you could call User.scoped and when the iteration in the View occurs the SQL in executed. Powerful stuff and the Future of Rails.

Let us know how you get on... All the best.

You wrote:

but when I added them to my database via migrations it only took a few seconds to add them. For some reason I thought they would have to go through all of my entries (of which there are thousands) and index them.

Indexing wont take long unless you have millions of records. DB Indexing is just a sort, and recording that sort to be used later.

Your index applied to both new and existing records.

UPDATE

Biggest bang for your buck:

  1. Move long running processes to delayed_job (or similar)
  2. Get rid of n+1 queries

Memcache is nice, but complicates your app, and you typically don't get the boost until your app is db read bound.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!