【问题标题】:How to test adding indexes performance in Rails console?如何在 Rails 控制台中测试添加索引的性能?
【发布时间】:2012-11-22 09:43:54
【问题描述】:

我想添加索引来提高我的应用性能。

我想测量添加索引的性能。

例如我有下表:

create_table "classifications", :force => true do |t|
  t.integer  "app_id"
  t.integer  "user_id"
  t.integer  "topic_id"
  t.string   "targit_type"
  t.integer  "targit_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

我想在这里添加三个索引:

# Classification
add_index :classifications, :app_id, name: "index_classifications_on_app_id"
add_index :classifications, :user_id, name: "index_classifications_on_user_id"
add_index :classifications, [:target_id, :targit_type], name: "index_classifications_on_targit_id_and_targit_type"

所以我想衡量这种变化的效果。

最好的方法是如何做到这一点? 我应该在 Rails 控制台中这样做吗?

>> Agreement.find_by_user_id_and_review_id(User.last.id, Review.last.id)                                                                              
  User Load (14.2ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
  Review Load (4.5ms)  SELECT "reviews".* FROM "reviews" ORDER BY "reviews"."id" DESC LIMIT 1
  Agreement Load (2.2ms)  SELECT "agreements".* FROM "agreements" WHERE "agreements"."user_id" = 2064 AND "agreements"."review_id" = 1557 LIMIT 1

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-3 performance postgresql


    【解决方案1】:

    一种在该表上查找查询并测量创建索引前后时间的可能性。

    PostgreSQL 提供了一些关于表和索引的统计信息 (9.1 docs)。
    我喜欢使用 pg_stat_user_indexes 来查看有关索引的所有统计信息。
    尝试查看它,我认为您会在那里找到非常有用的信息。
    您还应该检查 pg_stat_user_tables 以检查在表上运行全表扫描的次数。

    【讨论】:

      【解决方案2】:

      使用EXPLAIN (BUFFERS, ANALYZE) 或在旧版本中,纯EXPLAIN ANALYZE

      这不仅会为您提供查询时间,还会告诉您正在使用哪些索引。

      正如 sufleR 指出的那样,您还应该使用 pg_stat_user_indexes

      【讨论】:

        猜你喜欢
        • 2016-03-20
        • 2016-04-16
        • 1970-01-01
        • 2021-07-24
        • 2023-03-27
        • 1970-01-01
        • 2010-11-06
        • 2019-03-06
        • 2013-04-19
        相关资源
        最近更新 更多