#307 ElasticSearch Part 2 pro
This final part on ElasticSearch and Tire will show how to make more complex search queries, customize the indexing, and add facets.
- Download:
- source codeProject Files in Zip (84.1 KB)
- mp4Full Size H.264 Video (40.1 MB)
- m4vSmaller H.264 Video (19.9 MB)
- webmFull Size VP8 Video (23 MB)
- ogvFull Size Theora Video (50.6 MB)
Resources
bash
rake environment tire:import CLASS=Article FORCE=true
Gemfile
gem 'tire' gem 'will_paginate'
models/article.rb
include Tire::Model::Search include Tire::Model::Callbacks mapping do indexes :id, type: 'integer' indexes :author_id, type: 'integer' indexes :author_name indexes :name, boost: 10 indexes :content # analyzer: 'snowball' indexes :published_at, type: 'date' indexes :comments_count, type: 'integer' end def self.search(params) tire.search(page: params[:page], per_page: 2) do query do boolean do must { string params[:query], default_operator: "AND" } if params[:query].present? must { range :published_at, lte: Time.zone.now } must { term :author_id, params[:author_id] } if params[:author_id].present? end end sort { by :published_at, "desc" } if params[:query].blank? facet "authors" do terms :author_id end # raise to_curl end end # self.include_root_in_json = false (necessary before Rails 3.1) def to_indexed_json to_json(methods: [:author_name, :comments_count]) end def author_name author.name end def comments_count comments.size end
articles/index.html.erb
<%= form_tag articles_path, method: :get do %> <p> <%= text_field_tag :query, params[:query] %> <%= submit_tag "Search", name: nil %> </p> <% end %> <div id="facets"> <h3>Authors</h3> <ul> <% @articles.facets['authors']['terms'].each do |facet| %> <li> <%= link_to_unless_current Author.find(facet['term']).name, params.merge(author_id: facet['term']) %> <% if params[:author_id] == facet['term'].to_s %> (<%= link_to "remove", author_id: nil %>) <% else %> (<%= facet['count'] %>) <% end %> </li> <% end %> </ul> </div> <div id="articles"> <% @articles.each do |article| %> <h2> <%= link_to article.name, article %> <span class="comments">(<%= pluralize(article.comments_count, 'comment') %>)</span> </h2> <div class="info"> by <%= article.author_name %> on <%= article.published_at.to_time.strftime('%b %d, %Y') %> </div> <div class="content"><%= article.content %></div> <% end %> </div> <%= will_paginate @articles %>