Software engineer, data guy, Open Source enthusiast, New Hampshire resident, husband, father. Fan of guitars, hiking, photography, homebrewing, sarcasm.
Setting up a Ruby on Rails project with faceted Solr search integration using Sunspot and acts-as-taggable-on
In this article I’ll show how to setup a Rails project with faceted solr searching integration. This code uses the following: sunspot gem for Solr integration, and acts-as-taggable-on for tagging and search facets.
RVM/Rails Setup
Add gems, file: Gemfile, added:
Installing gems
Create default scaffolding for a Post model
Add tags property to Post model. file: app/models/post.rb
Run acts-as-taggable-on migration
Setup/create database
Part 2, Random Data
The model is now setup to create Posts with a title, content, and array of tags. For demonstration purposes, I decided to create a rake task to populate the content attribute with lorem ipsum text, and the tags with random words from /usr/share/dict/words.
Modified the Post model to enable :tag_list as mass assignable. file: app/models/post.rb
Added lorem gem; file: Gemfile
Installed
Created a ruby rake script to create 20 Posts with 20 random tag words. file: lib/tasks/create_random_posts_and_tags.rake
Executed rake task to create posts
Part 3, Solr Sunspot
Generate default configuration
Add code to index Post data. In this code, I added “:stored => true” to each property to: 1. avoid querying Active Record on the search results page; and 2. to enable matches highlighting. file: app/models/post.rb
Setup Solr development server via Jetty
At this point, you should be able to browse and query the solr search results and verify the structure of the indexed data. Example URL: http://localhost:8982/solr/select/?q=*:*
Add a new Search controller
Revised search controller to be named route. file: config/routes.rb
Define the search controller method. I set the controller to pass 2 instance variables to the view: @search and @hits. @hits contains the stored values, allowing us to query solr directly, instead of Active Record. file: app/controllers/search_controller.rb
Define the search view. This code contains the following sections: search form, search results (@hits with matches highlighting), and facets generation. I set the facets as an array, to allow the user to select multiple. file: app/views/search/search.html.erb
Browsing to http://localhost:3000/search now shows the search form. I entered “lorem” to get the following result. Note the asterisks around keyword “lorem” in the results. The tag facets are shown below with their associated result count.
By clicking on two tags, the facet counts and associated results decrease. The facet links can also be unselected. Great.