Search code examples
ruby-on-railsrubyelasticsearchsearchkick

Optimizing Searchkick in Rails 4


I'm using ES and Searchkick gem to handle searches in my Rails app. I'm currently doing:

class Paper < ActiveRecord::Base
  belongs_to :report
  belongs_to :user
  before_destroy :delete_dependant_papers

  searchkick word_start: [:realname]
end

This works great but it is unnecessarily indexing every column. I want it to index only the "realname" column.

I then came across search_data in the Searchkick GitHub page. This allows me to index only certain columns:

class Product < ActiveRecord::Base  
def search_data
    as_json only: [:name, :active]
    # or equivalently
    {
      name: name,
      active: active
    }
  end
end

How would I combine both of these? So that only 1 column is indexed with realname and word_start?


Solution

  • search_data method will let you index realname, and word_start will let you partially match your data. So your model need to look like this:

    class Paper < ActiveRecord::Base
      belongs_to :report
      belongs_to :user
      before_destroy :delete_dependant_papers
    
      searchkick word_start: [:realname]
    
      def search_data
        as_json only: [:realname]
      end
    end
    

    You need to call Paper.reindex in your console after changing search_data method.