【问题标题】:How can I make pg_search faster?如何使 pg_search 更快?
【发布时间】:2021-01-23 01:00:14
【问题描述】:

我正在尝试在我的 rails 应用程序中实现 pg_search。我已经开始工作了,但搜索速度很慢,超过 20 秒。我的addresses 表中有超过700 万条记录。有什么方法可以让它更快?

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]

更新

我已经添加了这个索引,但它似乎仍然很慢

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

【问题讨论】:

  • 您是否考虑将三元组索引添加到表中? about.gitlab.com/blog/2016/03/18/…
  • @max 我已经在做 trigram 和 tsearch 了。我应该只用三元组吗?
  • 我需要手动创建索引还是由 pg_search 处理?

标签: sql ruby-on-rails ruby postgresql pg-search


【解决方案1】:
  • 您是否对搜索功能进行了概要分析?
  • 这 20 秒是查询数据库还是包括在应用程序中呈现结果所需的时间?

默认情况下,pg_search 使用阈值 0.3 进行三元组搜索。数字越大匹配越严格,因此返回的结果越少。较低的数字更容易匹配,从而产生更多结果。

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

我不确定,但也许您需要重新索引您的模型:

rake pg_search:multisearch:rebuild[Address]

【讨论】:

  • 那个 rake 任务对我不起作用zsh: no matches found: pg_search:multisearch:rebuild[Address。也许是因为我没有使用多搜索?
  • 增加你的threshold 有什么改善吗?
  • rails -T | grep pg_search 检查您的 pg search rake 任务是否可用?
  • 阈值没有帮助。任务在那里rails pg_search:multisearch:rebuild[model,schema]
  • 因为您使用的是 zsh,所以您应该使用 rake pg_search:multisearch:rebuild\[Address\] 转义方括号
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-24
  • 1970-01-01
  • 1970-01-01
  • 2023-01-14
  • 1970-01-01
相关资源
最近更新 更多