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_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_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
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
# File 'lib/meilisearch-rails.rb', line 326 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
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 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 |
# File 'lib/meilisearch-rails.rb', line 344 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| MSJob.perform_later(record, remove ? 'ms_remove_from_index!' : 'ms_index!') 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 { |searchable| searchable.ms_enqueue_remove_from_index!(ms_synchronous?) } end end warn_searchable_missing_attributes end |
#ms_clear_index!(synchronous = false) ⇒ Object
576 577 578 579 580 581 582 583 584 585 |
# File 'lib/meilisearch-rails.rb', line 576 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! : index.delete_all_documents @ms_indexes[MeiliSearch::Rails.active?][settings] = nil end nil end |
#ms_index(name = nil) ⇒ Object
684 685 686 687 688 689 690 691 692 |
# File 'lib/meilisearch-rails.rb', line 684 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
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 551 552 553 554 555 |
# File 'lib/meilisearch-rails.rb', line 526 def ms_index!(document, synchronous = false) return if ms_without_auto_index_scope ms_configurations.each 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) 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) else index.delete_document(primary_key) end end end nil end |
#ms_index_documents(documents, synchronous = false) ⇒ Object
516 517 518 519 520 521 522 523 524 |
# File 'lib/meilisearch-rails.rb', line 516 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
694 695 696 697 698 699 700 701 702 |
# File 'lib/meilisearch-rails.rb', line 694 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
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 |
# File 'lib/meilisearch-rails.rb', line 704 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_raw_search(q, params = {}) ⇒ Object
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 |
# File 'lib/meilisearch-rails.rb', line 587 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
472 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 |
# File 'lib/meilisearch-rails.rb', line 472 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
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 |
# File 'lib/meilisearch-rails.rb', line 557 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) else index.delete_document(primary_key) end end nil end |
#ms_search(query, params = {}) ⇒ Object
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 |
# File 'lib/meilisearch-rails.rb', line 625 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
501 502 503 504 505 506 507 508 509 510 511 512 513 514 |
# File 'lib/meilisearch-rails.rb', line 501 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
455 456 457 458 459 460 461 462 |
# File 'lib/meilisearch-rails.rb', line 455 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
468 469 470 |
# File 'lib/meilisearch-rails.rb', line 468 def ms_without_auto_index_scope Thread.current["ms_without_auto_index_scope_for_#{model_name}"] end |
#ms_without_auto_index_scope=(value) ⇒ Object
464 465 466 |
# File 'lib/meilisearch-rails.rb', line 464 def ms_without_auto_index_scope=(value) Thread.current["ms_without_auto_index_scope_for_#{model_name}"] = value end |