Created
December 30, 2011 19:25
-
-
Save robdimarco/1541127 to your computer and use it in GitHub Desktop.
Business class with search method sorting correctly
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 ") | |
q_terms = %Q[ (#{q_terms}) OR (_query_:"{!prefix f=name_untokenized v=$qq}")^10] | |
p.merge!({:q=>q_terms, :qq=>query.downcase, :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 in the desired user | |
# | |
# > Sunspot.index!(Business.all) | |
# > search = Business.custom_search("Boone Moving") | |
# > puts search.results.map(&:id) | |
#[1,3,4,2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment