Sunspot with ActiveRecord outside Rails
Written on March 6, 2012
I heard Sunspot is still the most popular option for open source search engine for Ruby developers. I believe because of its great support for integration with ActiveRecord and Rails. But, if you want to use Sunspot as a standalone engine and access it with ActiveRecord but without Rails you might want to understand how it’s actually works, and how to make it works.
First make sure you already run the Sunspot server, it’s like sunspot-solr start if you’ve already installed sunspot-solr gem, then setup the sunspot url if you set it up using non-default port.
Sunspot.config.solr.url = 'http://localhost:9999/solr'
Then we need to create adapters for the model we want to index in sunspot, let’s say we have Post model.
class PostInstanceAdapter < Sunspot::Adapters::InstanceAdapter
def id
@instance.id
end
end
class PostDataAccessor < Sunspot::Adapters::DataAccessor
def load(id)
Post.find(id)
end
def load_all(ids)
Post.find_all_by_id(ids)
end
end
The next step is to define the ActiveRecord model and add indexing callback on save and destroy.
class Post < ActiveRecord::Base after_save :index_to_sunspot after_destroy :remove_sunspot_index private def index_to_sunspot Sunspot.index(self) Sunspot.commit end def remove_sunspot_index Sunspot.remove!(self) Sunspot.commit end end
We’re almost done, the last thing to do is register the adapters to Sunspot with the ActiveRecord model we defined before and setup index of ActiveRecord with Sunspot, here is an example.
Sunspot::Adapters::InstanceAdapter.register(PostInstanceAdapter, Post) Sunspot::Adapters::DataAccessor.register(PostDataAccessor, Post) Sunspot.setup(Post) do text :body text :title time :published_at, trie: true end
Tags: sunspot, sunspot activerecord, sunspot rails