Class: RailsPanda::Search::Strategies::Ngram::NgramIndexer

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_panda_search/strategies/ngram/ngram_indexer.rb

Class Method Summary collapse

Class Method Details

.index_record!(record, columns) ⇒ Object

Create ngram entries for a record's columns. Pure insert.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rails_panda_search/strategies/ngram/ngram_indexer.rb', line 20

def index_record!(record, columns)
  pk_hash = primary_key_hash(record)
  source_type = record.class.name

  columns.each do |column|
    value = record.send(column)
    next if value.blank?

    ngrams_for(value).each do |ngram|
      NgramEntry.create!(
        ngram: ngram,
        source_type: source_type,
        source_id: pk_hash.to_json,
        source_column: column.to_s
      )
    end
  end
end

.ngrams_for(text) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/rails_panda_search/strategies/ngram/ngram_indexer.rb', line 9

def ngrams_for(text)
  n = RailsPanda::Search.config.ngram_size

  text.to_s.downcase.split(" ").flat_map do |word|
    next [] if word.length < n

    (0..word.length - n).map { |i| word[i, n] }
  end.uniq
end

.primary_key_hash(record) ⇒ Object



47
48
49
50
# File 'lib/rails_panda_search/strategies/ngram/ngram_indexer.rb', line 47

def primary_key_hash(record)
  pk = Array(record.class.primary_key)
  pk.each_with_object({}) { |key, hash| hash[key] = record.send(key) }
end

.remove_record!(record) ⇒ Object

Remove all ngram entries for a record.



40
41
42
43
44
45
# File 'lib/rails_panda_search/strategies/ngram/ngram_indexer.rb', line 40

def remove_record!(record)
  NgramEntry.where(
    source_type: record.class.name,
    source_id: primary_key_hash(record).to_json
  ).delete_all
end