Module: Mongoid::FullTextSearch

Extended by:
ActiveSupport::Concern
Defined in:
lib/mongoid_fulltext.rb

Defined Under Namespace

Modules: ClassMethods Classes: UnknownFilterQueryOperator, UnspecifiedIndexError

Instance Method Summary collapse

Instance Method Details

#remove_from_ngram_indexObject



334
335
336
337
338
339
# File 'lib/mongoid_fulltext.rb', line 334

def remove_from_ngram_index
  self.mongoid_fulltext_config.each_pair do |index_name, fulltext_config|
    coll = collection.database[index_name]
    coll.find({'document_id' => self._id}).remove_all
  end
end

#update_ngram_indexObject



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
# File 'lib/mongoid_fulltext.rb', line 296

def update_ngram_index
  self.mongoid_fulltext_config.each_pair do |index_name, fulltext_config|
    if condition = fulltext_config[:update_if]
      case condition
      when Symbol;  next unless self.send condition
      when String;  next unless instance_eval condition
      when Proc;    next unless condition.call self
      else;         next
      end
    end

    # remove existing ngrams from external index
    coll = collection.database[index_name.to_sym]
    coll.find({'document_id' => self._id}).remove_all
    # extract ngrams from fields
    field_values = fulltext_config[:ngram_fields].map { |field| self.send(field) }
    ngrams = field_values.inject({}) { |accum, item| accum.update(self.class.all_ngrams(item, fulltext_config, false))}
    return if ngrams.empty?
    # apply filters, if necessary
    filter_values = nil
    if fulltext_config.has_key?(:filters)
      filter_values = Hash[fulltext_config[:filters].map do |key,value|
        begin
          [key, value.call(self)]
        rescue
          # Suppress any exceptions caused by filters
        end
      end.compact]
    end
    # insert new ngrams in external index
    ngrams.each_pair do |ngram, score|
      index_document = {'ngram' => ngram, 'document_id' => self._id, 'score' => score, 'class' => self.class.name}
      index_document['filter_values'] = filter_values if fulltext_config.has_key?(:filters)
      coll.insert(index_document)
    end
  end
end