我尝试使用pg_search的函数:trigram来查找与我在数据库中存储的名称相似的名称。不幸的是,由于我还在学习SQL,这个错误对我来说有点太多了。
我的卡片型号:
class Card < ApplicationRecord
include PgSearch
pg_search_scope :spelled_like,
:against => :name,
:using => :trigram
end
我尝试在rails C中做什么:
2.4.1 :005 > c = "Timeslream Navigator"
=> "Timeslream Navigator"
2.4.1 :006 > Card.spelled_like(c)
Card Load (1.9ms) SELECT "cards".* FROM "cards" INNER JOIN (SELECT "cards"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("cards"."name"::text, ''))), (to_tsquery('simple', ''' ' || 'Timeslream' || ' ''') && to_tsquery('simple', ''' ' || 'Navigator' || ' ''')), 0)) AS rank FROM "cards" WHERE (((coalesce("cards"."name"::text, '')) % 'Timeslream Navigator'))) AS pg_search_6ac9a32c0ca8e84e5bf0c3 ON "cards"."id" = pg_search_6ac9a32c0ca8e84e5bf0c3.pg_search_id ORDER BY pg_search_6ac9a32c0ca8e84e5bf0c3.rank DESC, "cards"."id" ASC LIMIT $1 [["LIMIT", 11]]
ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: operator does not exist: text % unknown
LINE 1: ...rds" WHERE (((coalesce("cards"."name"::text, '')) % 'Timeslr...
澄清 - 答案应该是Times TR eam Navigator(它确实存在于我的数据库中)
Postgres给了我一个提示:HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "cards".* FROM "cards" INNER JOIN (SELECT "cards"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("cards"."name"::text, ''))), (to_tsquery('simple', ''' ' || 'Timeslream' || ' ''') && to_tsquery('simple', ''' ' || 'Navigator' || ' ''')), 0)) AS rank FROM "cards" WHERE (((coalesce("cards"."name"::text, '')) % 'Timeslream Navigator'))) AS pg_search_6ac9a32c0ca8e84e5bf0c3 ON "cards"."id" = pg_search_6ac9a32c0ca8e84e5bf0c3.pg_search_id ORDER BY pg_search_6ac9a32c0ca8e84e5bf0c3.rank DESC, "cards"."id" ASC LIMIT $1
但是当我试着打电话的时候,我得到了另一个在这一点上没有告诉我的错误:
SyntaxError: (irb):7: syntax error, unexpected tCONSTANT, expecting end-of-input
"cards".* FROM "cards" INNER JOIN (SELECT "cards"."id" AS
^
卡架构:
ActiveRecord::Schema.define(version: 2018_05_31_102526) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
enable_extension "pg_trgm"
create_table "cards", force: :cascade do |t|
t.string "name"
t.string "set"
t.float "price"
t.string "image"
t.string "type_line"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
有什么想法吗?
答案 0 :(得分:0)
回答我自己的问题:
以下是允许我修复问题并开始享受trigram功能的迁移代码段:
class InstallPgTrgmContribPackage < ActiveRecord::Migration[5.2]
def up
execute "CREATE EXTENSION pg_trgm;"
end
def down
execute "DROP EXTENSION pg_trgm;"
end
end
答案 1 :(得分:0)
我的问题有点不同。即使我的扩展已经安装,我也会在 AWS 环境中遇到这个错误,而不是较低的环境。所以我放弃了扩展并重新创建了它。
那行得通。这是我的错误:
PG::UndefinedFunction:错误:操作符不存在:未知 <% text 由 pg_search gem 使用 trigrams 引起。
或者你可以禁用使用三元组,但我想保留它们,所以我一直在研究