Casecommons / pg_search

pg_search builds ActiveRecord named scopes that take advantage of PostgreSQL’s full text search

Home Page:http://www.casebook.net

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to rebuild indexes when not using mutlisearchable?

antarr opened this issue · comments

I'm trying to use pg_search in my addresses table. I already have several million records in the table. I'm trying to figure out how to rebuild the indexes. I tried rake pg_search:multisearch:rebuild\[Address\] but I get this error

PgSearch::Multisearch::ModelNotMultisearchable: Address is not multisearchable.

I tried adding a job that does uses update_pg_search_document but I get this error

NoMethodError: undefined method `update_pg_search_document' for #<Address:0x00007f94c250fc18> Did you mean? updated_at_previous_change

Is there a way to update my indexes. I tried touching every record like in the commented code in my job but that doesn't seam to work. Searching still takes over 30 seconds.

reindex_addresses_worker.rb

class ReindexAddressesWorker < ApplicationWorker
  sidekiq_options queue: 'imports'

  def perform
    # Address.in_batches.each do |batch|
    #   Parallel.map(batch) do |address|
    #     address.address_line_1 = address.address_line_1.squish
    #     address.address_line_2 = address.address_line_2.squish if address.address_line_2.present?
    #     address.save
    #   end
    # end
    PgSearch::Document.delete_all(searchable_type: 'Address')
      Address.in_batches.each do |batch|
        batch.each(&:update_pg_search_document)
      end
  end
end

trigram index migration

class IndexAddressesOnAddressLine1 < ActiveRecord::Migration[6.1]
  # An index can be created concurrently only outside of a transaction.
  disable_ddl_transaction!

  def up
    execute <<~SQL
CREATE INDEX pg_search_addresses_on_fields ON addresses USING gin(coalesce(address_line_1, address_line_2, ''::text) gin_trgm_ops)
SQL
  end

  def down
    execute <<~SQL
DELETE INDEX pg_search_addresses_on_fields
    SQL
  end
end

address.rb

class Address < ApplicationRecord
  include PgSearch::Model
  pg_search_scope :search_for,
                  against: %i[address_line_1 address_line_2],
                  using: {
                    tsearch: { dictionary: 'english' },
                    trigram: { threshold: 0.5 }
                  } 

@antarr there's no index to rebuild when not using multisearchable, it uses FTS directly on the addresses table