我正在通过类似的代码获取记录
@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会在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