- Install the gem
$ gem install sunspot_rails
- Edit your config/environment.rb to include
config.gem 'sunspot', :lib => 'sunspot'
config.gem 'sunspot_rails', :lib => 'sunspot/rails'
- Generate the sunspot configuration file in config/sunspot.yml
$ ./script/generate sunspot
- Run the Solr service
$ rake sunspot:solr:start
(if Rake complains that it couldn’t find this task, add require 'sunspot/rails/tasks' to the top of your Rakefile).
Defining an Index
class Article < ActiveRecord::Base
text :title, :boost => 2.0
text :author_name do
time :updated_at # for sorting by recent
string :sort_title do # for sorting by title, ignoring leading A/An/The
boolean :published, :using => :published?
state == :published
class SearchController < ApplicationControllerkeywords will be applied to all text fields. The remaining non-text fields can be defined to restrict the query (in the example, we want restrict it to published Articles) and ordering (in the example, we ordered by updated_at). If you don’t define an ordering, the results will be returned sorted by relevance based on occurence and location of the keywords in the document and the index as a whole. You can tweak the relevance score by defining boosts — in this example, Article titles that match the keywords are given a boost over other Articles that may match the keyword elsewhere.
@search = search(params)
order_by :updated_at, :desc
paginate :page => options[:page]
<%= will_paginate @search.results %>