Module: ElasticSearchable::Queries

Defined in:
lib/elastic_searchable/queries.rb

Constant Summary collapse

PER_PAGE_DEFAULT =
20

Instance Method Summary collapse

Instance Method Details

#per_pageObject



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

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/



15
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
# File 'lib/elastic_searchable/queries.rb', line 15

def search(query, options = {})
  page = (options.delete(:page) || 1).to_i
  options[:fields] ||= '_id'
  options[:size] ||= per_page_for_search(options)
  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

  response = ElasticSearchable.request :get, index_type_path('_search'), :query => query, :json_body => options
  hits = response['hits']
  ids = hits['hits'].collect {|h| h['_id'].to_i }
  results = self.find(ids).sort_by {|result| ids.index(result.id) }

  results.each do |result|
    result.instance_variable_set '@hit', hits['hits'][ids.index(result.id)]
  end

  ElasticSearchable::Paginator.handler.new(results, page, options[:size], hits['total'])
end