如何为现有属性添加索引和重新索引?

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
1个回答

3

rake db:migrate将立即执行数据库迁移并应用索引。您应该仅对搜索中使用的列应用索引。请记住,索引会增加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

谢谢您的建议 :) 如果我正在使用sunspot搜索,该怎么办? sunspot将其自己的索引索引到我选择的属性。例如,我向sunspot搜索添加了“标题”属性。但是,在MySQL中没有对其进行索引。看起来,sunspot正在自行处理某些事情。 - MKK
1
如果您计划搜索文本(或同时使用复杂逻辑搜索多个列),请使用全文搜索引擎。Solr是一个非常好的解决方案。是的,Solr将建立自己的索引。 - tiktak
抱歉,最后一个问题!如果有两个表,例如tagstaggings,并且taggings具有tag_id属性。我应该为tag.nametagging.tag_id添加索引,因为它可以更快地获取与标签相关的记录吗? - MKK
1
当然可以。Solr会根据您的模型重新索引。 - tiktak
1
我认为你应该添加两个索引。 - tiktak
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接