Class: Elasticity::Search::Results

Inherits:
ActiveSupport::ProxyObject
  • Object
show all
Includes:
Enumerable
Defined in:
lib/elasticity/search.rb

Constant Summary collapse

DEFAULT_SIZE =
10

Instance Method Summary collapse

Constructor Details

#initialize(response, body, mapper = nil) ⇒ Results

Returns a new instance of Results.



301
302
303
304
305
306
307
308
309
# File 'lib/elasticity/search.rb', line 301

def initialize(response, body, mapper = nil)
  @response = response
  @body = body
  @documents = if mapper.nil?
    @response["hits"]["hits"]
  else
    @response["hits"]["hits"].map { |hit| mapper.(hit) }
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



311
312
313
# File 'lib/elasticity/search.rb', line 311

def method_missing(name, *args, &block)
  @documents.public_send(name, *args, &block)
end

Instance Method Details

#aggregationsObject



319
320
321
# File 'lib/elasticity/search.rb', line 319

def aggregations
  @response["aggregations"] ||= {}
end

#current_pageObject

for pagination



344
345
346
347
# File 'lib/elasticity/search.rb', line 344

def current_page
  return 1 if @body[:from].nil?
  @body[:from] / per_page + 1
end

#each(&block) ⇒ Object



315
316
317
# File 'lib/elasticity/search.rb', line 315

def each(&block)
  @documents.each(&block)
end

#next_pageObject



349
350
351
# File 'lib/elasticity/search.rb', line 349

def next_page
  current_page < total_pages ? (current_page + 1) : nil
end

#per_pageObject

for pagination



339
340
341
# File 'lib/elasticity/search.rb', line 339

def per_page
  @body[:size] || DEFAULT_SIZE
end

#previous_pageObject



353
354
355
# File 'lib/elasticity/search.rb', line 353

def previous_page
  current_page > 1 ? (current_page - 1) : nil
end

#totalObject Also known as: total_entries



323
324
325
326
327
328
329
330
# File 'lib/elasticity/search.rb', line 323

def total
  res = @response["hits"]["total"]
  if res.is_a?(::Hash)
    res["value"]
  else
    res
  end
end

#total_pagesObject

for pagination



334
335
336
# File 'lib/elasticity/search.rb', line 334

def total_pages
  (total.to_f / per_page.to_f).ceil
end