代码之家  ›  专栏  ›  技术社区  ›  bmalets TerryS

如何从postgres JSONB列中获取值?

  •  2
  • bmalets TerryS  · 技术社区  · 6 年前

    我有PostgreSQL 10.5数据库和Rails 5应用程序。

    # == Schema Information
    #
    # Table name: property_keys
    #
    #  id         :integer          not null, primary key
    #  name       :string
    #  created_at :datetime         not null
    #  updated_at :datetime         not null
    #  i18n_name  :jsonb
    #
    
    class PropertyKey < ApplicationRecord
      # Fields
      store :i18n_name, accessors: I18n.available_locales, coder: JSON
    end
    

    我的迁移:

    class LocalizeProperties < ActiveRecord::Migration[5.2]
      def up
        add_column :property_keys, :i18n_name, :jsonb
    
        PropertyKey.all.each do |property_key|
          [:en, :de, :ru].each do |locale_key|
            property_key.i18n_name[locale_key] = property_key.name
          end
    
          property_key.save!
        end
      end
    
      def down
        remove_column :property_keys, :i18n_name
      end
    end
    

    表名: property_keys . 字段列表:

    • 编号:bigint
    • i18n_名称:jsonb

    以下是对所有数据的请求:

    enter image description here

    我想知道所有的英文名字 "en" i18n_name 列)。

    这是一个请求:

    SELECT
        id,
        i18n_name,
        i18n_name->'en' AS en
    FROM property_keys;
    

    它什么也不回。

    这是一张截图:

    enter image description here

    我也试过用 ->>

    enter image description here

    我该如何更改我的请求以及 PostgreSQL operators 我应该用它来工作吗?

    检查JSONB列的长度:

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  3
  •   Kamil Gosciminski    6 年前

    -> ->> 运算符按预期方式按键检索json对象,或者在后一种情况下作为文本工作。

    我怀疑您所看到的真正问题是,您看到的数据实际上并不是存储在表中的数据,这就是为什么 i18_name->'en' 因为没有钥匙就不能用了 en

    为了能够确认我的写作,请运行下面的查询,看看您在字符串中看到的内容和存储在表中的内容的长度是否匹配。他们可能不会:

    select
      length(i18n_name::text) AS stored,
      length('{"en":"asdasdadad","de":"asdasdadad","ru":"asdasdadad"}') AS whatisee
    

    你能用它做什么?或者使用 bytea 数据类型转换或 UPDATE 此列中包含正确(所见)数据的行。

    英语 在jsonb字段中键入。

        2
  •  0
  •   Pablo Santa Cruz    6 年前

    the ->> operator :

    SELECT id,
           i18n_name,
           i18n_name->>'en' AS en
      FROM property_keys;