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
- #meilisearch(options = {}, &block) ⇒ Object
- #ms_clear_index!(synchronous = false) ⇒ Object
- #ms_entries_for(document:, synchronous:) ⇒ Object
- #ms_index(name = nil) ⇒ Object
- #ms_index!(document, synchronous = false) ⇒ Object
- #ms_index_documents(documents, synchronous = false) ⇒ Object
- #ms_index_uid(options = nil) ⇒ Object
- #ms_must_reindex?(document) ⇒ Boolean
- #ms_primary_key_method(options = nil) ⇒ Object
- #ms_raw_search(q, params = {}) ⇒ Object
- #ms_reindex!(batch_size = MeiliSearch::Rails::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) ⇒ Object
- #ms_remove_from_index!(document, synchronous = false) ⇒ Object
- #ms_search(query, params = {}) ⇒ Object
- #ms_set_settings(synchronous = false) ⇒ Object
- #ms_without_auto_index(&block) ⇒ Object
- #ms_without_auto_index_scope ⇒ Object
- #ms_without_auto_index_scope=(value) ⇒ Object
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( = {}, &block) self.meilisearch_settings = IndexSettings.new(, &block) self. = { type: model_name.to_s.constantize, per_page: meilisearch_settings.get_setting(:hitsPerPage) || 20, page: 1 }.merge() attr_accessor :formatted if .key?(:per_environment) raise BadConfiguration, ':per_environment option should be defined globally on MeiliSearch::Rails.configuration block.' end if [: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 [:enqueue] raise ArgumentError, 'Cannot use a enqueue if the `synchronous` option is set' if [:synchronous] proc = if [:enqueue] == true proc do |record, remove| if remove MSCleanUpJob.perform_later(record.ms_entries) else MSJob.perform_later(record, 'ms_index!') end end elsif [:enqueue].respond_to?(:call) [:enqueue] elsif [:enqueue].is_a?(Symbol) proc { |record, remove| send([:enqueue], record, remove) } else raise ArgumentError, "Invalid `enqueue` option: #{[:enqueue]}" end [:enqueue] = proc do |record, remove| proc.call(record, remove) unless ms_without_auto_index_scope end end unless [: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 [: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 |, settings| next if ms_indexing_disabled?() index = ms_ensure_init(, settings) synchronous || [: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
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 |, settings| { synchronous: synchronous || [:synchronous], index_uid: ms_index_uid(), primary_key: primary_key }.with_indifferent_access unless ms_indexing_disabled?() 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 |, settings| next if ms_indexing_disabled?() primary_key = ms_primary_key_of(document, ) index = ms_ensure_init(, settings) if Utilities.indexable?(document, ) raise ArgumentError, 'Cannot index a record without a primary key' if primary_key.blank? doc = settings.get_attributes(document) doc = doc.merge ms_pk() => primary_key if synchronous || [:synchronous] index.add_documents(doc).await else index.add_documents(doc) end elsif ms_conditional_index?() && primary_key.present? # remove non-indexable documents if synchronous || [: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 |, settings| next if ms_indexing_disabled?() index = ms_ensure_init(, settings) task = index.add_documents(documents.map { |d| settings.get_attributes(d).merge ms_pk() => ms_primary_key_of(d, ) }) index.wait_for_task(task['taskUid']) if synchronous || [: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( = nil) ||= ||= MeiliSearch::Rails.configuration name = [:index_uid] || model_name.to_s.gsub('::', '_') name = "#{name}_#{::Rails.env}" if [:per_environment] name end |
#ms_must_reindex?(document) ⇒ 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 |, settings| next if ms_indexing_disabled?() return true if ms_primary_key_changed?(document, ) 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 [[:if], [: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( = nil) ||= [:primary_key] || [: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 |, settings| next if ms_indexing_disabled?() index = ms_ensure_init(, settings) last_task = nil ms_find_in_batches(batch_size) do |group| if ms_conditional_index?() # delete non-indexable documents ids = group.select { |d| !Utilities.indexable?(d, ) }.map { |d| ms_primary_key_of(d, ) } index.delete_documents(ids.select(&:present?)) # select only indexable documents group = group.select { |d| Utilities.indexable?(d, ) } end documents = group.map do |d| attributes = settings.get_attributes(d) attributes = attributes.to_hash unless attributes.instance_of?(Hash) attributes.merge ms_pk() => ms_primary_key_of(d, ) end last_task = index.add_documents(documents) end index.wait_for_task(last_task['taskUid']) if last_task && (synchronous || [:synchronous]) end nil end |
#ms_remove_from_index!(document, synchronous = false) ⇒ Object
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 |, settings| next if ms_indexing_disabled?() index = ms_ensure_init(, settings) if synchronous || [: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 [:type].columns.map(&:to_s).exclude?(condition_key.to_s) else [:type].columns.map(&:name).map(&:to_s).exclude?(condition_key.to_s) end condition_key = [: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().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 = [: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().to_s].to_s] if o o.formatted = hit['_formatted'] o end end.compact res = Pagination.create(results, json['totalHits'], .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 |, settings| if [:primary_settings] && [:inherit] primary = [:primary_settings].to_settings final_settings = primary.merge(settings.to_settings) else final_settings = settings.to_settings end index = SafeIndex.new(ms_index_uid(), true, ) 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_scope ⇒ Object
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 |