Class: Searchkick::Results

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/searchkick/results.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, response, options = {}) ⇒ Results

Returns a new instance of Results.



12
13
14
15
16
# File 'lib/searchkick/results.rb', line 12

def initialize(klass, response, options = {})
  @klass = klass
  @response = response
  @options = options
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



8
9
10
# File 'lib/searchkick/results.rb', line 8

def klass
  @klass
end

#optionsObject (readonly)

Returns the value of attribute options.



8
9
10
# File 'lib/searchkick/results.rb', line 8

def options
  @options
end

#responseObject (readonly)

Returns the value of attribute response.



8
9
10
# File 'lib/searchkick/results.rb', line 8

def response
  @response
end

Instance Method Details

#aggregationsObject



105
106
107
# File 'lib/searchkick/results.rb', line 105

def aggregations
  response["aggregations"]
end

#aggsObject



109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/searchkick/results.rb', line 109

def aggs
  @aggs ||= begin
    if aggregations
      aggregations.dup.each do |field, filtered_agg|
        buckets = filtered_agg[field]
        # move the buckets one level above into the field hash
        if buckets
          filtered_agg.delete(field)
          filtered_agg.merge!(buckets)
        end
      end
    end
  end
end

#clear_scrollObject



268
269
270
271
272
273
274
275
276
277
# File 'lib/searchkick/results.rb', line 268

def clear_scroll
  begin
    # try to clear scroll
    # not required as scroll will expire
    # but there is a cost to open scrolls
    Searchkick.client.clear_scroll(scroll_id: scroll_id)
  rescue Elasticsearch::Transport::Transport::Error
    # do nothing
  end
end

#current_pageObject



157
158
159
# File 'lib/searchkick/results.rb', line 157

def current_page
  options[:page]
end

#entry_name(options = {}) ⇒ Object



136
137
138
139
140
141
142
143
144
# File 'lib/searchkick/results.rb', line 136

def entry_name(options = {})
  if options.empty?
    # backward compatibility
    model_name.human.downcase
  else
    default = options[:count] == 1 ? model_name.human : model_name.human.pluralize
    model_name.human(options.reverse_merge(default: default))
  end
end

#errorObject



128
129
130
# File 'lib/searchkick/results.rb', line 128

def error
  response["error"]
end

#first_page?Boolean

Returns:

  • (Boolean)


189
190
191
# File 'lib/searchkick/results.rb', line 189

def first_page?
  previous_page.nil?
end

#highlights(multiple: false) ⇒ Object



209
210
211
212
213
# File 'lib/searchkick/results.rb', line 209

def highlights(multiple: false)
  hits.map do |hit|
    hit_highlights(hit, multiple: multiple)
  end
end

#hitsObject



201
202
203
204
205
206
207
# File 'lib/searchkick/results.rb', line 201

def hits
  if error
    raise Searchkick::Error, "Query error - use the error method to view it"
  else
    @response["hits"]["hits"]
  end
end

#last_page?Boolean

Returns:

  • (Boolean)


193
194
195
# File 'lib/searchkick/results.rb', line 193

def last_page?
  next_page.nil?
end

#misspellings?Boolean

Returns:

  • (Boolean)


230
231
232
# File 'lib/searchkick/results.rb', line 230

def misspellings?
  @options[:misspellings]
end

#model_nameObject



132
133
134
# File 'lib/searchkick/results.rb', line 132

def model_name
  klass.model_name
end

#next_pageObject



185
186
187
# File 'lib/searchkick/results.rb', line 185

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

#offset_valueObject Also known as: offset



175
176
177
# File 'lib/searchkick/results.rb', line 175

def offset_value
  (current_page - 1) * per_page + padding
end

#out_of_range?Boolean

Returns:

  • (Boolean)


197
198
199
# File 'lib/searchkick/results.rb', line 197

def out_of_range?
  current_page > total_pages
end

#paddingObject



166
167
168
# File 'lib/searchkick/results.rb', line 166

def padding
  options[:padding]
end

#per_pageObject Also known as: limit_value



161
162
163
# File 'lib/searchkick/results.rb', line 161

def per_page
  options[:per_page]
end

#previous_pageObject Also known as: prev_page



180
181
182
# File 'lib/searchkick/results.rb', line 180

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

#resultsObject



18
19
20
# File 'lib/searchkick/results.rb', line 18

def results
  @results ||= with_hit.map(&:first)
end

#scrollObject

Raises:



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/searchkick/results.rb', line 238

def scroll
  raise Searchkick::Error, "Pass `scroll` option to the search method for scrolling" unless scroll_id

  if block_given?
    records = self
    while records.any?
      yield records
      records = records.scroll
    end

    records.clear_scroll
  else
    params = {
      scroll: options[:scroll],
      scroll_id: scroll_id
    }

    begin
      # TODO Active Support notifications for this scroll call
      Searchkick::Results.new(@klass, Searchkick.client.scroll(params), @options)
    rescue Elasticsearch::Transport::Transport::Errors::NotFound => e
      if e.class.to_s =~ /NotFound/ && e.message =~ /search_context_missing_exception/i
        raise Searchkick::Error, "Scroll id has expired"
      else
        raise e
      end
    end
  end
end

#scroll_idObject



234
235
236
# File 'lib/searchkick/results.rb', line 234

def scroll_id
  @response["_scroll_id"]
end

#suggestionsObject



95
96
97
98
99
100
101
102
103
# File 'lib/searchkick/results.rb', line 95

def suggestions
  if response["suggest"]
    response["suggest"].values.flat_map { |v| v.first["options"] }.sort_by { |o| -o["score"] }.map { |o| o["text"] }.uniq
  elsif options[:suggest] || options[:term] == "*" # TODO remove 2nd term
    []
  else
    raise "Pass `suggest: true` to the search method for suggestions"
  end
end

#tookObject



124
125
126
# File 'lib/searchkick/results.rb', line 124

def took
  response["took"]
end

#total_countObject Also known as: total_entries



146
147
148
149
150
151
152
153
154
# File 'lib/searchkick/results.rb', line 146

def total_count
  if options[:total_entries]
    options[:total_entries]
  elsif response["hits"]["total"].is_a?(Hash)
    response["hits"]["total"]["value"]
  else
    response["hits"]["total"]
  end
end

#total_pagesObject Also known as: num_pages



170
171
172
# File 'lib/searchkick/results.rb', line 170

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

#with_highlights(multiple: false) ⇒ Object

TODO return enumerator like with_score



216
217
218
219
220
# File 'lib/searchkick/results.rb', line 216

def with_highlights(multiple: false)
  with_hit.map do |result, hit|
    [result, hit_highlights(hit, multiple: multiple)]
  end
end

#with_hitObject

TODO return enumerator like with_score



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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/searchkick/results.rb', line 23

def with_hit
  @with_hit ||= begin
    if options[:load]
      # results can have different types
      results = {}

      hits.group_by { |hit, _| hit["_index"] }.each do |index, grouped_hits|
        klasses =
          if @klass
            [@klass]
          else
            index_alias = index.split("_")[0..-2].join("_")
            Array((options[:index_mapping] || {})[index_alias])
          end
        raise Searchkick::Error, "Unknown model for index: #{index}" unless klasses.any?

        results[index] = {}
        klasses.each do |klass|
          results[index].merge!(results_query(klass, grouped_hits).to_a.index_by { |r| r.id.to_s })
        end
      end

      missing_ids = []

      # sort
      results =
        hits.map do |hit|
          result = results[hit["_index"]][hit["_id"].to_s]
          if result && !(options[:load].is_a?(Hash) && options[:load][:dumpable])
            if (hit["highlight"] || options[:highlight]) && !result.respond_to?(:search_highlights)
              highlights = hit_highlights(hit)
              result.define_singleton_method(:search_highlights) do
                highlights
              end
            end
          end
          [result, hit]
        end.select do |result, hit|
          missing_ids << hit["_id"] unless result
          result
        end

      if missing_ids.any?
        Searchkick.warn("Records in search index do not exist in database: #{missing_ids.join(", ")}")
      end

      results
    else
      hits.map do |hit|
        result =
          if hit["_source"]
            hit.except("_source").merge(hit["_source"])
          elsif hit["fields"]
            hit.except("fields").merge(hit["fields"])
          else
            hit
          end

        if hit["highlight"] || options[:highlight]
          highlight = Hash[hit["highlight"].to_a.map { |k, v| [base_field(k), v.first] }]
          options[:highlighted_fields].map { |k| base_field(k) }.each do |k|
            result["highlighted_#{k}"] ||= (highlight[k] || result[k])
          end
        end

        result["id"] ||= result["_id"] # needed for legacy reasons
        [HashWrapper.new(result), hit]
      end
    end
  end
end

#with_scoreObject



222
223
224
225
226
227
228
# File 'lib/searchkick/results.rb', line 222

def with_score
  return enum_for(:with_score) unless block_given?

  with_hit.each do |result, hit|
    yield result, hit["_score"]
  end
end