Module: ElasticSearchable::Queries

Defined in:
lib/elastic_searchable/queries.rb

Constant Summary collapse

PER_PAGE_DEFAULT =
20
MAX_RETRIES =
5

Instance Method Summary collapse

Instance Method Details

#per_pageObject



6
7
8
# File 'lib/elastic_searchable/queries.rb', line 6

def per_page
  PER_PAGE_DEFAULT
end

#search(query, options = {}) ⇒ Object

search returns a will_paginate collection of ActiveRecord objects for the search results supported options: :page - page of results to search for :per_page - number of results per page

www.elasticsearch.com/docs/elasticsearch/rest_api/search/



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/elastic_searchable/queries.rb', line 16

def search(query, options = {})
  page = (options.delete(:page) || 1).to_i
  size = (options[:size] ||= per_page_for_search(options))
  options[:fields] ||= '_id'
  options[:from] ||= options[:size] * (page - 1)
  if query.is_a?(Hash)
    options[:query] = query
  else
    options[:query] = {
      :query_string => {
        :query => query,
        :default_operator => options.delete(:default_operator)
      }
    }
  end
  query = {}
  case sort = options.delete(:sort)
  when Array,Hash
    options[:sort] = sort
  when String
    query[:sort] = sort
  end

  ids_to_delete = []
  results = []
  ids = []
  hits_total = nil
  retries = MAX_RETRIES

  loop do
    response = ElasticSearchable.request :get, index_type_path('_search'), :query => query, :json_body => options
    hits = response['hits']
    hits_total ||= hits['total'].to_i
    new_ids = collect_hit_ids(hits)
    new_results = collect_result_records(new_ids, hits)
    ids += new_ids
    results += new_results

    break if results.size >= ids.size || retries <= 0

    retries -= 1

    options[:from] = options[:from] + options[:size]
    options[:size] = ids.size - results.size

    ids_to_delete += (new_ids - new_results.map(&:id))
    ids -= ids_to_delete
  end

  ids_to_delete.each do |id|
    delete_id_from_index_backgrounded id
  end

  ElasticSearchable::Paginator.handler.new(results, page, size, hits_total - ids_to_delete.size)
end