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
- #algolia_clear_index!(synchronous = false) ⇒ Object
- #algolia_index!(object, synchronous = false) ⇒ Object
- #algolia_index_name(options = nil, index_name = nil) ⇒ Object
- #algolia_index_objects(objects, synchronous = false) ⇒ Object
- #algolia_must_reindex?(object) ⇒ Boolean
- #algolia_raw_search(q, params = {}) ⇒ Object
-
#algolia_reindex(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) ⇒ Object
reindex whole database using a extra temporary index + move operation.
- #algolia_reindex!(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) ⇒ Object
- #algolia_remove_from_index!(object, synchronous = false) ⇒ Object
- #algolia_search(q, params = {}) ⇒ Object
- #algolia_search_for_facet_values(facet, text, params = {}) ⇒ Object (also: #algolia_search_facet)
- #algolia_set_settings(synchronous = false) ⇒ Object
- #algolia_without_auto_index(&block) ⇒ Object
- #algolia_without_auto_index_scope ⇒ Object
- #algolia_without_auto_index_scope=(value) ⇒ Object
- #algoliasearch(options = {}, &block) ⇒ Object
- #ensure_algolia_index(name = nil) ⇒ Object
Class Method Details
.extended(base) ⇒ Object
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
# File 'lib/algoliasearch-rails.rb', line 302 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_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
612 613 614 615 616 617 618 619 620 621 622 623 624 625 |
# File 'lib/algoliasearch-rails.rb', line 612 def algolia_clear_index!(synchronous = false) algolia_configurations.each do |, settings| next if algolia_indexing_disabled?() || [:replica] algolia_ensure_init(, settings) index_name = algolia_index_name() res = AlgoliaSearch.client.clear_objects(index_name) if synchronous || [:synchronous] AlgoliaSearch.client.wait_for_task(index_name, res.task_id) end end nil end |
#algolia_index!(object, synchronous = false) ⇒ Object
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 |
# File 'lib/algoliasearch-rails.rb', line 566 def algolia_index!(object, synchronous = false) return if algolia_without_auto_index_scope algolia_configurations.each do |, settings| next if algolia_indexing_disabled?() object_id = algolia_object_id_of(object, ) index_name = algolia_index_name() algolia_ensure_init(, settings) next if [:replica] if algolia_indexable?(object, ) raise ArgumentError.new("Cannot index a record with a blank objectID") if object_id.blank? resp = AlgoliaSearch.client.save_object(index_name, settings.get_attributes(object).merge({ 'objectID' => algolia_object_id_of(object, ) })) if synchronous || [:synchronous] AlgoliaSearch.client.wait_for_task(index_name, resp.task_id) end elsif algolia_conditional_index?() && !object_id.blank? # remove non-indexable objects resp = AlgoliaSearch.client.delete_object(index_name, object_id) if synchronous || [:synchronous] AlgoliaSearch.client.wait_for_task(index_name, resp.task_id) end end end nil end |
#algolia_index_name(options = nil, index_name = nil) ⇒ Object
727 728 729 730 731 732 |
# File 'lib/algoliasearch-rails.rb', line 727 def algolia_index_name( = nil, index_name = nil) ||= name = index_name || [:index_name] || model_name.to_s.gsub('::', '_') name = "#{name}_#{Rails.env.to_s}" if [:per_environment] name end |
#algolia_index_objects(objects, synchronous = false) ⇒ Object
552 553 554 555 556 557 558 559 560 561 562 563 564 |
# File 'lib/algoliasearch-rails.rb', line 552 def algolia_index_objects(objects, synchronous = false) algolia_configurations.each do |, settings| next if algolia_indexing_disabled?() algolia_ensure_init(, settings) index_name = algolia_index_name() next if [:replica] tasks = AlgoliaSearch.client.save_objects(index_name, objects.map { |o| settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, ) }) tasks.each do |task| AlgoliaSearch.client.wait_for_task(index_name, task.task_id) if synchronous || [:synchronous] end end end |
#algolia_must_reindex?(object) ⇒ Boolean
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 |
# File 'lib/algoliasearch-rails.rb', line 734 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 |, settings| next if algolia_indexing_disabled?() next if [:replica] return true if algolia_object_id_changed?(object, ) settings.get_attribute_names(object).each do |k| return true if algolia_attribute_changed?(object, k, true) end [[:if], [: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
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 |
# File 'lib/algoliasearch-rails.rb', line 628 def algolia_raw_search(q, params = {}) index_name_base = params.delete(:index) || params.delete('index') || params.delete(:replica) || params.delete('replica') opts = unless index_name_base.nil? algolia_configurations.each do |o, s| if o[:index_name].to_s == index_name_base.to_s opts = o ensure_algolia_index(index_name_base) end end end index_name = algolia_index_name(opts, index_name_base) AlgoliaSearch.client.search_single_index(index_name,Hash[params.to_h.map { |k,v| [k.to_s, v.to_s] }].merge({query: q})).to_hash end |
#algolia_reindex(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) ⇒ Object
reindex whole database using a extra temporary index + move operation
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 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 473 def algolia_reindex(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) return if algolia_without_auto_index_scope algolia_configurations.each do |, settings| next if algolia_indexing_disabled?() next if [:replica] algolia_ensure_init(, settings) index_name = algolia_index_name() # fetch the master settings master_settings = AlgoliaSearch.client.get_settings(index_name).to_hash rescue {} # if master doesn't exist yet master_exists = master_settings != {} master_settings.merge!(settings.to_hash) # remove the replicas of the temporary index master_settings.delete :replicas master_settings.delete 'replicas' # init temporary index tmp_index_name = "#{index_name}.tmp" = .merge({ :index_name => tmp_index_name }) .delete(:per_environment) # already included in the temporary index_name tmp_settings = settings.dup if [:check_settings] == false && master_exists task_id = AlgoliaSearch.client.operation_index( index_name, Algolia::Search::OperationIndexParams.new(operation: Algolia::Search::OperationType::COPY, destination: tmp_index_name, scope: %w[settings synonyms rules]) ).task_id AlgoliaSearch.client.wait_for_task(index_name, task_id) else algolia_ensure_init(, tmp_settings, master_settings) end algolia_find_in_batches(batch_size) do |group| if algolia_conditional_index?() # select only indexable objects group = group.select { |o| algolia_indexable?(o, ) } end objects = group.map { |o| tmp_settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, ) } AlgoliaSearch.client.save_objects(tmp_index_name, objects) end task_id = AlgoliaSearch.client.operation_index( tmp_index_name, Algolia::Search::OperationIndexParams.new(operation: "move", destination: index_name) ).task_id AlgoliaSearch.client.wait_for_task(index_name, task_id) if synchronous || [:synchronous] end nil end |
#algolia_reindex!(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) ⇒ Object
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 |
# File 'lib/algoliasearch-rails.rb', line 440 def algolia_reindex!(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) return if algolia_without_auto_index_scope algolia_configurations.each do |, settings| next if algolia_indexing_disabled?() algolia_ensure_init(, settings) index_name = algolia_index_name() next if [:replica] last_task = nil algolia_find_in_batches(batch_size) do |group| if algolia_conditional_index?() # delete non-indexable objects ids = group.select { |o| !algolia_indexable?(o, ) }.map { |o| algolia_object_id_of(o, ) } AlgoliaSearch.client.delete_objects(index_name, ids.select { |id| !id.blank? }) # select only indexable objects group = group.select { |o| algolia_indexable?(o, ) } 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, ) end save_tasks = AlgoliaSearch.client.save_objects(index_name, objects) last_task = save_tasks.present? ? save_tasks.last.task_id : last_task end AlgoliaSearch.client.wait_for_task(index_name, last_task) if last_task and (synchronous || [:synchronous]) end nil end |
#algolia_remove_from_index!(object, synchronous = false) ⇒ Object
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 |
# File 'lib/algoliasearch-rails.rb', line 593 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 |, settings| next if algolia_indexing_disabled?() algolia_ensure_init(, settings) index_name = algolia_index_name() next if [:replica] resp = AlgoliaSearch.client.delete_object(index_name, object_id) if synchronous || [:synchronous] AlgoliaSearch.client.wait_for_task(index_name, resp.task_id) end end nil end |
#algolia_search(q, params = {}) ⇒ Object
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 |
# File 'lib/algoliasearch-rails.rb', line 670 def algolia_search(q, params = {}) if AlgoliaSearch.configuration[:pagination_backend] # kaminari, will_paginate, and pagy 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 = [: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, .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
703 704 705 706 707 708 709 710 711 712 |
# File 'lib/algoliasearch-rails.rb', line 703 def algolia_search_for_facet_values(facet, text, params = {}) index_name = params.delete(:index) || params.delete('index') || params.delete(:replica) || params.delete('replicas') index_name ||= algolia_index_name() req = Algolia::Search::SearchForFacetValuesRequest.new({facet_query: text, params: params.to_query}) AlgoliaSearch.client.search_for_facet_values(index_name, facet, req).facet_hits end |
#algolia_set_settings(synchronous = false) ⇒ Object
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 |
# File 'lib/algoliasearch-rails.rb', line 526 def algolia_set_settings(synchronous = false) algolia_configurations.each do |, settings| if [:primary_settings] && [:inherit] primary = [:primary_settings].to_settings.to_hash primary.delete :replicas primary.delete 'replicas' final_settings = primary.merge(settings.to_settings.to_hash) else final_settings = settings.to_settings.to_hash end s = final_settings.map do |k, v| [settings.setting_name(k), v] end.to_h synonyms = s.delete("synonyms") || s.delete(:synonyms) unless synonyms.nil? || synonyms.empty? resp = AlgoliaSearch.client.save_synonyms(index_name,synonyms.map {|s| Algolia::Search::SynonymHit.new({object_id: s.join("-"), synonyms: s, type: "synonym"}) } ) AlgoliaSearch.client.wait_for_task(index_name, resp.task_id) if synchronous || [:synchronous] end resp = AlgoliaSearch.client.set_settings(index_name, Algolia::Search::IndexSettings.new(s)) AlgoliaSearch.client.wait_for_task(index_name, resp.task_id) if synchronous || [:synchronous] end end |
#algolia_without_auto_index(&block) ⇒ Object
423 424 425 426 427 428 429 430 |
# File 'lib/algoliasearch-rails.rb', line 423 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_scope ⇒ Object
436 437 438 |
# File 'lib/algoliasearch-rails.rb', line 436 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
432 433 434 |
# File 'lib/algoliasearch-rails.rb', line 432 def algolia_without_auto_index_scope=(value) Thread.current["algolia_without_auto_index_scope_for_#{self.model_name}"] = value end |
#algoliasearch(options = {}, &block) ⇒ Object
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 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 |
# File 'lib/algoliasearch-rails.rb', line 322 def algoliasearch( = {}, &block) self.algoliasearch_settings = IndexSettings.new(, &block) self. = { :type => algolia_full_const_get(model_name.to_s), :per_page => algoliasearch_settings.get_setting(:hitsPerPage) || 10, :page => 1 }.merge() attr_accessor :highlight_result, :snippet_result if [: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 [:enqueue] raise ArgumentError.new("Cannot use a enqueue if the `synchronous` option if set") if [:synchronous] proc = if [:enqueue] == true Proc.new do |record, remove| AlgoliaJob.perform_later(record, remove ? 'algolia_remove_from_index!' : 'algolia_index!') end elsif [:enqueue].respond_to?(:call) [:enqueue] elsif [:enqueue].is_a?(Symbol) Proc.new { |record, remove| self.send([:enqueue], record, remove) } else raise ArgumentError.new("Invalid `enqueue` option: #{[:enqueue]}") end [:enqueue] = Proc.new do |record, remove| proc.call(record, remove) unless algolia_without_auto_index_scope end end unless [: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 [: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 |
#ensure_algolia_index(name = nil) ⇒ Object
717 718 719 720 721 722 723 724 725 |
# File 'lib/algoliasearch-rails.rb', line 717 def ensure_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 |