public
Description: Rails plugin for integration of the Sunspot Solr library
Homepage: http://github.com/outoftime/sunspot_rails
Clone URL: git://github.com/outoftime/sunspot_rails.git
README.rdoc

Sunspot::Rails

Sunspot::Rails is a Rails plugin that provides drop-in integration of the Sunspot Solr search library with Rails. It provides the following features:

  • Configure Sunspot using config/sunspot.yml
  • Extend ActiveRecord for easy index configuration, search, and indexing
  • Automatically index ActiveRecord objects when they are saved, and remove them from the index when they are destroyed (can be disabled)
  • Automatically commit Solr changes at the end of each request
  • Provide utility methods to find and fix orphaned documents and rebuild the Solr index for a given class
  • Provide rake tasks for starting and stopping the development Solr instance, using the configuration in sunspot.yml

Sunspot::Rails has been tested with Rails versions 2.1, 2.2, and 2.3

Installation

First, install the Sunspot and Sunspot::Rails gems:

  sudo gem install outoftime-sunspot outoftime-sunspot_rails --source=http://gems.github.com

In your project’s config/environment.rb, add the following gem dependencies:

  config.gem 'outoftime-sunspot_rails', :lib => 'sunspot/rails'

If you are using an older version of Rails that doesn’t support plugins-as-gems, use:

  script/plugin install git://github.com/outoftime/sunspot_rails.git

Create the file config/sunspot.yml and set it up for your environments. Here is a sample:

  common: &common
    solr:
      hostname: localhost
      port: 8983

  production:
    <<: *common

  development:
    <<: *common
    solr:
      port: 8982

  test:
    <<: *common
    solr:
      port: 8981

To start up a Solr instance, issue the following:

  rake sunspot:solr:start

Note that using the built-in Solr instance packaged with Sunspot is great for development, but is not recommended for production. See the Sunspot documentation for more information.

Usage

Setup

In order for an ActiveRecord model to be indexable and searchable, it must be configured for search. For example:

  class Post < ActiveRecord::Base
    searchable do
      text :title, :body
      integer :blog_id
      time :updated_at
      string :sort_title do
        title.downcase.sub(/^(an?|the) /, '')
      end
    end
  end

See the documentation for Sunspot.setup for full details on what can go in the configuration block.

Indexing

By default, models are indexed whenever they are saved, and removed from the index whenever they are destroyed. This behavior can be disabled:

  class Post < ActiveRecord::Base
    searchable :auto_index => false, :auto_remove => false do
      # setup...
    end
  end

Note that <strong>using the :auto_remove option is not recommended </strong>, as destroying an object without removing it from the index will create an orphaned document in the index, which is a Bad Thing. Turning off +:auto_index+ is perfectly safe if you prefer to manage indexing manually (perhaps using a background job).

If you have disabled lifecycle indexing hooks, you can invoke indexing operations directly on your model:

  post = Post.create
  post.index
  post.remove_from_index

Committing

When data is changed in Solr, it is initially stored in memory and not made available to the currently running searcher instance. Issuing a commit to Solr will cause it to write the changes to disk, and instantiate a new searcher instance. This operation is fairly expensive, so rather than issuing a commit every time a document is added or removed, Sunspot::Rails issues a commit at the end of any request where data has been added to or removed from Solr. If you need to immediately issue a commit, bang!-versions of the methods are available:

  post = Post.create
  post.index!
  # this is the same as...
  post.index
  Sunspot.commit

When writing tests outside of the context of a controller request, you will want to use one of these two approaches.

Searching

Do it like this:

  Post.search do
    with :blog_id, 1
    with(:updated_at).greater_than(Time.now - 2.weeks)
    order :sort_title, :asc
    paginate :page => 1, :per_page => 15
  end

See the documentation for Sunspot.search for all the options available in the search block, and the information available in the result block.

Searching for IDs

In some situations, you may want to get the IDs for models returned by a search without actually loading the models out of the database. For that, you can call search_ids, using the same block format as #search. This will return an array of IDs.

Searching for multiple types

Sunspot is entirely agnostic about whether searches are for one or more types; the only restriction is that columns used for restriction, ordering, etc. are defined in the same way for all types being searched. Sunspot::Rails does not provide any additional support for this, since there is not anything useful to be added, so just use the interface provided by Sunspot:

  Sunspot.search(Post, Comment) do
    with :blog_id, 1
    order :created_at, :asc
  end

Be sure to check out the Sunspot documentation for all the details.

Adding search functionality in mixins

Sunspot does not require that search setup for a given class happen all in one place; it is perfectly acceptable to call the +Sunspot.setup+ method more than once. This capability is particularly useful for adding search functionality in mixins. For instance, if you have a Ratable module, you may wish to add additional search fields for searchable classes that mix in that module. For example:

  module Ratable
    def self.included(base)
      if base.searchable?
        base.searchable do
          float :average_rating do
            ratings.average(:value)
          end
        end
      end
    end
  end

Note the use of base.searchable? - this ensures that only classes that already have search enabled will have the additional configuration added. The above pattern requires that the class be declared searchable before the module is mixed in; other patterns (such as passing a :searchable option to an acts_as_-style declaration) may be more flexible.

Utility methods

If you need to completely reindex all of the instances of a given model class, you can issue:

  Post.reindex

If for some reason models get deleted from the database, but not from the index, they will become index orphans - not a good situation. To get IDs that exist in the index but not the database, you can use the index_orphans method; to remove those documents from the index, use clean_index_orphans. Note that neither of these operations should be needed if Sunspot and Sunspot::Rails are used as intended.

Further Reading

Reading the documentation for Sunspot is highly recommended. Sunspot::Rails exists to wrap Sunspot with a Rails-friendly API, but almost all of the functionality you use in Sunspot::Rails is implemented in Sunspot.

Posts about Sunspot on my blog are available at outofti.me/tagged/sunspot

Bugs

Please submit bug reports to outoftime.lighthouseapp.com/projects/20339-sunspot

Contributors

Mat Brown <mat@patch.com>

MIT License

Copyright © 2009 Mat Brown

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.