9

我正在关注 Ryan Bates关于在 Rails 中使用内置 PostgresQL 全文搜索的优秀教程。我目前正在使用 pg_search gem un-indexed 没问题,但我需要提高性能。我正在使用指定了“英语”字典的 tsvector。

我正在使用 PostgreSQL 版本 9.1.4

根据 Ryan 的指示,我已经使用此代码运行了一个新的迁移,指定了我想要创建的两个新索引。首先是架构:

create_table "references", :force => true do |t|
  t.string   "title"
  t.string   "type"
  t.datetime "created_at",         :null => false
  t.datetime "updated_at",         :null => false
  t.string   "public_url"
  t.string   "content_type"
  t.integer  "file_size"
  t.text     "overview"
  t.text     "body"
  t.text     "full_text"
  t.integer  "folder_id"
end

我的迁移如下所示:

def up
  execute "create index references_title on references using gin(to_tsvector('english', title))"
  execute "create index references_full_text on references using gin(to_tsvector('english', full_text))"
end

def down
  execute "drop index references_title"
  execute "drop index references_full_text"
end

我还继续并取消了 application.rb 中的 :sql 选项的注释

config.active_record.schema_format = :sql

我继续收到相同的 rake aborted 错误:

==  AddSearchIndexesToReferences: migrating ===================================
-- execute("CREATE INDEX references_title on references using gin(to_tsvector('english',    title))")
rake aborted!
An error has occurred, this and all later migrations canceled:

PG::Error: ERROR:  syntax error at or near "references"
LINE 1: CREATE INDEX references_title on references using gin(to_tsv...
                                     ^
: CREATE INDEX references_title on references using gin(to_tsvector('english', title))
4

1 回答 1

7

REFERENCES 是与外键一起使用的关键字,因此除非双引号,否则不能将其用作表名:

def up
  execute %q{create index references_title on "references" using gin(to_tsvector('english', title))}
  execute %q{create index references_full_text on "references" using gin(to_tsvector('english', full_text))}
end

您还必须在 SQL 代码片段中使用该表名的任何地方用双引号引起来。如果 ActiveRecord 正在构建 SQL,它将为您进行引用。如果您希望在很多 SQL 片段中使用表名,那么我建议您重命名表,这样您就不必关心引用问题。

于 2012-11-02T04:05:07.773 回答