module Mongoid::FullTextSearch

Constants

VERSION

Public Instance Methods

remove_from_ngram_index() click to toggle source
# File lib/mongoid/full_text_search.rb, line 363
def remove_from_ngram_index
  mongoid_fulltext_config.each_pair do |index_name, _fulltext_config|
    coll = collection.database[index_name]
    if Mongoid::Compatibility::Version.mongoid5_or_newer?
      coll.find('document_id' => _id).delete_many
    else
      coll.find('document_id' => _id).remove_all
    end
  end
end
update_ngram_index() click to toggle source
# File lib/mongoid/full_text_search.rb, line 317
def update_ngram_index
  mongoid_fulltext_config.each_pair do |index_name, fulltext_config|
    if condition = fulltext_config[:update_if]
      case condition
      when Symbol then  next unless send condition
      when String then  next unless instance_eval condition
      when Proc then    next unless condition.call self
      else; next
      end
    end

    # remove existing ngrams from external index
    coll = collection.database[index_name.to_sym]
    if Mongoid::Compatibility::Version.mongoid5_or_newer?
      coll.find('document_id' => _id).delete_many
    else
      coll.find('document_id' => _id).remove_all
    end
    # extract ngrams from fields
    field_values = fulltext_config[:ngram_fields].map { |field| 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.key?(:filters)
      filter_values = Hash[fulltext_config[:filters].map do |key, value|
        begin
          [key, value.call(self)]
        rescue StandardError
          # 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' => _id, 'score' => score, 'class' => self.class.name }
      index_document['filter_values'] = filter_values if fulltext_config.key?(:filters)
      if Mongoid::Compatibility::Version.mongoid5_or_newer?
        coll.insert_one(index_document)
      else
        coll.insert(index_document)
      end
    end
  end
end