现在的位置: 首页 > 综合 > 正文

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

2018年01月10日 ⁄ 综合 ⁄ 共 2075字 ⁄ 字号 评论关闭

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
【上篇】
【下篇】

抱歉!评论已关闭.