我想知道为什么要这样做
UserView.where(:user_viewable_type => 'Song').order('created_at desc').limit(5)
需要1213毫秒才能运行。有点慢吗?
在schema.rb user_viewable_type
中编入索引:
add_index "user_views", ["user_viewable_type"], :name => "index_views_on_viewable_type"
即使在psql中:
"index_views_on_viewable_type" btree (user_viewable_type)
使用.explain
运行返回:
UserView.where(:user_viewable_type => 'Song').order('created_at desc').limit(5).explain
UserView Load (1801.4ms) SELECT "user_views".* FROM "user_views" WHERE "user_views"."user_viewable_type" = 'Song' ORDER BY created_at desc LIMIT 5
EXPLAIN (1.6ms) EXPLAIN SELECT "user_views".* FROM "user_views" WHERE "user_views"."user_viewable_type" = 'Song' ORDER BY created_at desc LIMIT 5
=> "EXPLAIN for: SELECT \"user_views\".* FROM \"user_views\" WHERE \"user_views\".\"user_viewable_type\" = 'Song' ORDER BY created_at desc LIMIT 5\n QUERY PLAN\n-------------------------------------------------------------------------------\n Limit (cost=17113.28..17113.28 rows=5 width=37)\n -> Sort (cost=17113.28..17147.82 rows=69085 width=37)\n Sort Key: created_at\n -> Seq Scan on user_views (cost=0.00..16883.78 rows=69085 width=37)\n Filter: ((user_viewable_type)::text = 'Song'::text)\n(5 rows)\n"
所以我决定打破查询并删除order
,我得到:
UserView.where(:user_viewable_type => 'Song').limit(5).explain
UserView Load (1.6ms) SELECT "user_views".* FROM "user_views" WHERE "user_views"."user_viewable_type" = 'Song' LIMIT 5
似乎order('created_at desc')
导致查询速度变慢。但为什么?难道不能快点订购吗?
我在order
列上尝试id
:
UserView.where(:user_viewable_type => 'Song').order('id desc').limit(5).explain
UserView Load (44.8ms) SELECT "user_views".* FROM "user_views" WHERE "user_views"."user_viewable_type" = 'Song' ORDER BY id desc LIMIT 5
快得多!可能有什么不对?
我应该提几件事:
:live_viewable_type
通过Rails迁移将:user_viewable_type
重命名为t.rename :live_viewable_type, :user_viewable_type
。但是,我不认为这应该是问题,因为索引仍然在右栏。答案 0 :(得分:3)
据我所知,问题可能是:
a)您未在created_at
或:
b)数据库正在选择一个索引或另一个索引(即使用created_at
索引,使user_viewable_type
规范变慢,反之亦然。
如果您经常拨打这些电话,可能值得查看[created_at, user_viewable_type]
上的综合索引(或其他方式:[user_viewable_type, created_at]
,具体取决于哪种方式会更快地缩小搜索结果。)< / p>