class Tagliani::Search

Attributes

client[R]

Public Class Methods

client() click to toggle source
# File lib/tagliani/search.rb, line 9
def client
  Elasticsearch::Client.new host: Tagliani.config.elasticsearch.url,
                            log: Tagliani.config.elasticsearch.log
end
new(body:, where: nil) click to toggle source
# File lib/tagliani/search.rb, line 17
def initialize(body:, where: nil)
  @index = Tagliani.config.elasticsearch.index
  @client = self.class.client
  @where_clause = where
  @body = body

  build_where(@where_clause) if @where_clause
end

Public Instance Methods

response() click to toggle source
# File lib/tagliani/search.rb, line 26
def response
  @client.search(index: @index, body: @body)
end
serialize(type:) click to toggle source
# File lib/tagliani/search.rb, line 30
def serialize(type:)
  model_kls = "#{type}_kls"
  model_id = "#{type}_id"

  models = {}

  response['hits']['hits'].each do |entry|
    entry_source = entry['_source']
    class_name = entry_source[model_kls]
    models[class_name] ||= []
    models[class_name] << entry_source[model_id]
  end

  models.flat_map do |model, ids|
    model.constantize.where(id: ids)
  end
end

Private Instance Methods

build_query_string(args) click to toggle source
# File lib/tagliani/search.rb, line 62
def build_query_string(args)
  query = args.to_h.map do |key, val|
    "(#{val.map { |object| "#{key}:#{object}" }.join(' OR ')})"
  end.join(' AND ')
end
build_where(args) click to toggle source
# File lib/tagliani/search.rb, line 50
def build_where(args)
  @body[:query] ||= {}
  @body[:query][:bool] ||= {}
  @body[:query][:bool][:must] ||= []
  
  @body[:query][:bool][:must] << [
    query_string: {
      query: build_query_string(args)
    }
  ]
end