如何在Active Record迁移中向字段添加索引以更快地进行查询?

时间:2014-08-10 03:57:35

标签: sql ruby activerecord indexing query-optimization

我使用以下迁移来创建字典单词表:

class CreateTerms < ActiveRecord::Migration
  def change
    create_table :terms do |t|
      t.string :word, index: true
      t.timestamps
    end
  end
end

我尝试添加'索引'但由于某种原因我的查询仍然很慢。服务器日志:

Term Load (34.4ms)  SELECT "terms".* FROM "terms" WHERE (word LIKE ('launi%'))

当我用id更快地查找内容时:

Term Load (0.8ms)  SELECT "terms".* FROM "terms" WHERE "terms"."id" = $1 LIMIT 1  [["id", 143556]]

我是否正确添加了索引?

如何将第一个查询缩小到1 ms范围,如第二个?

1 个答案:

答案 0 :(得分:0)

您可以尝试的一件事是在主键上创建索引,并包含要进行搜索的列。这样可以更快地查询数据库 更容易。