我应该在 Ruby on Rails 3.0 中的计数器缓存列上添加索引吗
环境:Rails 3.0.4、MySQL、Ruby 1.8.7
我有下表:
create_table "countries", :force => true do |t|
t.string "iso", :limit => 2, :null => false
t.string "name", :limit => 80, :null => false
t.string "printable_name", :limit => 80, :null => false
t.string "iso3", :limit => 3
t.integer "numcode", :limit => 2
t.integer "users_count", :default => 0
t.integer "rank"
end
我经常搜索用户数超过 n 的国家。向计数器缓存“users_count”添加索引是否有意义?
我意识到这会为添加的每个用户增加一点开销,但我想确保在计数器缓存的机制中没有遗漏其他东西,
Environment: Rails 3.0.4, MySQL, Ruby 1.8.7
I have the following table:
create_table "countries", :force => true do |t|
t.string "iso", :limit => 2, :null => false
t.string "name", :limit => 80, :null => false
t.string "printable_name", :limit => 80, :null => false
t.string "iso3", :limit => 3
t.integer "numcode", :limit => 2
t.integer "users_count", :default => 0
t.integer "rank"
end
I regularly search for countries with more than n users. Does it make sense to add an index to the counter cache 'users_count'?
I realize that it will add a slight overhead for every user added but I want to be sure that there is not something else that I'm missing in the mechanics of counter caches,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所说,添加索引将为每次数据库写入
countries
表增加一点开销,以换取加快使用该列的查询的速度。根据经验,除非您的写入量非常大,否则如果您执行大量引用
where
users_count 列的查询,则可能值得添加索引> 查询子句。Rails 计数器缓存功能只是在创建
belongs_to
国家/地区的用户时增加users_count
值,并在用户被销毁时减少该值。As you say, adding an index will add a slight overhead for every database write to the
countries
table, in exchange for speeding up queries that use the column.As a rule of thumb, unless you have a very high volume of writes it's probably worth adding the index if you do any significant number of queries that reference the
users_count
column in thewhere
clause of the query.Rails counter cache functionality simply increments the
users_count
value when a user thatbelongs_to
the country is created, and decrements it when the user is destroyed.