Sha256: dcc3b24a32041262f8838c5a7a284f827aecd28e3917dc9b987000a548ac756d

Contents?: true

Size: 1.19 KB

Versions: 2

Compression:

Stored size: 1.19 KB

Contents

class Searcher
  attr_reader :results

  def initialize options = {}
    @options = options

    @query = options[:query]
    @q = options[:q]

    @search_group = options[:search_group] || "pages,attachments"
    @type = options[:type]
    @comparator = options[:comparator] || "AND"
  end

  def self.search options = {}
    searcher = Searcher.new options
    searcher.search

    searcher
  end

  def search
    q = @query

    if @q
      q = @q
    else
      q = q.split(" ").collect{|x| "_all:" + x + "*"}.join(" #{@comparator} ")
    end

    if @type
      q = "(#{q}) AND type:#{@type}"
    end

    client = Page.__elasticsearch__.client
    query = client.search index: search_group, 
      size: 30,
      q: q

    @results = Hashie::Mash.new query['hits']
  end

  def results_with_hits 
    grouped_results = {}

    hits = @results.hits
    hits.group_by(&:_type).each do |type, values|
      klass = type.classify.constantize
      ids = values.collect{|value| value._source.id }
      grouped_results[type] = klass.find(ids).group_by(&:id)
    end

    hits.each do |hit|
      yield grouped_results[hit._type][hit._source.id].first, hit
    end
  end

  def search_group
    @search_group
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
tawork-0.0.24 lib/searcher.rb
tawork-0.0.23 lib/searcher.rb