Rails 4中使用PGSQL添加GIN或GiST类型的索引

44
在Rails中可以使用以下代码添加索引: add_index :table, :column_name, :using => 'btree' 在Rails 4中,是否可以使用PGSQL添加GINGiST索引,例如: add_index :students, :name, :using => 'gin' 如果需要使用schema.rb而不是structure.sql,则必须手动执行语句。
2个回答

58

在Rails 4中,您现在可以在迁移中执行以下操作:

add_index :products, :data, using: :gin

1
有关此事是否有文档?我在Stackoverflow上看到了一个类似的答案,但是在迁移时使用add_index:products,:data,using::gin会引发异常。 - Bill
11
出现了一个错误 PG::UndefinedObject: ERROR: data type character varying has no default operator class for access method "gin",并且这是在 Rails 4.2 上发生的。 - King'ori Maina
1
小修正,您还需要将配置作为属性给出,例如:'english': execute("CREATE INDEX some_name ON products USING gin(to_tsvector('english', 'data'))") - panmari
4
在Rails 5中,您可以使用opclass参数来使用默认的操作符类并避免该错误:add_index :products, :data, using: :gin, opclass: :gin_trgm_ops。详见https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_index。 - Scott Bartell
1
在此步骤之上的迁移中添加 enable_extension "btree_gin" - Haseeb A
显示剩余6条评论

35

哇!这个问题让我有几根头发变成灰色了。我正在使用Rails 4.2并尝试运行此迁移,但它给我与之前的人一样的错误。

PG::UndefinedObject: ERROR: data type character varying has no default

我发现您实际上仍然可以继续使用schema.rb,而无需使用config/application.rb。

config.active_record.schema_format = :sql

我缺少的一个重要的东西就是安装Postgres contrib模块。 我假设像gin和gist这样的功能已经启用了。 我从来没有注意到,但是模块显示在您的schema.rb文件中。 它们会像这样出现在顶部

ActiveRecord::Schema.define(version: 20151203234708) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"
  enable_extension "pg_trgm"
  enable_extension "fuzzystrmatch"
  enable_extension "btree_gin"
  enable_extension "btree_gist"

如果您未看到启用了btree_gin,那么您将无法使用该代码

add_index :products, :data, using: :gin

您可以通过运行迁移来安装任何模块。更改将在您的schema.rb中反映出来。

class InstallSomeContribPackages < ActiveRecord::Migration
  def up
    execute "CREATE EXTENSION IF NOT EXISTS btree_gin;"
    execute "CREATE EXTENSION IF NOT EXISTS btree_gist;"
  end

  def down
    execute "DROP EXTENSION IF EXISTS btree_gin;"
    execute "DROP EXTENSION IF EXISTS btree_gist;"
  end
end

这里是一个Postgres模块列表


13
您可以使用迁移语法在迁移过程中添加扩展程序 https://dev59.com/9GQn5IYBdhLWcg3wvZJ_ 例如,可以通过使用以下代码启用btree_gin扩展程序:enable_extension "btree_gin" - mmrobins
1
我还要指出的是,btree_gin 对于 PostgreSQL 9.4 来说已经足够了。 - denis.peplin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接