【问题标题】:Migration of trigram search in RailsRails 中三元组搜索的迁移
【发布时间】:2015-03-17 12:09:00
【问题描述】:

我有一个迁移:

class AddGinIndexToContacts < ActiveRecord::Migration
  def up
    execute("CREATE INDEX contacts_search_idx ON contacts USING gin (first_name gin_trgm_ops, last_name gin_trgm_ops, name gin_trgm_ops)")
  end

  def down
    execute("DROP INDEX contacts_search_idx")
  end
end

它在schema.rb中生成此代码:

add_index "contacts", ["first_name", "last_name", "name"], name: "contacts_search_idx", using: :gin

之后,当我执行rake db:schema:load 时,它会生成错误的sql:

CREATE  INDEX  "contacts_search_idx" ON "contacts" USING gin ("first_name", "last_name", "name")

首先,它说:

错误:数据类型字符变化没有默认操作符类 访问方法“gin”

其次,还有gin_trgm_ops丢失。

如何让它发挥作用?

Rails 4.2

【问题讨论】:

    标签: ruby-on-rails ruby migration pg-search trigram


    【解决方案1】:

    您可以使用 order 参数来定义操作符类。

    add_index "contacts", ["first_name", "last_name", "name"], name: "contacts_search_idx", using: :gin, order: {first_name: :gin_trgm_ops, last_name: :gin_trgm_ops, name: :gin_trgm_ops}
    

    在此处找到此解决方案:http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index#1553-Adding-index-with-other-operator-classes-PostgreSQL-

    【讨论】:

    • 谢谢,但是没有gin_trgm_ops还是会生成错误的schema.rb
    【解决方案2】:

    您现在可以使用opclass 选项:

    add_index :contacts, [:first_name, :last_name, :name], name: "contacts_search_idx", using: :gin, opclass: { first_name: :gin_trgm_ops, last_name: :gin_trgm_ops, name: :gin_trgm_ops }
    

    【讨论】:

    • 它向我显示了这样的错误'未知密钥::opclass。有效键是::unique、:order、:name、:where、:length、:internal、:using、:algorithm、:type'
    • 注意:opclass 选项需要 Rails 5.2+
    【解决方案3】:

    不幸的是,除非将架构更改为 sql,否则无法解决此问题。几个链接:

    Rails and Postgres Hstore: Can you add an index in a migration?

    Why does add_index using 'gin' create a 'btree' index instead?

    一旦我将架构格式更改为 sql,它就可以正常工作了。

    【讨论】:

    • 您应该包含链接中的重要信息,并将它们添加为参考。请查看帮助中心
    【解决方案4】:

    您需要安装 btree_gin Postgres extension 才能使用 GIN 索引。

    只需将enable_extension('btree_gin') 添加到迁移中,就可以正常工作了。

    【讨论】:

      猜你喜欢
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      相关资源
      最近更新 更多