Module: AlgoliaSearch::ClassMethods

Defined in:
lib/algoliasearch-rails.rb

Overview

these are the class methods added when AlgoliaSearch is included

Defined Under Namespace

Modules: AdditionalMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/algoliasearch-rails.rb', line 357

def self.extended(base)
  class <<base
    alias_method :without_auto_index, :algolia_without_auto_index unless method_defined? :without_auto_index
    alias_method :reindex!, :algolia_reindex! unless method_defined? :reindex!
    alias_method :reindex, :algolia_reindex unless method_defined? :reindex
    alias_method :index_objects, :algolia_index_objects unless method_defined? :index_objects
    alias_method :index!, :algolia_index! unless method_defined? :index!
    alias_method :remove_from_index!, :algolia_remove_from_index! unless method_defined? :remove_from_index!
    alias_method :clear_index!, :algolia_clear_index! unless method_defined? :clear_index!
    alias_method :search, :algolia_search unless method_defined? :search
    alias_method :raw_search, :algolia_raw_search unless method_defined? :raw_search
    alias_method :search_facet, :algolia_search_facet unless method_defined? :search_facet
    alias_method :search_for_facet_values, :algolia_search_for_facet_values unless method_defined? :search_for_facet_values
    alias_method :index, :algolia_index unless method_defined? :index
    alias_method :index_name, :algolia_index_name unless method_defined? :index_name
    alias_method :must_reindex?, :algolia_must_reindex? unless method_defined? :must_reindex?
  end

  base.cattr_accessor :algoliasearch_options, :algoliasearch_settings
end

Instance Method Details

#algolia_clear_index!(synchronous = false) ⇒ Object



642
643
644
645
646
647
648
649
650
651
# File 'lib/algoliasearch-rails.rb', line 642

def algolia_clear_index!(synchronous = false)
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    index = algolia_ensure_init(options, settings)
    next if options[:replica]
    synchronous || options[:synchronous] ? index.clear_objects! : index.clear_objects
    @algolia_indexes[settings] = nil
  end
  nil
end

#algolia_index(name = nil) ⇒ Object



730
731
732
733
734
735
736
737
738
# File 'lib/algoliasearch-rails.rb', line 730

def algolia_index(name = nil)
  if name
    algolia_configurations.each do |o, s|
      return algolia_ensure_init(o, s) if o[:index_name].to_s == name.to_s
    end
    raise ArgumentError.new("Invalid index/replica name: #{name}")
  end
  algolia_ensure_init
end

#algolia_index!(object, synchronous = false) ⇒ Object



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
# File 'lib/algoliasearch-rails.rb', line 599

def algolia_index!(object, synchronous = false)
  return if algolia_without_auto_index_scope
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    object_id = algolia_object_id_of(object, options)
    index = algolia_ensure_init(options, settings)
    next if options[:replica]
    if algolia_indexable?(object, options)
      raise ArgumentError.new("Cannot index a record with a blank objectID") if object_id.blank?
      if synchronous || options[:synchronous]
        index.save_object!(settings.get_attributes(object).merge 'objectID' => algolia_object_id_of(object, options))
      else
        index.save_object(settings.get_attributes(object).merge 'objectID' => algolia_object_id_of(object, options))
      end
    elsif algolia_conditional_index?(options) && !object_id.blank?
      # remove non-indexable objects
      if synchronous || options[:synchronous]
        index.delete_object!(object_id)
      else
        index.delete_object(object_id)
      end
    end
  end
  nil
end

#algolia_index_name(options = nil) ⇒ Object



740
741
742
743
744
745
# File 'lib/algoliasearch-rails.rb', line 740

def algolia_index_name(options = nil)
  options ||= algoliasearch_options
  name = options[:index_name] || model_name.to_s.gsub('::', '_')
  name = "#{name}_#{Rails.env.to_s}" if options[:per_environment]
  name
end

#algolia_index_objects(objects, synchronous = false) ⇒ Object



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

def algolia_index_objects(objects, synchronous = false)
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    index = algolia_ensure_init(options, settings)
    next if options[:replica]
    task = index.save_objects(objects.map { |o| settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, options) })
    index.wait_task(task.raw_response["taskID"]) if synchronous || options[:synchronous]
  end
end

#algolia_must_reindex?(object) ⇒ 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
# File 'lib/algoliasearch-rails.rb', line 747

def algolia_must_reindex?(object)
  # use +algolia_dirty?+ method if implemented
  return object.send(:algolia_dirty?) if (object.respond_to?(:algolia_dirty?))
  # Loop over each index to see if a attribute used in records has changed
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    next if options[:replica]
    return true if algolia_object_id_changed?(object, options)
    settings.get_attribute_names(object).each do |k|
      return true if algolia_attribute_changed?(object, k, true)
    end
    [options[:if], options[:unless]].each do |condition|
      case condition
      when nil
      when String, Symbol
        return true if algolia_attribute_changed?(object, condition, true)
      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
  return false
end

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



653
654
655
656
657
658
659
660
# File 'lib/algoliasearch-rails.rb', line 653

def algolia_raw_search(q, params = {})
  index_name = params.delete(:index) ||
               params.delete('index') ||
               params.delete(:replica) ||
               params.delete('replica')
  index = algolia_index(index_name)
  index.search(q, Hash[params.map { |k,v| [k.to_s, v.to_s] }])
end

#algolia_reindex(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) ⇒ Object

reindex whole database using a extra temporary index + move operation



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

def algolia_reindex(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false)
  return if algolia_without_auto_index_scope
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    next if options[:replica]

    # fetch the master settings
    master_index = algolia_ensure_init(options, settings)
    master_settings = master_index.get_settings rescue {} # if master doesn't exist yet
    master_exists = master_settings != {}
    master_settings.merge!(JSON.parse(settings.to_settings.to_json)) # convert symbols to strings

    # remove the replicas of the temporary index
    master_settings.delete :replicas
    master_settings.delete 'replicas'

    # init temporary index
    src_index_name = algolia_index_name(options)
    tmp_index_name = "#{src_index_name}.tmp"
    tmp_options = options.merge({ :index_name => tmp_index_name })
    tmp_options.delete(:per_environment) # already included in the temporary index_name
    tmp_settings = settings.dup

    if options[:check_settings] == false && master_exists
      AlgoliaSearch.client.copy_index!(src_index_name, tmp_index_name, { scope: %w[settings synonyms rules] })
      tmp_index = SafeIndex.new(tmp_index_name, !!options[:raise_on_failure])
    else
      tmp_index = algolia_ensure_init(tmp_options, tmp_settings, master_settings)
    end

    algolia_find_in_batches(batch_size) do |group|
      if algolia_conditional_index?(options)
        # select only indexable objects
        group = group.select { |o| algolia_indexable?(o, tmp_options) }
      end
      objects = group.map { |o| tmp_settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, tmp_options) }
      tmp_index.save_objects(objects)
    end

    move_task = SafeIndex.move_index(tmp_index.name, src_index_name)
    master_index.wait_task(move_task.raw_response["taskID"]) if synchronous || options[:synchronous]
  end
  nil
end

#algolia_reindex!(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) ⇒ Object



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

def algolia_reindex!(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false)
  return if algolia_without_auto_index_scope
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    index = algolia_ensure_init(options, settings)
    next if options[:replica]
    last_task = nil

    algolia_find_in_batches(batch_size) do |group|
      if algolia_conditional_index?(options)
        # delete non-indexable objects
        ids = group.select { |o| !algolia_indexable?(o, options) }.map { |o| algolia_object_id_of(o, options) }
        index.delete_objects(ids.select { |id| !id.blank? })
        # select only indexable objects
        group = group.select { |o| algolia_indexable?(o, options) }
      end
      objects = group.map do |o|
        attributes = settings.get_attributes(o)
        unless attributes.class == Hash
          attributes = attributes.to_hash
        end
        attributes.merge 'objectID' => algolia_object_id_of(o, options)
      end
      last_task = index.save_objects(objects)
    end
    index.wait_task(last_task.raw_response["taskID"]) if last_task and (synchronous || options[:synchronous])
  end
  nil
end

#algolia_remove_from_index!(object, synchronous = false) ⇒ Object

Raises:

  • (ArgumentError)


625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
# File 'lib/algoliasearch-rails.rb', line 625

def algolia_remove_from_index!(object, synchronous = false)
  return if algolia_without_auto_index_scope
  object_id = algolia_object_id_of(object)
  raise ArgumentError.new("Cannot index a record with a blank objectID") if object_id.blank?
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    index = algolia_ensure_init(options, settings)
    next if options[:replica]
    if synchronous || options[:synchronous]
      index.delete_object!(object_id)
    else
      index.delete_object(object_id)
    end
  end
  nil
end

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



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

def algolia_search(q, params = {})
  if AlgoliaSearch.configuration[:pagination_backend]
    # kaminari and will_paginate start pagination at 1, Algolia starts at 0
    params[:page] = (params.delete('page') || params.delete(:page)).to_i
    params[:page] -= 1 if params[:page].to_i > 0
  end
  json = algolia_raw_search(q, params)
  hit_ids = json['hits'].map { |hit| hit['objectID'] }
  if defined?(::Mongoid::Document) && self.include?(::Mongoid::Document)
    condition_key = algolia_object_id_method.in
  else
    condition_key = algolia_object_id_method
  end
  results_by_id = algoliasearch_options[:type].where(condition_key => hit_ids).index_by do |hit|
    algolia_object_id_of(hit)
  end
  results = json['hits'].map do |hit|
    o = results_by_id[hit['objectID'].to_s]
    if o
      o.highlight_result = hit['_highlightResult']
      o.snippet_result = hit['_snippetResult']
      o
    end
  end.compact
  # Algolia has a default limit of 1000 retrievable hits
  total_hits = json['nbHits'].to_i < json['nbPages'].to_i * json['hitsPerPage'].to_i ?
    json['nbHits'].to_i: json['nbPages'].to_i * json['hitsPerPage'].to_i
  res = AlgoliaSearch::Pagination.create(results, total_hits, algoliasearch_options.merge({ :page => json['page'].to_i + 1, :per_page => json['hitsPerPage'] }))
  res.extend(AdditionalMethods)
  res.send(:algolia_init_raw_answer, json)
  res
end

#algolia_search_for_facet_values(facet, text, params = {}) ⇒ Object Also known as: algolia_search_facet



717
718
719
720
721
722
723
724
725
# File 'lib/algoliasearch-rails.rb', line 717

def algolia_search_for_facet_values(facet, text, params = {})
  index_name = params.delete(:index) ||
               params.delete('index') ||
               params.delete(:replica) ||
               params.delete('replicas')
  index = algolia_index(index_name)
  query = Hash[params.map { |k, v| [k.to_s, v.to_s] }]
  index.search_for_facet_values(facet, text, query)['facetHits']
end

#algolia_set_settings(synchronous = false) ⇒ Object



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
# File 'lib/algoliasearch-rails.rb', line 572

def algolia_set_settings(synchronous = false)
  algolia_configurations.each do |options, settings|
    if options[:primary_settings] && options[:inherit]
      primary = options[:primary_settings].to_settings
      primary.delete :replicas
      primary.delete 'replicas'
      final_settings = primary.merge(settings.to_settings)
    else
      final_settings = settings.to_settings
    end

    index = SafeIndex.new(algolia_index_name(options), true)
    task = index.set_settings(final_settings)
    index.wait_task(task.raw_response["taskID"]) if synchronous
  end
end

#algolia_without_auto_index(&block) ⇒ Object



479
480
481
482
483
484
485
486
# File 'lib/algoliasearch-rails.rb', line 479

def algolia_without_auto_index(&block)
  self.algolia_without_auto_index_scope = true
  begin
    yield
  ensure
    self.algolia_without_auto_index_scope = false
  end
end

#algolia_without_auto_index_scopeObject



492
493
494
# File 'lib/algoliasearch-rails.rb', line 492

def algolia_without_auto_index_scope
  Thread.current["algolia_without_auto_index_scope_for_#{self.model_name}"]
end

#algolia_without_auto_index_scope=(value) ⇒ Object



488
489
490
# File 'lib/algoliasearch-rails.rb', line 488

def algolia_without_auto_index_scope=(value)
  Thread.current["algolia_without_auto_index_scope_for_#{self.model_name}"] = value
end

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



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

def algoliasearch(options = {}, &block)
  self.algoliasearch_settings = IndexSettings.new(options, &block)
  self.algoliasearch_options = { :type => algolia_full_const_get(model_name.to_s), :per_page => algoliasearch_settings.get_setting(:hitsPerPage) || 10, :page => 1 }.merge(options)

  attr_accessor :highlight_result, :snippet_result

  if options[:synchronous] == true
    if defined?(::Sequel) && 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
          algolia_mark_synchronous
        end
      end
    else
      after_validation :algolia_mark_synchronous if respond_to?(:after_validation)
    end
  end
  if options[:enqueue]
    raise ArgumentError.new("Cannot use a enqueue if the `synchronous` option if set") if options[:synchronous]
    proc = if options[:enqueue] == true
      Proc.new do |record, remove|
        AlgoliaJob.perform_later(record, remove ? 'algolia_remove_from_index!' : 'algolia_index!')
      end
    elsif options[:enqueue].respond_to?(:call)
      options[:enqueue]
    elsif options[:enqueue].is_a?(Symbol)
      Proc.new { |record, remove| self.send(options[:enqueue], record, remove) }
    else
      raise ArgumentError.new("Invalid `enqueue` option: #{options[:enqueue]}")
    end
    algoliasearch_options[:enqueue] = Proc.new do |record, remove|
      proc.call(record, remove) unless algolia_without_auto_index_scope
    end
  end
  unless options[:auto_index] == false
    if defined?(::Sequel) && 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
          algolia_mark_must_reindex
        end

        define_method(:before_save) do |*args|
          copy_before_save.bind(self).call
          algolia_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
            algolia_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
            self.db.after_commit do
              algolia_perform_index_tasks
            end
          end
        end
      end
    else
      after_validation :algolia_mark_must_reindex if respond_to?(:after_validation)
      before_save :algolia_mark_for_auto_indexing if respond_to?(:before_save)
      if respond_to?(:after_commit)
        after_commit :algolia_perform_index_tasks
      elsif respond_to?(:after_save)
        after_save :algolia_perform_index_tasks
      end
    end
  end
  unless options[:auto_remove] == false
    if defined?(::Sequel) && 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
          algolia_enqueue_remove_from_index!(algolia_synchronous?)
          super(*args)
        end
      end
    else
      after_destroy { |searchable| searchable.algolia_enqueue_remove_from_index!(algolia_synchronous?) } if respond_to?(:after_destroy)
    end
  end
end