3

我正在通过代码获取记录,就像这些

@community = Community.find_by_community_name(params[:community_name])
@user = User.find_by_username(params[:username])

我想让它加载更快,所以我想像这样为它们添加索引。
如果我这样做rake db:migrate,它是否也会重新索引到现有记录?
或者只是从现在开始创建的记录?
像这样添加索引是否提高了加载速度?

class AddIndexToCommunity < ActiveRecord::Migration
  def self.up
    add_index :communities, [:community_name, :title, :body], :name=>:communities_idx
  end

  def self.down
    remove_index :communities, [:community_name, :title, :body], :name=>:communities_idx
  end
end



class AddIndexToUser < ActiveRecord::Migration
  def self.up
    add_index :users, [:username, :nickname, :body], :name=>:users_idx
  end

  def self.down
    remove_index :users, [:username, :nickname, :body], :name=>:users_idx
  end
end
4

1 回答 1

3

rake db:migrate将执行数据库迁移并立即应用索引。您应该仅将索引应用于您在搜索中使用的列。请记住,indeces 会增加操作的时间insert损失update。如果您按它们加载记录names,则仅将索引添加到names

class AddIndexToCommunity < ActiveRecord::Migration
  def self.up
    add_index :communities, :community_name
  end

  def self.down
    remove_index :communities, :community_name
  end
end



class AddIndexToUser < ActiveRecord::Migration
  def self.up
    add_index :users, :username
  end

  def self.down
    remove_index :users, :username
  end
end
于 2013-02-05T14:33:29.377 回答