2013-02-05 56 views
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 

回答

3

rake db:migrate将执行数据库迁移并立即应用indeces。您应该将indedes仅应用于您在搜索中使用的列。请记住,在insertupdate操作中,这些数据会增加时间处罚。如果通过他们的names上加载的记录,添加的indeces只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 
+0

谢谢你的提醒:)我使用的是太阳黑子搜索什么,如果?太阳黑子将它自己的索引放入我选择的属性中。例如,我为太阳黑搜索添加了“标题”属性。但是,它并没有在MySQL中编入索引。看来,太阳黑子自己正在做点什么。 – MKK

+1

如果您打算使用全文搜索引擎搜索文本(或同时使用复杂逻辑的多个列)。 Solr是一个非常好的解决方案。是的,Solr会建立自己的想法。 – tiktak

+0

我已经使用Solr实施了全文搜索。所以我不想去碰那个。它工作正常。我只是在MySQL的索引列表中看不到这些属性。但它应该没问题,对吧?所以现在我只是决定将索引添加到'community_name'和'username'。谢谢:) – MKK