#278 Search with Sunspot
Sunspot makes it easy to do full text searching through Solr. Here I show how to search on various attributes and add facets for filtering the search further.
- Download:
- source codeProject Files in Zip (231 KB)
- mp4Full Size H.264 Video (21.6 MB)
- m4vSmaller H.264 Video (11.8 MB)
- webmFull Size VP8 Video (16.1 MB)
- ogvFull Size Theora Video (28.3 MB)
Resources
bash
bundle
rails g sunspot_rails:install
rake sunspot:solr:start
rake sunspot:reindex
bundle rails g sunspot_rails:install rake sunspot:solr:start rake sunspot:reindex
Gemfile
gem 'sunspot_rails'
gem 'sunspot_rails'
models/article.rb
searchable do
text :name, :boost => 5
text :content, :publish_month
text :comments do
comments.map(&:content)
end
time :published_at
string :publish_month
end
def publish_month
published_at.strftime("%B %Y")
end
searchable do text :name, :boost => 5 text :content, :publish_month text :comments do comments.map(&:content) end time :published_at string :publish_month end def publish_month published_at.strftime("%B %Y") end
articles_controller.rb
def index
@search = Article.search do
fulltext params[:search]
with(:published_at).less_than(Time.zone.now)
facet(:publish_month)
with(:publish_month, params[:month]) if params[:month].present?
end
@articles = @search.results
end
def index @search = Article.search do fulltext params[:search] with(:published_at).less_than(Time.zone.now) facet(:publish_month) with(:publish_month, params[:month]) if params[:month].present? end @articles = @search.results end
articles/index.html.erb
<%= form_tag articles_path, :method => :get do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<div id="facets">
<h3>Published</h3>
<ul>
<% for row in @search.facet(:publish_month).rows %>
<li>
<% if params[:month].blank? %>
<%= link_to row.value, :month => row.value %> (<%= row.count %>)
<% else %>
<strong><%= row.value %></strong> (<%= link_to "remove", :month => nil %>)
<% end %>
</li>
<% end %>
</ul>
</div>
<%= form_tag articles_path, :method => :get do %> <p> <%= text_field_tag :search, params[:search] %> <%= submit_tag "Search", :name => nil %> </p> <% end %> <div id="facets"> <h3>Published</h3> <ul> <% for row in @search.facet(:publish_month).rows %> <li> <% if params[:month].blank? %> <%= link_to row.value, :month => row.value %> (<%= row.count %>) <% else %> <strong><%= row.value %></strong> (<%= link_to "remove", :month => nil %>) <% end %> </li> <% end %> </ul> </div>

