Last Updated: February 25, 2016
·
2.078K
· manudwarf

Full-text search in Ruby with picky

Hey guys,

I just migrated my bus and tramway webapp search engine to Picky, a wonderful gem that I found that makes full-text REALLY easy.

First step, add picky to your Gemfile.

Then, update the model :

class Stop < ActiveRecord::Base
  after_save :reindex

  def reindex
    StopIndex.replace self
  end

  def self.search s
    ids = (StopSearch.search s).ids
    where "id in (?) and enabled is true", ids
  end

end

And finally, add an initializer config/initializers/picky.rb

if Stop.table_exists? then
  StopIndex = Picky::Index.new :stops do
    source Stop.all

    # This will add all attributes to the index.
    Stop.attribute_names[1..-1].each do |cname|
      category cname.to_sym
    end
  end

  StopSearch = Picky::Search.new StopIndex

  begin
    # Try to load the index from cache.
    StopIndex.load
  rescue
    # Index on first boot or on database changes.
    StopIndex.index
  end

  # Save the index program exit.
  at_exit { StopIndex.dump }
end

1 Response
Add your response

Nice one :) Also note that you can use source { Stop.all } instead of source Stop.all to have it be executed when StopIndex.index is called. Cheers

over 1 year ago ·