如何在PostgreSQL中使用“LIKE”查询jsonb列类型?

9
在 PostgreSQL 数据库中的 hstore 列中,我知道可以使用类似下面这样的“LIKE”查询来搜索包含特定字符串的名称(在 Ruby on Rails 中):
  Product.where("hstore_data -> 'author' LIKE '%billy%'")

我尝试对jsonb列类型使用这种方法,但是出现了以下错误:

ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: operator does not exist: jsonb ~~ unknown
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. : SELECT "products".* FROM "products" WHERE (jsonb_data -> 'author' LIKE '%billy%')

有没有一种方法可以正确地在jsonb列类型中使用“LIKE”?


可能会有帮助:https://dev59.com/hF0a5IYBdhLWcg3whJDW - Andrey Deineko
3
只需使用返回文本的运算符(http://www.postgresql.org/docs/current/static/functions-json.html),而不是json[b]:`->>`(可能需要括号,即`(jsonb_col ->> 'key') LIKE 'pattern'`,这取决于您使用的PostgreSQL版本)。 - pozs
Pozs,非常好的解决方案!非常感谢! :) 如果您想在下面添加它,我当然会接受您的答案。这是我使用的代码:Product.where("(jsonb_data ->> 'author') LIKE '%billy%'")非常感谢您的帮助。谢谢!! - sjsc
我知道答案已经被接受了,但是这个Gist可能会有所帮助。 - Anand Soni
1个回答

17

你可以尝试这个

希望你能

product.jsonb_data = {
      author: "billynando"
   }

然后

Product.where("jsonb_data ->> :key LIKE :value",
  key: "author", value: "%billy%"
)

更多在这里


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