Skip to content

Instantly share code, notes, and snippets.

@itchy
Created December 4, 2012 17:19
Show Gist options
  • Save itchy/4206438 to your computer and use it in GitHub Desktop.
Save itchy/4206438 to your computer and use it in GitHub Desktop.
Best 2012 (a)
class SiteSearch
extend LocalTire::ActiveModel::Extensions
per_page 10
search_indexes :profiles, :groups, :blog_posts, :questions, :chats
def self.search(params)
current_page = get_page(params[:page])
query_string = params[:query] if params.member?(:query)
search_indexes params[:scope] if params.member?(:scope) && params[:scope] != 'all'
results = perform_query(query_string, current_page).results
# SSJ This is what I like
results.extend Tire::Results::Pagination
rescue Errno::ECONNREFUSED => e
Rails.logger.error "[Tire::Search::Search] Unable to connect to ElasticSearch database!"
puts e
generate_mock_results
rescue Exception => e
Rails.logger.error e
puts e
generate_mock_results
end
private
def self.perform_query(query_string, current_page)
Tire.search get_search_indexes do
if query_string
query do
string query_string,
:default_operator => "AND",
:fields => [:screen_name, :search_content, :description, :title, :tags, :comments, :question, :answers, :topics, :posts]
end
end
# SSJ Use filters for requirments that don't affect the relevance score
filter :bool, :must_not => { :term => {:private, true}}
filter :bool, :must_not => { :term => {:company, true}}
from (current_page-1) * (SiteSearch::get_per_page)
size SiteSearch::get_per_page
end
end
end
@itchy
Copy link
Author

itchy commented Dec 4, 2012

What I like about this code is that it demonstrates a transition in my thinking from brute force, to explore first. Tire has two search paradigms, search a single ActiveRecord model or do a generic (non-rails) search. I wanted to create a multiple index search, but still provide some of the functionality Tire provides to ActiveModel searches. Looking in the gem source, I was able to locate to modules that had the functionality I was looking for and all I needed to do was extend those functions onto the full index result set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment