Searching with sunspot solr. | Ram Laxman Yadav

Searching with sunspot solr.

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.

Here is an example to implement sunspot solr in rails applications.

Install Gem

Add these lines into your Gemfile

gem 'sunspot_rails'
gem 'sunspot_solr' # optional pre-packaged Solr distribution for use in development

Now run bundle install.

Generate a default configuration file:

rails generate sunspot_rails:install

Start sunspot solr

bundle exec rake sunspot:solr:start # or sunspot:solr:run to start in foreground.

Making objects to search by solr

Solr makes indexes for objects to perform search. To do this follow these steps:

Add a searchable block to the objects you wish to index.

class Post < ActiveRecord::Base
  searchable do
    text :title, :body    # text for text fields. 
    boolean :some_fields  # for boolean values.
    integer :id            # for int values.
    time    :some_fields   # for timestamps fields.

Re-index solr

When you make any changes in the searchable block then run the following command bundle exec rake sunspot:solr:reindex

Searching do
  fulltext 'some keywords'

You can modify search by these following steps:

  • Add with into search block to apply some conditions.
  • Add order_by into search block to order searched results.
  • You can paginate search results by adding paginate into search block.

For more details please click here. Enjoy !!!

Ram Laxman Yadav
Ram Laxman Yadav
Ruby on Rails Developer