【问题标题】:how to query json data in text field rails postgresql如何在文本字段rails postgresql中查询json数据
【发布时间】:2013-11-01 04:16:09
【问题描述】:

我有一个带有data type text的数据库表列(collection)

我在collection中插入了json数据

这是我的 json 数据

{"name":"test","age":"25","country":"xxx"}

但是现在我如何查询这个 json 数据。有没有如下选项

User.where(collection: :name) # Here name denotes test

【问题讨论】:

  • 你发现了吗?

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 rails-postgresql


【解决方案1】:

由于 JSON 是一个字符串,您只能使用 SQLite/MySQL(或任何其他数据库)进行字符串比较。另外,尽量保持数据类型为 binary

您可以执行:LIKE 操作以在您存储的 JSON 字符串中出现子字符串。

您进行的上述比较将不起作用,因为它仅用于在集合列中搜索名称,而您已在该列中存储了整个 JSON 字符串。

【讨论】:

    【解决方案2】:

    您可能需要考虑使用 json 数据类型

    https://github.com/diogob/activerecord-postgres-hstore

    如果您使用的是 rails 4,则不需要此 gem,但文档仍然适用。

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 2015-04-27
      • 2017-06-13
      相关资源
      最近更新 更多