ruby on rails-如何向现有属性添加索引和重新索引



我正在通过类似的代码获取记录

@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

rake db:migrate将执行数据库迁移并立即应用indeces。您应该仅将索引应用于搜索中使用的列。请记住,indeces会在insertupdate运算上添加时间惩罚。如果按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

相关内容

  • 没有找到相关文章

最新更新