您的位置:首页 > 编程语言 > Ruby

Ruby on Rails 整合solr实现分面搜索

2012-01-06 16:57 316 查看


Ruby on Rails 整合solr实现分面搜索

分面搜索(Faceted Search): 分面是指事物的多维度属性。例如一本书包含主题、作者、年代等分面。而分面搜索是指通过事物的这些属性不断筛选、过滤搜索结果的方法。可以将分面搜索看成搜索和浏览的结合。最近做分面搜索,下面代码你懂的。。。
def s

require 'net/http'
require 'rexml/document'

# 定义url
@url = "http://localhost:8983/solr/select/?"
@keywords =  params[ :wd ]
@facet = params[ :facet ]
@facet_keywords = params[ :keys ]
@url_suffix = case
when @facet == 'brand' then "&fq=brand:#{@facet_keywords}"
when @facet == 'category' then "&fq=category:#{@facet_keywords}"
when @facet == 'price' then "&fq=price:#{@facet_keywords}"
else  ""
end
@fullurl = @url + "q=#{@keywords}&version=2.2&start=0&rows=20&indent=on&facet=true&facet.field=brand&facet.field=category&facet.field=price&facet.mincount=1#{@url_suffix}"
#render :text => @fullurl
logger.info @fullurl
#=begin
# 获取xml文档
Net::HTTP.start( 'localhost', 8983 ) do |http|
@response = http.get( @fullurl )
if @response.message == 'OK'
@doc = REXML::Document.new( @response.body )
@root = @doc.root
@products = @doc.get_elements( "response/result/doc" )
#@faceted = REXML::XPath.each( @doc, "//response//lst[@name='facet_fields']") { |e| logger.info e.name }
#logger.info @faceted
@doc = doc_to_hash( @response.body )
@facet = facet_to_hash( @response.body )

logger.info @xml
#render :text => @xml
#logger.info "{1,2,34,5,6,7s}"
#@root = @doc.root
#parse_recursive(@response.body)

render 'search'
else
render :text => 'solr server is error..'
end
end
#=end

end

private

def doc_to_hash( xml_data )
doc = REXML::Document.new( xml_data )
xml_to_hash = Hash.new
tmp = Hash.new
count_i = 0
hash_prefix = 'doc'
products = doc.get_elements( "response/result/doc" )
products.each do |product|
product.each_element { |e|
tmp[e.attributes['name']] = e.text
}
xml_to_hash[hash_prefix.to_s + count_i.to_s] = tmp
tmp = Hash.new
count_i = count_i + 1
end
return xml_to_hash
end

def facet_to_hash( xml_data )
doc = REXML::Document.new( xml_data )
xml_to_hash = Hash.new
tmp = Hash.new
tmp2 = Hash.new
count_i = 0
hash_prefix = 'facet'
products = doc.get_elements( "//response//lst[@name='facet_fields']" )
products.each do |product|
product.each_element { |e|
e.each_element { |f|
tmp2[f.attributes['name']] = f.text
}
tmp[e.attributes['name']] = tmp2
tmp2 = Hash.new
}
xml_to_hash[hash_prefix.to_s + count_i.to_s] = tmp
tmp = Hash.new
count_i = count_i + 1
end
return xml_to_hash['facet0']
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: