我在我的应用程序中使用 pg_search gem 来实现搜索功能。在添加 pg_search 之前,我已经在我的 Postgres 数据库中的一个表中添加了 130,000 行数据。现在,当我运行搜索时,它需要的时间太长,即大约 16000 毫秒。
我正在关注 PostgreSQL 中的 Railscasts Episode343 全文搜索
这是我的 pg_search 模型中的代码:
include PgSearch
pg_search_scope :search, :against => [:applicant, :generic_name, :trade_name, :description],
using: {tsearch: {dictionary: "english"}},
ignoring: :accents
def self.text_search(query)
if query.present?
rank = <<-RANK
ts_rank(to_tsvector(generic_name), plainto_tsquery(#{sanitize(query)})) +
ts_rank(to_tsvector(trade_name), plainto_tsquery(#{sanitize(query)}))+
ts_rank(to_tsvector(description), plainto_tsquery(#{sanitize(query)})) +
ts_rank(to_tsvector(applicant), plainto_tsquery(#{sanitize(query)}))
RANK
where("generic_name @@ :q or trade_name @@ :q or description @@ :q or applicant @@ :q", q: query)
else
all
end
end
我的服务器输出如下:
Parameters: {"utf8"=>"✓", "query"=>"intraocular lenses"}
Parameters: {"utf8"=>"✓", "query"=>"intraocular lenses"}
Rendered layouts/_search.html.erb (1.5ms)
Rendered layouts/_search.html.erb (1.5ms)
Rendered medicaldevices/index.html.erb within layouts/application (16535.9ms)
Rendered medicaldevices/index.html.erb within layouts/application (16535.9ms)
Rendered layouts/_header.html.erb (1.8ms)
Rendered layouts/_header.html.erb (1.8ms)
Rendered layouts/_footer.html.erb (0.1ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 16574ms (Views: 60.3ms | ActiveRecord: 16510.7ms)
Completed 200 OK in 16574ms (Views: 60.3ms | ActiveRecord: 16510.7ms)
这是我用于索引的迁移文件
class AddSearchIndexToMedicaldevices < ActiveRecord::Migration
def up
execute "create index generic_name on medicaldevices using gin(to_tsvector('english', generic_name))"
execute "create index trade_name on medicaldevices using gin(to_tsvector('english', trade_name))"
execute "create index description on medicaldevices using gin(to_tsvector('english', description))"
execute "create index applicant on medicaldevices using gin(to_tsvector('english', applicant))"
end
def down
execute "drop index generic_name"
execute "drop index trade_name"
execute "drop index description"
execute "drop index applicant"
end
end