我想添加索引以提高我的应用效果。
我想测量添加索引的性能。
例如我有以下表格:
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
答案 0 :(得分:1)
在该表上查找查询并测量创建索引之前和之后的时间的一种可能性。
PostgreSQL提供了一些关于表和索引的统计信息(9.1 docs) 我喜欢使用pg_stat_user_indexes来查看有关索引的所有统计信息 试着看一下,我认为你会在那里找到非常有用的信息 您还应该检查pg_stat_user_tables以查看在表上运行的全表扫描的次数。
答案 1 :(得分:0)
使用EXPLAIN (BUFFERS, ANALYZE)
或旧版本,EXPLAIN ANALYZE
。
这不仅可以为您提供查询时间,还可以告诉您正在使用哪些索引。
你也应该使用pg_stat_user_indexes
作为sufleR指出。