Sunspot – power up your app with solr before knowing it

The title is a bit skeptical. Isn’t it? But trust me, it’s true. You can implement solr power searching in your Ruby on Rails application without knowing Solr. Yes, you off course know about Solr. What you don’t know is how to make it work for you. Let’s check how can you power your application with Solr using Sunspot gem.

What is Sunspot?

Sunspot is a Ruby library for expressive, powerful interaction with the Solr search engine. Sunspot is built on top of the RSolr library, which provides a low-level interface for Solr interaction; Sunspot provides a simple, intuitive, expressive DSL backed by powerful features for indexing objects and searching for them.

Using the sunspots DSL, you can easily implement solr powered searching. Its drop-in support with Rails models let you power your site with a few lines of codes.

Installation

Add the following line in your Bundle file.

gem 'sunspot_rails'
gem 'sunspot_solr'

Then run ‘bundle install’. 

Install the global configurations:

rails generate sunspot_rails:install

Configure your model to use Solr indexing:

class Post < ActiveRecord::Base
  searchable do
    text :title, :body
    text :comments do
      comments.map { |comment| comment.body }
    end

    boolean :featured
    integer :blog_id
    integer :author_id
    integer :category_ids, :multiple => true
    double  :average_rating
    time    :published_at
    time    :expired_at

    string  :sort_title do
      title.downcase.gsub(/^(an?|the)/, '')
    end
  end
end

Your model is configured. When you add new contents to your Model, it will be auto indexed by Solr using ‘save’ callbacks.

Now you can use the solr to search for contents (Blog)

Post.search do
  fulltext 'best pizza'

  with :blog_id, 1
  with(:published_at).less_than Time.now
  order_by :published_at, :desc
  paginate :page => 2, :per_page => 15
  facet :category_ids, :author_id
end

You are almost done. Before before chiming in, start solr.

Start Solr

bundle exec rake sunspot:solr:start

If you change to your schema, you need to reindex.

bundle exec rake sunspot:solr:reindex

You’re done. Start enjoying. However, when your problems gets complex, you may need to consult the official page or github pages.

Disclaimer: All the codes are copied from gem’s github page.