Class: Searchkick::Index

Inherits:
Object
  • Object
show all
Defined in:
lib/searchkick/index.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Index

Returns a new instance of Index


5
6
7
8
# File 'lib/searchkick/index.rb', line 5

def initialize(name, options = {})
  @name = name
  @options = options
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name


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

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options


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

def options
  @options
end

Instance Method Details

#alias_exists?Boolean

Returns:

  • (Boolean)

26
27
28
# File 'lib/searchkick/index.rb', line 26

def alias_exists?
  client.indices.exists_alias name: name
end

#all_indices(options = {}) ⇒ Object


143
144
145
146
147
148
149
150
151
152
# File 'lib/searchkick/index.rb', line 143

def all_indices(options = {})
  indices =
    begin
      client.indices.get_aliases
    rescue Elasticsearch::Transport::Transport::Errors::NotFound
      {}
    end
  indices = indices.select { |_k, v| v.empty? || v["aliases"].empty? } if options[:unaliased]
  indices.select { |k, _v| k =~ /\A#{Regexp.escape(name)}_\d{14,17}\z/ }.keys
end

#bulk_delete(records) ⇒ Object


55
56
57
# File 'lib/searchkick/index.rb', line 55

def bulk_delete(records)
  Searchkick.queue_items(records.reject { |r| r.id.blank? }.map { |r| {delete: record_data(r)} })
end

#bulk_index(records) ⇒ Object Also known as: import


59
60
61
# File 'lib/searchkick/index.rb', line 59

def bulk_index(records)
  Searchkick.queue_items(records.map { |r| {index: record_data(r).merge(data: search_data(r))} })
end

#clean_indicesObject

remove old indices that start w/ index_name


155
156
157
158
159
160
161
# File 'lib/searchkick/index.rb', line 155

def clean_indices
  indices = all_indices(unaliased: true)
  indices.each do |index|
    Searchkick::Index.new(index).delete
  end
  indices
end

#create(options = {}) ⇒ Object


10
11
12
# File 'lib/searchkick/index.rb', line 10

def create(options = {})
  client.indices.create index: name, body: options
end

#create_index(options = {}) ⇒ Object

reindex


136
137
138
139
140
141
# File 'lib/searchkick/index.rb', line 136

def create_index(options = {})
  index_options = options[:index_options] || self.index_options
  index = Searchkick::Index.new("#{name}_#{Time.now.strftime('%Y%m%d%H%M%S%L')}", @options)
  index.create(index_options)
  index
end

#deleteObject


14
15
16
# File 'lib/searchkick/index.rb', line 14

def delete
  client.indices.delete index: name
end

#exists?Boolean

Returns:

  • (Boolean)

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

def exists?
  client.indices.exists index: name
end

#import_scope(scope, options = {}) ⇒ Object


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
# File 'lib/searchkick/index.rb', line 214

def import_scope(scope, options = {})
  batch_size = @options[:batch_size] || 1000

  # use scope for import
  scope = scope.search_import if scope.respond_to?(:search_import)
  if scope.respond_to?(:find_in_batches)
    if options[:resume]
      # use total docs instead of max id since there's not a great way
      # to get the max _id without scripting since it's a string

      # TODO use primary key and prefix with table name
      scope = scope.where("id > ?", total_docs)
    end

    scope.find_in_batches batch_size: batch_size do |batch|
      import batch.select(&:should_index?)
    end
  else
    # https://github.com/karmi/tire/blob/master/lib/tire/model/import.rb
    # use cursor for Mongoid
    items = []
    # TODO add resume
    scope.all.each do |item|
      items << item if item.should_index?
      if items.length == batch_size
        import items
        items = []
      end
    end
    import items
  end
end

#index_optionsObject


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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/searchkick/index.rb', line 247

def index_options
  options = @options
  language = options[:language]
  language = language.call if language.respond_to?(:call)

  if options[:mappings] && !options[:merge_mappings]
    settings = options[:settings] || {}
    mappings = options[:mappings]
  else
    below22 = Searchkick.server_below?("2.2.0")
    below50 = Searchkick.server_below?("5.0.0-alpha1")
    default_type = below50 ? "string" : "text"
    default_analyzer = below50 ? :default_index : :default
    keyword_mapping =
      if below50
        {
          type: default_type,
          index: "not_analyzed"
        }
      else
        {
          type: "keyword"
        }
      end

    keyword_mapping[:ignore_above] = 256 unless below22

    settings = {
      analysis: {
        analyzer: {
          searchkick_keyword: {
            type: "custom",
            tokenizer: "keyword",
            filter: ["lowercase"] + (options[:stem_conversions] == false ? [] : ["searchkick_stemmer"])
          },
          default_analyzer => {
            type: "custom",
            # character filters -> tokenizer -> token filters
            # https://www.elastic.co/guide/en/elasticsearch/guide/current/analysis-intro.html
            char_filter: ["ampersand"],
            tokenizer: "standard",
            # synonym should come last, after stemming and shingle
            # shingle must come before searchkick_stemmer
            filter: ["standard", "lowercase", "asciifolding", "searchkick_index_shingle", "searchkick_stemmer"]
          },
          searchkick_search: {
            type: "custom",
            char_filter: ["ampersand"],
            tokenizer: "standard",
            filter: ["standard", "lowercase", "asciifolding", "searchkick_search_shingle", "searchkick_stemmer"]
          },
          searchkick_search2: {
            type: "custom",
            char_filter: ["ampersand"],
            tokenizer: "standard",
            filter: ["standard", "lowercase", "asciifolding", "searchkick_stemmer"]
          },
          # https://github.com/leschenko/elasticsearch_autocomplete/blob/master/lib/elasticsearch_autocomplete/analyzers.rb
          searchkick_autocomplete_index: {
            type: "custom",
            tokenizer: "searchkick_autocomplete_ngram",
            filter: ["lowercase", "asciifolding"]
          },
          searchkick_autocomplete_search: {
            type: "custom",
            tokenizer: "keyword",
            filter: ["lowercase", "asciifolding"]
          },
          searchkick_word_search: {
            type: "custom",
            tokenizer: "standard",
            filter: ["lowercase", "asciifolding"]
          },
          searchkick_suggest_index: {
            type: "custom",
            tokenizer: "standard",
            filter: ["lowercase", "asciifolding", "searchkick_suggest_shingle"]
          },
          searchkick_text_start_index: {
            type: "custom",
            tokenizer: "keyword",
            filter: ["lowercase", "asciifolding", "searchkick_edge_ngram"]
          },
          searchkick_text_middle_index: {
            type: "custom",
            tokenizer: "keyword",
            filter: ["lowercase", "asciifolding", "searchkick_ngram"]
          },
          searchkick_text_end_index: {
            type: "custom",
            tokenizer: "keyword",
            filter: ["lowercase", "asciifolding", "reverse", "searchkick_edge_ngram", "reverse"]
          },
          searchkick_word_start_index: {
            type: "custom",
            tokenizer: "standard",
            filter: ["lowercase", "asciifolding", "searchkick_edge_ngram"]
          },
          searchkick_word_middle_index: {
            type: "custom",
            tokenizer: "standard",
            filter: ["lowercase", "asciifolding", "searchkick_ngram"]
          },
          searchkick_word_end_index: {
            type: "custom",
            tokenizer: "standard",
            filter: ["lowercase", "asciifolding", "reverse", "searchkick_edge_ngram", "reverse"]
          }
        },
        filter: {
          searchkick_index_shingle: {
            type: "shingle",
            token_separator: ""
          },
          # lucky find http://web.archiveorange.com/archive/v/AAfXfQ17f57FcRINsof7
          searchkick_search_shingle: {
            type: "shingle",
            token_separator: "",
            output_unigrams: false,
            output_unigrams_if_no_shingles: true
          },
          searchkick_suggest_shingle: {
            type: "shingle",
            max_shingle_size: 5
          },
          searchkick_edge_ngram: {
            type: "edgeNGram",
            min_gram: 1,
            max_gram: 50
          },
          searchkick_ngram: {
            type: "nGram",
            min_gram: 1,
            max_gram: 50
          },
          searchkick_stemmer: {
            # use stemmer if language is lowercase, snowball otherwise
            # TODO deprecate language option in favor of stemmer
            type: language == language.to_s.downcase ? "stemmer" : "snowball",
            language: language || "English"
          }
        },
        char_filter: {
          # https://www.elastic.co/guide/en/elasticsearch/guide/current/custom-analyzers.html
          # &_to_and
          ampersand: {
            type: "mapping",
            mappings: ["&=> and "]
          }
        },
        tokenizer: {
          searchkick_autocomplete_ngram: {
            type: "edgeNGram",
            min_gram: 1,
            max_gram: 50
          }
        }
      }
    }

    if Searchkick.env == "test"
      settings[:number_of_shards] = 1
      settings[:number_of_replicas] = 0
    end

    if options[:similarity]
      settings[:similarity] = {default: {type: options[:similarity]}}
    end

    settings.deep_merge!(options[:settings] || {})

    # synonyms
    synonyms = options[:synonyms] || []

    synonyms = synonyms.call if synonyms.respond_to?(:call)

    if synonyms.any?
      settings[:analysis][:filter][:searchkick_synonym] = {
        type: "synonym",
        synonyms: synonyms.select { |s| s.size > 1 }.map { |s| s.join(",") }
      }
      # choosing a place for the synonym filter when stemming is not easy
      # https://groups.google.com/forum/#!topic/elasticsearch/p7qcQlgHdB8
      # TODO use a snowball stemmer on synonyms when creating the token filter

      # http://elasticsearch-users.115913.n3.nabble.com/synonym-multi-words-search-td4030811.html
      # I find the following approach effective if you are doing multi-word synonyms (synonym phrases):
      # - Only apply the synonym expansion at index time
      # - Don't have the synonym filter applied search
      # - Use directional synonyms where appropriate. You want to make sure that you're not injecting terms that are too general.
      settings[:analysis][:analyzer][default_analyzer][:filter].insert(4, "searchkick_synonym")
      settings[:analysis][:analyzer][default_analyzer][:filter] << "searchkick_synonym"

      %w(word_start word_middle word_end).each do |type|
        settings[:analysis][:analyzer]["searchkick_#{type}_index".to_sym][:filter].insert(2, "searchkick_synonym")
      end
    end

    if options[:wordnet]
      settings[:analysis][:filter][:searchkick_wordnet] = {
        type: "synonym",
        format: "wordnet",
        synonyms_path: Searchkick.wordnet_path
      }

      settings[:analysis][:analyzer][default_analyzer][:filter].insert(4, "searchkick_wordnet")
      settings[:analysis][:analyzer][default_analyzer][:filter] << "searchkick_wordnet"

      %w(word_start word_middle word_end).each do |type|
        settings[:analysis][:analyzer]["searchkick_#{type}_index".to_sym][:filter].insert(2, "searchkick_wordnet")
      end
    end

    if options[:special_characters] == false
      settings[:analysis][:analyzer].each do |_, analyzer_settings|
        analyzer_settings[:filter].reject! { |f| f == "asciifolding" }
      end
    end

    mapping = {}

    # conversions
    Array(options[:conversions]).each do |conversions_field|
      mapping[conversions_field] = {
        type: "nested",
        properties: {
          query: {type: default_type, analyzer: "searchkick_keyword"},
          count: {type: "integer"}
        }
      }
    end

    mapping_options = Hash[
      [:autocomplete, :suggest, :word, :text_start, :text_middle, :text_end, :word_start, :word_middle, :word_end, :highlight, :searchable, :filterable, :only_analyzed]
        .map { |type| [type, (options[type] || []).map(&:to_s)] }
    ]

    word = options[:word] != false && (!options[:match] || options[:match] == :word)

    mapping_options.values.flatten.uniq.each do |field|
      fields = {}

      if mapping_options[:only_analyzed].include?(field) || (options.key?(:filterable) && !mapping_options[:filterable].include?(field))
        fields[field] = {type: default_type, index: "no"}
      else
        fields[field] = keyword_mapping
      end

      if !options[:searchable] || mapping_options[:searchable].include?(field)
        if word
          fields["analyzed"] = {type: default_type, index: "analyzed", analyzer: default_analyzer}

          if mapping_options[:highlight].include?(field)
            fields["analyzed"][:term_vector] = "with_positions_offsets"
          end
        end

        mapping_options.except(:highlight, :searchable, :filterable, :only_analyzed, :word).each do |type, f|
          if options[:match] == type || f.include?(field)
            fields[type] = {type: default_type, index: "analyzed", analyzer: "searchkick_#{type}_index"}
          end
        end
      end

      mapping[field] =
        if below50
          {
            type: "multi_field",
            fields: fields
          }
        elsif fields[field]
          fields[field].merge(fields: fields.except(field))
        end
    end

    (options[:locations] || []).map(&:to_s).each do |field|
      mapping[field] = {
        type: "geo_point"
      }
    end

    (options[:unsearchable] || []).map(&:to_s).each do |field|
      mapping[field] = {
        type: default_type,
        index: "no"
      }
    end

    routing = {}
    if options[:routing]
      routing = {required: true}
      unless options[:routing] == true
        routing[:path] = options[:routing].to_s
      end
    end

    dynamic_fields = {
      # analyzed field must be the default field for include_in_all
      # http://www.elasticsearch.org/guide/reference/mapping/multi-field-type/
      # however, we can include the not_analyzed field in _all
      # and the _all index analyzer will take care of it
      "{name}" => keyword_mapping.merge(include_in_all: !options[:searchable])
    }

    if options.key?(:filterable)
      dynamic_fields["{name}"] = {type: default_type, index: "no"}
    end

    dynamic_fields["{name}"][:ignore_above] = 256 unless below22

    unless options[:searchable]
      if options[:match] && options[:match] != :word
        dynamic_fields[options[:match]] = {type: default_type, index: "analyzed", analyzer: "searchkick_#{options[:match]}_index"}
      end

      if word
        dynamic_fields["analyzed"] = {type: default_type, index: "analyzed"}
      end
    end

    # http://www.elasticsearch.org/guide/reference/mapping/multi-field-type/
    multi_field =
      if below50
        {
          type: "multi_field",
          fields: dynamic_fields
        }
      else
        dynamic_fields["{name}"].merge(fields: dynamic_fields.except("{name}"))
      end

    mappings = {
      _default_: {
        _all: {type: default_type, index: "analyzed", analyzer: default_analyzer},
        properties: mapping,
        _routing: routing,
        # https://gist.github.com/kimchy/2898285
        dynamic_templates: [
          {
            string_template: {
              match: "*",
              match_mapping_type: "string",
              mapping: multi_field
            }
          }
        ]
      }
    }.deep_merge(options[:mappings] || {})
  end

  {
    settings: settings,
    mappings: mappings
  }
end

#klass_document_type(klass) ⇒ Object


609
610
611
612
613
614
615
# File 'lib/searchkick/index.rb', line 609

def klass_document_type(klass)
  if klass.respond_to?(:document_type)
    klass.document_type
  else
    klass.model_name.to_s.underscore
  end
end

#mappingObject


30
31
32
# File 'lib/searchkick/index.rb', line 30

def mapping
  client.indices.get_mapping index: name
end

#record_data(r) ⇒ Object


64
65
66
67
68
69
70
71
72
# File 'lib/searchkick/index.rb', line 64

def record_data(r)
  data = {
    _index: name,
    _id: search_id(r),
    _type: document_type(r)
  }
  data[:_routing] = r.search_routing if r.respond_to?(:search_routing)
  data
end

#refreshObject


22
23
24
# File 'lib/searchkick/index.rb', line 22

def refresh
  client.indices.refresh index: name
end

#reindex_record(record) ⇒ Object


82
83
84
85
86
87
88
89
90
91
92
# File 'lib/searchkick/index.rb', line 82

def reindex_record(record)
  if record.destroyed? || !record.should_index?
    begin
      remove(record)
    rescue Elasticsearch::Transport::Transport::Errors::NotFound
      # do nothing
    end
  else
    store(record)
  end
end

#reindex_record_async(record) ⇒ Object


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

def reindex_record_async(record)
  if Searchkick.callbacks_value.nil?
    if defined?(Searchkick::ReindexV2Job)
      Searchkick::ReindexV2Job.perform_later(record.class.name, record.id.to_s)
    else
      Delayed::Job.enqueue Searchkick::ReindexJob.new(record.class.name, record.id.to_s)
    end
  else
    reindex_record(record)
  end
end

#reindex_scope(scope, options = {}) ⇒ Object


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
# File 'lib/searchkick/index.rb', line 179

def reindex_scope(scope, options = {})
  skip_import = options[:import] == false
  resume = options[:resume]

  if resume
    index_name = all_indices.sort.last
    raise Searchkick::Error, "No index to resume" unless index_name
    index = Searchkick::Index.new(index_name)
  else
    clean_indices

    index = create_index(index_options: scope.searchkick_index_options)
  end

  # check if alias exists
  if alias_exists?
    # import before swap
    index.import_scope(scope, resume: resume) unless skip_import

    # get existing indices to remove
    swap(index.name)
    clean_indices
  else
    delete if exists?
    swap(index.name)

    # import after swap
    index.import_scope(scope, resume: resume) unless skip_import
  end

  index.refresh

  true
end

#remove(record) ⇒ Object


51
52
53
# File 'lib/searchkick/index.rb', line 51

def remove(record)
  bulk_delete([record])
end

#retrieve(record) ⇒ Object


74
75
76
77
78
79
80
# File 'lib/searchkick/index.rb', line 74

def retrieve(record)
  client.get(
    index: name,
    type: document_type(record),
    id: search_id(record)
  )["_source"]
end

#search_model(searchkick_klass, term = nil, options = {}) {|query.body| ... } ⇒ Object

search

Yields:

  • (query.body)

124
125
126
127
128
129
130
131
132
# File 'lib/searchkick/index.rb', line 124

def search_model(searchkick_klass, term = nil, options = {}, &block)
  query = Searchkick::Query.new(searchkick_klass, term, options)
  yield(query.body) if block
  if options[:execute] == false
    query
  else
    query.execute
  end
end

#similar_record(record, options = {}) ⇒ Object


106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/searchkick/index.rb', line 106

def similar_record(record, options = {})
  like_text = retrieve(record).to_hash
    .keep_if { |k, _| !options[:fields] || options[:fields].map(&:to_s).include?(k) }
    .values.compact.join(" ")

  # TODO deep merge method
  options[:where] ||= {}
  options[:where][:_id] ||= {}
  options[:where][:_id][:not] = record.id.to_s
  options[:per_page] ||= 10
  options[:similar] = true

  # TODO use index class instead of record class
  search_model(record.class, like_text, options)
end

#store(record) ⇒ Object

record based


47
48
49
# File 'lib/searchkick/index.rb', line 47

def store(record)
  bulk_index([record])
end

#swap(new_name) ⇒ Object


34
35
36
37
38
39
40
41
42
43
# File 'lib/searchkick/index.rb', line 34

def swap(new_name)
  old_indices =
    begin
      client.indices.get_alias(name: name).keys
    rescue Elasticsearch::Transport::Transport::Errors::NotFound
      {}
    end
  actions = old_indices.map { |old_name| {remove: {index: old_name, alias: name}} } + [{add: {index: new_name, alias: name}}]
  client.indices.update_aliases body: {actions: actions}
end

#tokens(text, options = {}) ⇒ Object

other


605
606
607
# File 'lib/searchkick/index.rb', line 605

def tokens(text, options = {})
  client.indices.analyze({text: text, index: name}.merge(options))["tokens"].map { |t| t["token"] }
end

#total_docsObject


163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/searchkick/index.rb', line 163

def total_docs
  response =
    client.search(
      index: name,
      body: {
        fields: [],
        query: {match_all: {}},
        size: 0
      }
    )

  response["hits"]["total"]
end