Class: Searchkick::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/searchkick/query.rb,
lib/searchkick/logging.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, term, options = {}) ⇒ Query

Returns a new instance of Query.



6
7
8
9
10
11
12
13
14
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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/searchkick/query.rb', line 6

def initialize(klass, term, options = {})
  if term.is_a?(Hash)
    options = term
    term = nil
  else
    term = term.to_s
  end

  @klass = klass
  @term = term
  @options = options

  boost_fields = {}
  fields =
    if options[:fields]
      if options[:autocomplete]
        options[:fields].map{|f| "#{f}.autocomplete" }
      else
        options[:fields].map do |value|
          k, v = value.is_a?(Hash) ? value.to_a.first : [value, :word]
          k2, boost = k.to_s.split("^", 2)
          field = "#{k2}.#{v == :word ? "analyzed" : v}"
          boost_fields[field] = boost.to_i if boost
          field
        end
      end
    else
      if options[:autocomplete]
        (searchkick_options[:autocomplete] || []).map{|f| "#{f}.autocomplete" }
      else
        ["_all"]
      end
    end

  operator = options[:operator] || (options[:partial] ? "or" : "and")

  # pagination
  page = [options[:page].to_i, 1].max
  per_page = (options[:limit] || options[:per_page] || 100000).to_i
  padding = [options[:padding].to_i, 0].max
  offset = options[:offset] || (page - 1) * per_page + padding

  conversions_field = searchkick_options[:conversions]
  personalize_field = searchkick_options[:personalize]

  all = term == "*"

  if options[:query]
    payload = options[:query]
  elsif options[:similar]
    payload = {
      more_like_this: {
        fields: fields,
        like_text: term,
        min_doc_freq: 1,
        min_term_freq: 1,
        analyzer: "searchkick_search2"
      }
    }
  elsif all
    payload = {
      match_all: {}
    }
  else
    if options[:autocomplete]
      payload = {
        multi_match: {
          fields: fields,
          query: term,
          analyzer: "searchkick_autocomplete_search"
        }
      }
    else
      queries = []
      fields.each do |field|
        factor = boost_fields[field] || 1
        shared_options = {
          fields: [field],
          query: term,
          use_dis_max: false,
          operator: operator,
          boost: factor
        }
        if field == "_all" or field.end_with?(".analyzed")
          shared_options[:cutoff_frequency] = 0.001 unless operator == "and"
          queries.concat [
            {multi_match: shared_options.merge(boost: 10 * factor, analyzer: "searchkick_search")},
            {multi_match: shared_options.merge(boost: 10 * factor, analyzer: "searchkick_search2")}
          ]
          if options[:misspellings] != false
            distance = (options[:misspellings].is_a?(Hash) && options[:misspellings][:distance]) || 1
            queries.concat [
              {multi_match: shared_options.merge(fuzziness: distance, max_expansions: 3, analyzer: "searchkick_search")},
              {multi_match: shared_options.merge(fuzziness: distance, max_expansions: 3, analyzer: "searchkick_search2")}
            ]
          end
        else
          analyzer = field.match(/\.word_(start|middle|end)\z/) ? "searchkick_word_search" : "searchkick_autocomplete_search"
          queries << {multi_match: shared_options.merge(analyzer: analyzer)}
        end
      end

      payload = {
        dis_max: {
          queries: queries
        }
      }
    end

    if conversions_field and options[:conversions] != false
      # wrap payload in a bool query
      payload = {
        bool: {
          must: payload,
          should: {
            nested: {
              path: conversions_field,
              score_mode: "total",
              query: {
                function_score: {
                  boost_mode: "replace",
                  query: {
                    match: {
                      query: term
                    }
                  },
                  script_score: {
                    script: "doc['count'].value"
                  }
                }
              }
            }
          }
        }
      }
    end
  end

  custom_filters = []

  boost_by = options[:boost_by] || {}
  if boost_by.is_a?(Array)
    boost_by = Hash[ boost_by.map{|f| [f, {factor: 1}] } ]
  end
  if options[:boost]
    boost_by[options[:boost]] = {factor: 1}
  end

  boost_by.each do |field, value|
    custom_filters << {
      filter: {
        exists: {
          field: field
        }
      },
      script_score: {
        script: "#{value[:factor].to_f} * log(doc['#{field}'].value + 2.718281828)"
      }
    }
  end

  boost_where = options[:boost_where] || {}
  if options[:user_id] and personalize_field
    boost_where[personalize_field] = options[:user_id]
  end
  if options[:personalize]
    boost_where.merge!(options[:personalize])
  end
  boost_where.each do |field, value|
    if value.is_a?(Hash)
      value, factor = value[:value], value[:factor]
    else
      factor = 1000
    end
    custom_filters << {
      filter: {
        term: {field => value}
      },
      boost_factor: factor
    }
  end

  if custom_filters.any?
    payload = {
      function_score: {
        functions: custom_filters,
        query: payload,
        score_mode: "sum"
      }
    }
  end

  payload = {
    query: payload,
    size: per_page,
    from: offset
  }
  payload[:explain] = options[:explain] if options[:explain]

  # order
  if options[:order]
    order = options[:order].is_a?(Enumerable) ? options[:order] : {options[:order] => :asc}
    payload[:sort] = Hash[ order.map{|k, v| [k.to_s == "id" ? :_id : k, v] } ]
  end

  # filters
  filters = where_filters(options[:where])
  if filters.any?
    payload[:filter] = {
      and: filters
    }
  end

  # facets
  facet_limits = {}
  if options[:facets]
    facets = options[:facets] || {}
    if facets.is_a?(Array) # convert to more advanced syntax
      facets = Hash[ facets.map{|f| [f, {}] } ]
    end

    payload[:facets] = {}
    facets.each do |field, facet_options|
      # ask for extra facets due to
      # https://github.com/elasticsearch/elasticsearch/issues/1305
      size = facet_options[:limit] ? facet_options[:limit] + 150 : 100000

      if facet_options[:ranges]
        payload[:facets][field] = {
          range: {
            field.to_sym => facet_options[:ranges]
          }
        }
      elsif facet_options[:stats]
        payload[:facets][field] = {
          terms_stats: {
            key_field: field,
            value_script: "doc.score",
            size: size
          }
        }
      else
        payload[:facets][field] = {
          terms: {
            field: field,
            size: size
          }
        }
      end

      facet_limits[field] = facet_options[:limit] if facet_options[:limit]

      # offset is not possible
      # http://elasticsearch-users.115913.n3.nabble.com/Is-pagination-possible-in-termsStatsFacet-td3422943.html

      facet_options.deep_merge!(where: options[:where].reject{|k| k == field}) if options[:smart_facets] == true
      facet_filters = where_filters(facet_options[:where])
      if facet_filters.any?
        payload[:facets][field][:facet_filter] = {
          and: {
            filters: facet_filters
          }
        }
      end
    end
  end

  # suggestions
  if options[:suggest]
    suggest_fields = (searchkick_options[:suggest] || []).map(&:to_s)

    # intersection
    if options[:fields]
      suggest_fields = suggest_fields & options[:fields].map{|v| (v.is_a?(Hash) ? v.keys.first : v).to_s }
    end

    if suggest_fields.any?
      payload[:suggest] = {text: term}
      suggest_fields.each do |field|
        payload[:suggest][field] = {
          phrase: {
            field: "#{field}.suggest"
          }
        }
      end
    end
  end

  # highlight
  if options[:highlight]
    payload[:highlight] = {
      fields: Hash[ fields.map{|f| [f, {}] } ]
    }
    if options[:highlight].is_a?(Hash) and tag = options[:highlight][:tag]
      payload[:highlight][:pre_tags] = [tag]
      payload[:highlight][:post_tags] = [tag.to_s.gsub(/\A</, "</")]
    end
  end

  # model and eagar loading
  load = options[:load].nil? ? true : options[:load]

  # An empty array will cause only the _id and _type for each hit to be returned
  # http://www.elasticsearch.org/guide/reference/api/search/fields/
  if load
    payload[:fields] = []
  elsif options[:select]
    payload[:fields] = options[:select]
  end

  if options[:type] or klass != searchkick_klass
    @type = [options[:type] || klass].flatten.map{|v| searchkick_index.klass_document_type(v) }
  end

  @body = payload
  @facet_limits = facet_limits
  @page = page
  @per_page = per_page
  @padding = padding
  @load = load
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



4
5
6
# File 'lib/searchkick/query.rb', line 4

def body
  @body
end

#klassObject (readonly)

Returns the value of attribute klass.



3
4
5
# File 'lib/searchkick/query.rb', line 3

def klass
  @klass
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/searchkick/query.rb', line 3

def options
  @options
end

#termObject (readonly)

Returns the value of attribute term.



3
4
5
# File 'lib/searchkick/query.rb', line 3

def term
  @term
end

Instance Method Details

#executeObject



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/searchkick/query.rb', line 349

def execute
  begin
    response = Searchkick.client.search(params)
  rescue => e # TODO rescue type
    status_code = e.message[1..3].to_i
    if status_code == 404
      raise MissingIndexError, "Index missing - run #{searchkick_klass.name}.reindex"
    elsif status_code == 500 and (
        e.message.include?("IllegalArgumentException[minimumSimilarity >= 1]") or
        e.message.include?("No query registered for [multi_match]") or
        e.message.include?("[match] query does not support [cutoff_frequency]]") or
        e.message.include?("No query registered for [function_score]]")
      )

      raise UnsupportedVersionError, "This version of Searchkick requires Elasticsearch 0.90.4 or greater"
    elsif status_code == 400
      if e.message.include?("[multi_match] analyzer [searchkick_search] not found")
        raise InvalidQueryError, "Bad mapping - run #{searchkick_klass.name}.reindex"
      else
        raise InvalidQueryError, e.message
      end
    else
      raise e
    end
  end

  # apply facet limit in client due to
  # https://github.com/elasticsearch/elasticsearch/issues/1305
  @facet_limits.each do |field, limit|
    field = field.to_s
    facet = response["facets"][field]
    response["facets"][field]["terms"] = facet["terms"].first(limit)
    response["facets"][field]["other"] = facet["total"] - facet["terms"].sum{|term| term["count"] }
  end

  opts = {
    page: @page,
    per_page: @per_page,
    padding: @padding,
    load: @load,
    includes: options[:include] || options[:includes]
  }
  Searchkick::Results.new(searchkick_klass, response, opts)
end

#execute_with_instrumentationObject



5
6
7
8
9
10
11
12
13
# File 'lib/searchkick/logging.rb', line 5

def execute_with_instrumentation
  event = {
    name: "#{searchkick_klass.name} Search",
    query: params
  }
  ActiveSupport::Notifications.instrument("search.searchkick", event) do
    execute_without_instrumentation
  end
end

#paramsObject



340
341
342
343
344
345
346
347
# File 'lib/searchkick/query.rb', line 340

def params
  params = {
    index: options[:index_name] || searchkick_index.name,
    body: body
  }
  params.merge!(type: @type) if @type
  params
end

#searchkick_indexObject



328
329
330
# File 'lib/searchkick/query.rb', line 328

def searchkick_index
  klass.searchkick_index
end

#searchkick_klassObject



336
337
338
# File 'lib/searchkick/query.rb', line 336

def searchkick_klass
  klass.searchkick_klass
end

#searchkick_optionsObject



332
333
334
# File 'lib/searchkick/query.rb', line 332

def searchkick_options
  klass.searchkick_options
end