ruby-on-rails - add_index 在此代码中以及更一般的情况下用于什么?

标签 ruby-on-rails database indexing

我正在努力理解这段代码……它来自 Rails 教程书,是制作类似 Twitter 的应用程序过程的一部分。

class CreateRelationships < ActiveRecord::Migration
  def change
    create_table :relationships do |t|
      t.integer :follower_id
      t.integer :followed_id

      t.timestamps
    end

    add_index :relationships, :follower_id
    add_index :relationships, :followed_id
    add_index :relationships, [:follower_id, :followed_id], unique: true
  end

end
  • 因为只有 2 列(follower_id 和 followed_id),为什么 他们需要索引吗?
  • 索引是否以某种方式对它们进行排序?这似乎有点奇怪 我将索引添加到具有 2 列的表中。
  • 索引对行有什么作用?
  • 索引是可选的吗?如果是这样,为什么/为什么不使用它?在上面的代码中使用它是个好主意吗?

如果可以,请回答所有问题。我只是想了解这个概念,在阅读它之后我有这些问题。

最佳答案

Since there are only 2 columns (follower_id and followed_id) why would there be a need for an index?

索引的需要不依赖于列数。它用于加快查找速度。即使您的表只有一列,验证该列中是否存在特定值也需要您在最坏的情况下扫描整个表。有索引就可以马上回答。

Does the index sort them in some way? It just seems a bit strange to me to add an index to a table with 2 columns?

不,一般来说,索引不会以任何方式对表中的数据进行排序。我说“一般”是因为聚簇索引确实对数据进行了排序。参见 this question了解更多详情。

What does the index do to the rows?

同样,没有什么一般的。不同的 DBMS 使用不同的机制将表中的行关联到索引。编制索引是 DBA 工作中最重要的任务之一。如果您对此有基本的想法,那就太好了。阅读 wikipedia article获得基础知识。

Is indexing optional? If so why/why not use it?

是的,索引是可选的。当您看到查询性能下降时,您应该使用索引。同样,不同的 DBMS 为您提供不同的机制来监控您的查询性能,您应该进行监控以在性能下降超过阈值时提醒您。凭借经验,您将从一开始就清楚应用程序的大部分索引需求。

Is it a good idea to use it in the code above?

无法对此发表评论。每个应用程序的索引需求是不同的。您还应该意识到过度索引的缺点。如果您有很多索引,您的更新、插入和删除会随着时间的推移而变慢,因为它们也需要更新您的索引。

关于ruby-on-rails - add_index 在此代码中以及更一般的情况下用于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19923802/

相关文章:

ruby-on-rails - 致命 : Peer authentication failed for user "shop"

ruby-on-rails - 使用 ransacker 自定义搜索

database - 不能在oracle中删除表空间

indexing - 使用Redis排序集建立索引

ruby-on-rails - rails 3 : Disable session cookies

Mysql2::错误:表 "Admin_Users"已存在

ruby-on-rails - rails 、Postgres、EC2/AWS : Database Config Does Not Specify Adapter Error

database - 导出工具以在 Elasticsearch 2.3.5 索引之间通过查询复制数据

c - 打印可变参数函数中的数组索引

mysql - 优化sql查询