Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

sql - How can I make pg_search faster?

I'm trying to implement pg_search in my rails application. I've got it working but searches are very slow, over 20 seconds. I have over 7 million records in my addresses table. Are there ways I can make it faster?

app/models/address.rb

class Address < ApplicationRecord
  include PgSearch::Model
  pg_search_scope :search_for, against: %i[address_line_1 address_line_2], using: %i[tsearch trigram]

UPDATE

I've added this index but it still seems to be just as slow

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • Have you profiling the search feature?
  • Is this 20 seconds the time it takes to query the database or include rendering the results in the application?

By default, pg_search uses a threshold of 0.3 for trigram searches. Higher numbers match more strictly and thus return fewer results. Lower numbers match more permissively, letting in more results.

pg_search_scope :search_for, 
  against: %i[address_line_1 address_line_2], 
  using: {
    tsearch: { dictionary: 'english' },
    trigram: { threshold: 0.5 } # increase the threshold
  }

I'm not sure but maybe you need to reindex your model:

rake pg_search:multisearch:rebuild[Address]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...