Created
December 30, 2011 18:19
-
-
Save robdimarco/1540892 to your computer and use it in GitHub Desktop.
Business class with custom search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Business < ActiveRecord | |
searchable do | |
text :name | |
text :location | |
end | |
def self.custom_search(query) | |
search do | |
adjust_solr_params do |p| | |
# We want to break out all of the terms | |
terms = query.split(/[^a-zA-Z0-9]+/) | |
q_terms=terms.map {|term| | |
"(" << %w(name_text location_text).map{ |f| | |
%Q[#{f}:#{term.downcase}~}] | |
}.join(" OR ") << ")" | |
}.join(" AND ") | |
p.merge!({:q=>q_terms, :sort=> "score desc", :fl=>"id score"}) | |
end | |
end | |
end | |
end | |
# Given data set | |
# ID Name Location | |
# 1 Boone Moving Service Raleigh, NC | |
# 2 Bone’s Moving New York, NY | |
# 3 Boone Moving Los Angeles, CA | |
# 4 Jimmy’s Movers Boone, NC | |
# | |
# this query will match records 1, 2, 3, 4 | |
# | |
# > Sunspot.index!(Business.all) | |
# > search = Business.custom_search("Boone Movers") | |
# > puts search.results.map(&:id) | |
#[4,3,1,2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment