Module: MeiliSearch::Rails::ClassMethods

Defined in:
lib/meilisearch-rails.rb

Overview

these are the class methods added when MeiliSearch is included

Defined Under Namespace

Modules: AdditionalMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/meilisearch-rails.rb', line 354

def self.extended(base)
  class << base
    alias_method :without_auto_index, :ms_without_auto_index unless method_defined? :without_auto_index
    alias_method :reindex!, :ms_reindex! unless method_defined? :reindex!
    alias_method :index_documents, :ms_index_documents unless method_defined? :index_documents
    alias_method :index!, :ms_index! unless method_defined? :index!
    alias_method :remove_from_index!, :ms_remove_from_index! unless method_defined? :remove_from_index!
    alias_method :clear_index!, :ms_clear_index! unless method_defined? :clear_index!
    alias_method :search, :ms_search unless method_defined? :search
    alias_method :raw_search, :ms_raw_search unless method_defined? :raw_search
    alias_method :index, :ms_index unless method_defined? :index
    alias_method :index_uid, :ms_index_uid unless method_defined? :index_uid
    alias_method :must_reindex?, :ms_must_reindex? unless method_defined? :must_reindex?
  end

  base.cattr_accessor :meilisearch_options, :meilisearch_settings
end

Instance Method Details

#meilisearch(options = {}, &block) ⇒ Object



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
# File 'lib/meilisearch-rails.rb', line 372

def meilisearch(options = {}, &block)
  self.meilisearch_settings = IndexSettings.new(options, &block)
  self.meilisearch_options = {
    type: model_name.to_s.constantize,
    per_page: meilisearch_settings.get_setting(:hitsPerPage) || 20, page: 1
  }.merge(options)

  attr_accessor :formatted

  if options.key?(:per_environment)
    raise BadConfiguration, ':per_environment option should be defined globally on MeiliSearch::Rails.configuration block.'
  end

  if options[:synchronous] == true
    if defined?(::Sequel::Model) && self < Sequel::Model
      class_eval do
        copy_after_validation = instance_method(:after_validation)
        define_method(:after_validation) do |*args|
          super(*args)
          copy_after_validation.bind(self).call
          ms_mark_synchronous
        end
      end
    elsif respond_to?(:after_validation)
      after_validation :ms_mark_synchronous
    end
  end
  if options[:enqueue]
    raise ArgumentError, 'Cannot use a enqueue if the `synchronous` option is set' if options[:synchronous]

    proc = if options[:enqueue] == true
             proc do |record, remove|
               if remove
                 MSCleanUpJob.perform_later(record.ms_entries)
               else
                 MSJob.perform_later(record, 'ms_index!')
               end
             end
           elsif options[:enqueue].respond_to?(:call)
             options[:enqueue]
           elsif options[:enqueue].is_a?(Symbol)
             proc { |record, remove| send(options[:enqueue], record, remove) }
           else
             raise ArgumentError, "Invalid `enqueue` option: #{options[:enqueue]}"
           end
    meilisearch_options[:enqueue] = proc do |record, remove|
      proc.call(record, remove) unless ms_without_auto_index_scope
    end
  end
  unless options[:auto_index] == false
    if defined?(::Sequel::Model) && self < Sequel::Model
      class_eval do
        copy_after_validation = instance_method(:after_validation)
        copy_before_save = instance_method(:before_save)

        define_method(:after_validation) do |*args|
          super(*args)
          copy_after_validation.bind(self).call
          ms_mark_must_reindex
        end

        define_method(:before_save) do |*args|
          copy_before_save.bind(self).call
          ms_mark_for_auto_indexing
          super(*args)
        end

        sequel_version = Gem::Version.new(Sequel.version)
        if sequel_version >= Gem::Version.new('4.0.0') && sequel_version < Gem::Version.new('5.0.0')
          copy_after_commit = instance_method(:after_commit)
          define_method(:after_commit) do |*args|
            super(*args)
            copy_after_commit.bind(self).call
            ms_perform_index_tasks
          end
        else
          copy_after_save = instance_method(:after_save)
          define_method(:after_save) do |*args|
            super(*args)
            copy_after_save.bind(self).call
            db.after_commit do
              ms_perform_index_tasks
            end
          end
        end
      end
    else
      after_validation :ms_mark_must_reindex if respond_to?(:after_validation)
      before_save :ms_mark_for_auto_indexing if respond_to?(:before_save)
      if respond_to?(:after_commit)
        after_commit :ms_perform_index_tasks
      elsif respond_to?(:after_save)
        after_save :ms_perform_index_tasks
      end
    end
  end
  unless options[:auto_remove] == false
    if defined?(::Sequel::Model) && self < Sequel::Model
      class_eval do
        copy_after_destroy = instance_method(:after_destroy)

        define_method(:after_destroy) do |*args|
          copy_after_destroy.bind(self).call
          ms_enqueue_remove_from_index!(ms_synchronous?)
          super(*args)
        end
      end
    elsif respond_to?(:after_destroy)
      after_destroy_commit { |searchable| searchable.ms_enqueue_remove_from_index!(ms_synchronous?) }
    end
  end
end

#ms_clear_index!(synchronous = false) ⇒ Object



619
620
621
622
623
624
625
626
627
628
# File 'lib/meilisearch-rails.rb', line 619

def ms_clear_index!(synchronous = false)
  ms_configurations.each do |options, settings|
    next if ms_indexing_disabled?(options)

    index = ms_ensure_init(options, settings)
    synchronous || options[:synchronous] ? index.delete_all_documents.await : index.delete_all_documents
    @ms_indexes[MeiliSearch::Rails.active?][settings] = nil
  end
  nil
end

#ms_entries_for(document:, synchronous:) ⇒ Object

Raises:

  • (ArgumentError)


587
588
589
590
591
592
593
594
595
596
597
598
# File 'lib/meilisearch-rails.rb', line 587

def ms_entries_for(document:, synchronous:)
  primary_key = ms_primary_key_of(document)
  raise ArgumentError, 'Cannot index a record without a primary key' if primary_key.blank?

  ms_configurations.filter_map do |options, settings|
    {
      synchronous: synchronous || options[:synchronous],
      index_uid: ms_index_uid(options),
      primary_key: primary_key
    }.with_indifferent_access unless ms_indexing_disabled?(options)
  end
end

#ms_index(name = nil) ⇒ Object



727
728
729
730
731
732
733
734
735
# File 'lib/meilisearch-rails.rb', line 727

def ms_index(name = nil)
  if name
    ms_configurations.each do |o, s|
      return ms_ensure_init(o, s) if o[:index_uid].to_s == name.to_s
    end
    raise ArgumentError, "Invalid index name: #{name}"
  end
  ms_ensure_init
end

#ms_index!(document, synchronous = false) ⇒ Object



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
# File 'lib/meilisearch-rails.rb', line 556

def ms_index!(document, synchronous = false)
  return if ms_without_auto_index_scope

  # MS tasks to be returned
  ms_configurations.map do |options, settings|
    next if ms_indexing_disabled?(options)

    primary_key = ms_primary_key_of(document, options)
    index = ms_ensure_init(options, settings)
    if Utilities.indexable?(document, options)
      raise ArgumentError, 'Cannot index a record without a primary key' if primary_key.blank?

      doc = settings.get_attributes(document)
      doc = doc.merge ms_pk(options) => primary_key

      if synchronous || options[:synchronous]
        index.add_documents(doc).await
      else
        index.add_documents(doc)
      end
    elsif ms_conditional_index?(options) && primary_key.present?
      # remove non-indexable documents
      if synchronous || options[:synchronous]
        index.delete_document(primary_key).await
      else
        index.delete_document(primary_key)
      end
    end
  end.compact
end

#ms_index_documents(documents, synchronous = false) ⇒ Object



546
547
548
549
550
551
552
553
554
# File 'lib/meilisearch-rails.rb', line 546

def ms_index_documents(documents, synchronous = false)
  ms_configurations.each do |options, settings|
    next if ms_indexing_disabled?(options)

    index = ms_ensure_init(options, settings)
    task = index.add_documents(documents.map { |d| settings.get_attributes(d).merge ms_pk(options) => ms_primary_key_of(d, options) })
    index.wait_for_task(task['taskUid']) if synchronous || options[:synchronous]
  end
end

#ms_index_uid(options = nil) ⇒ Object



737
738
739
740
741
742
743
744
745
# File 'lib/meilisearch-rails.rb', line 737

def ms_index_uid(options = nil)
  options ||= meilisearch_options
  global_options ||= MeiliSearch::Rails.configuration

  name = options[:index_uid] || model_name.to_s.gsub('::', '_')
  name = "#{name}_#{::Rails.env}" if global_options[:per_environment]

  name
end

#ms_must_reindex?(document) ⇒ Boolean

Returns:

  • (Boolean)


747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
# File 'lib/meilisearch-rails.rb', line 747

def ms_must_reindex?(document)
  # use +ms_dirty?+ method if implemented
  return document.send(:ms_dirty?) if document.respond_to?(:ms_dirty?)

  # Loop over each index to see if a attribute used in records has changed
  ms_configurations.each do |options, settings|
    next if ms_indexing_disabled?(options)
    return true if ms_primary_key_changed?(document, options)

    settings.get_attribute_names(document).each do |k|
      return true if ms_attribute_changed?(document, k)
      # return true if !document.respond_to?(changed_method) || document.send(changed_method)
    end
    [options[:if], options[:unless]].each do |condition|
      case condition
      when nil
        return false
      when String, Symbol
        return true if ms_attribute_changed?(document, condition)
      else
        # if the :if, :unless condition is a anything else,
        # we have no idea whether we should reindex or not
        # let's always reindex then
        return true
      end
    end
  end

  # By default, we don't reindex
  false
end

#ms_primary_key_method(options = nil) ⇒ Object



779
780
781
782
# File 'lib/meilisearch-rails.rb', line 779

def ms_primary_key_method(options = nil)
  options ||= meilisearch_options
  options[:primary_key] || options[:id] || :id
end

#ms_raw_search(q, params = {}) ⇒ Object



630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# File 'lib/meilisearch-rails.rb', line 630

def ms_raw_search(q, params = {})
  index_uid = params.delete(:index) || params.delete('index')

  unless meilisearch_settings.get_setting(:attributes_to_highlight).nil?
    params[:attributes_to_highlight] = meilisearch_settings.get_setting(:attributes_to_highlight)
  end

  unless meilisearch_settings.get_setting(:attributes_to_crop).nil?
    params[:attributes_to_crop] = meilisearch_settings.get_setting(:attributes_to_crop)

    unless meilisearch_settings.get_setting(:crop_length).nil?
      params[:crop_length] = meilisearch_settings.get_setting(:crop_length)
    end
  end

  index = ms_index(index_uid)
  index.search(q, params.to_h { |k, v| [k, v] })
end

#ms_reindex!(batch_size = MeiliSearch::Rails::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) ⇒ Object



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
# File 'lib/meilisearch-rails.rb', line 502

def ms_reindex!(batch_size = MeiliSearch::Rails::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false)
  return if ms_without_auto_index_scope

  ms_configurations.each do |options, settings|
    next if ms_indexing_disabled?(options)

    index = ms_ensure_init(options, settings)
    last_task = nil

    ms_find_in_batches(batch_size) do |group|
      if ms_conditional_index?(options)
        # delete non-indexable documents
        ids = group.select { |d| !Utilities.indexable?(d, options) }.map { |d| ms_primary_key_of(d, options) }
        index.delete_documents(ids.select(&:present?))
        # select only indexable documents
        group = group.select { |d| Utilities.indexable?(d, options) }
      end
      documents = group.map do |d|
        attributes = settings.get_attributes(d)
        attributes = attributes.to_hash unless attributes.instance_of?(Hash)
        attributes.merge ms_pk(options) => ms_primary_key_of(d, options)
      end
      last_task = index.add_documents(documents)
    end
    index.wait_for_task(last_task['taskUid']) if last_task && (synchronous || options[:synchronous])
  end
  nil
end

#ms_remove_from_index!(document, synchronous = false) ⇒ Object

Raises:

  • (ArgumentError)


600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# File 'lib/meilisearch-rails.rb', line 600

def ms_remove_from_index!(document, synchronous = false)
  return if ms_without_auto_index_scope

  primary_key = ms_primary_key_of(document)
  raise ArgumentError, 'Cannot index a record without a primary key' if primary_key.blank?

  ms_configurations.each do |options, settings|
    next if ms_indexing_disabled?(options)

    index = ms_ensure_init(options, settings)
    if synchronous || options[:synchronous]
      index.delete_document(primary_key).await
    else
      index.delete_document(primary_key)
    end
  end
  nil
end

#ms_search(query, params = {}) ⇒ Object



668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# File 'lib/meilisearch-rails.rb', line 668

def ms_search(query, params = {})
  if MeiliSearch::Rails.configuration[:pagination_backend]
    %i[page hitsPerPage hits_per_page].each do |key|
      params[key.to_s.underscore.to_sym] = params[key].to_i if params.key?(key)
    end

    # It is required to activate the finite pagination in Meilisearch v0.30 (or newer),
    # to have at least `hits_per_page` defined or `page` in the search request.
    params[:page] ||= 1
  end

  json = ms_raw_search(query, params)

  # condition_key gets the primary key of the document; looks for "id" on the options
  condition_key = if defined?(::Mongoid::Document) && include?(::Mongoid::Document)
                    ms_primary_key_method.in
                  else
                    ms_primary_key_method
                  end

  # The condition_key must be a valid column otherwise, the `.where` below will not work
  # Since we provide a way to customize the primary_key value, `ms_pk(meilisearch_options)` may not
  # respond with a valid database column. The blocks below prevent that from happening.
  has_virtual_column_as_pk = if defined?(::Sequel::Model) && self < Sequel::Model
                               meilisearch_options[:type].columns.map(&:to_s).exclude?(condition_key.to_s)
                             else
                               meilisearch_options[:type].columns.map(&:name).map(&:to_s).exclude?(condition_key.to_s)
                             end

  condition_key = meilisearch_options[:type].primary_key if has_virtual_column_as_pk

  hit_ids = if has_virtual_column_as_pk
              json['hits'].map { |hit| hit[condition_key] }
            else
              json['hits'].map { |hit| hit[ms_pk(meilisearch_options).to_s] }
            end

  # meilisearch_options[:type] refers to the Model name (e.g. Product)
  # results_by_id creates a hash with the primaryKey of the document (id) as the key and doc itself as the value
  # {"13"=>#<Product id: 13, name: "iphone", href: "apple", tags: nil, type: nil,
  # description: "Puts even more features at your fingertips", release_date: nil>}
  results_by_id = meilisearch_options[:type].where(condition_key => hit_ids).index_by do |hit|
    ms_primary_key_of(hit)
  end

  results = json['hits'].map do |hit|
    o = results_by_id[hit[ms_pk(meilisearch_options).to_s].to_s]
    if o
      o.formatted = hit['_formatted']
      o
    end
  end.compact

  res = Pagination.create(results, json['totalHits'], meilisearch_options.merge(page: json['page'], per_page: json['hitsPerPage']))
  res.extend(AdditionalMethods)
  res.send(:ms_init_raw_answer, json)
  res
end

#ms_set_settings(synchronous = false) ⇒ Object



531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/meilisearch-rails.rb', line 531

def ms_set_settings(synchronous = false)
  ms_configurations.each do |options, settings|
    if options[:primary_settings] && options[:inherit]
      primary = options[:primary_settings].to_settings
      final_settings = primary.merge(settings.to_settings)
    else
      final_settings = settings.to_settings
    end

    index = SafeIndex.new(ms_index_uid(options), true, options)
    task = index.update_settings(final_settings)
    index.wait_for_task(task['taskUid']) if synchronous
  end
end

#ms_without_auto_index(&block) ⇒ Object



485
486
487
488
489
490
491
492
# File 'lib/meilisearch-rails.rb', line 485

def ms_without_auto_index(&block)
  self.ms_without_auto_index_scope = true
  begin
    yield
  ensure
    self.ms_without_auto_index_scope = false
  end
end

#ms_without_auto_index_scopeObject



498
499
500
# File 'lib/meilisearch-rails.rb', line 498

def ms_without_auto_index_scope
  Thread.current["ms_without_auto_index_scope_for_#{model_name}"]
end

#ms_without_auto_index_scope=(value) ⇒ Object



494
495
496
# File 'lib/meilisearch-rails.rb', line 494

def ms_without_auto_index_scope=(value)
  Thread.current["ms_without_auto_index_scope_for_#{model_name}"] = value
end