开发者

rails - created_at when user for ordering, Should you add an Index to the table?

开发者_StackOverflow社区

Hello for one of my models photos I have:

default_scope :order => 'photos.created_at DESC, photos.version DESC'

Given that I'm ordering by CREATED_AT and Version... Should I have a DB index on CREATED_AT?

Thanks


One trick that may be helpful: in typical MySql/ActiveRecord models, you will have id as a numeric primary key (hence implicitly indexed), which should be in the same order of created_at - which means you could order by id instead and get the fast performance, without the write cost for an extra index.


The following is based on my PostgreSQL experience but would probably also apply for MySQL and others.

If you plan on retrieving a large number of records from this table or making use of pagination, an index on the fields used in the ORDER BY would be useful.

You should create an index on all order fields in the same order. If you are mixing ASC and DESC in your ORDER BY you would need to create an index with these specific orderings to take full advantage of the index.

A suitable ActiveRecord migration for your photos table would be:

add_index :photos, [:created_at, :version]

I would recommend looking at the EXPLAIN ANALYZE output with production-like data before and after adding the index to confirm it is having the effect you are after.


Was just reading up on this last night as I was adding indices to a number of tables. The short answer is 'yes'. The case is quite eloquently made here:

https://web.archive.org/web/20140426154227/https://tomafro.net/2009/08/using-indexes-in-rails-choosing-additional-indexes

The longer answer is also 'yes' but why don't you test it out a bit and see what sort of mileage you get out of it based on how your app interacts with the data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜