我应该在 Ruby on Rails 3.0 中的计数器缓存列上添加索引吗

发布于 2024-10-21 10:54:14 字数 656 浏览 6 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小清晰的声音 2024-10-28 10:54:14

正如您所说,添加索引将为每次数据库写入 countries 表增加一点开销,以换取加快使用该列的查询的速度。

根据经验,除非您的写入量非常大,否则如果您执行大量引用 whereusers_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 the where clause of the query.

Rails counter cache functionality simply increments the users_count value when a user that belongs_to the country is created, and decrements it when the user is destroyed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文