postgresql将JSON迁移到JSONB

Boa*_*oaz 47 postgresql jsonb

在postgresql 9.4中,新的JSONB被合并.

在postgresql 9.3中的实时数据库中,我有一个JSON列.

我想将其迁移到JSONB.

假设我首先将数据库迁移到9.4(使用pg_upgrade).接下来我该怎么办?

Mar*_*rth 80

ALTER TABLE table_with_json
  ALTER COLUMN my_json
  SET DATA TYPE jsonb
  USING my_json::jsonb;
Run Code Online (Sandbox Code Playgroud)


Ale*_*pov 31

在Rails的上下文中,这是一个ActiveRecord迁移替代方案:

def change
  reversible do |dir|
    dir.up { change_column :models, :attribute, 'jsonb USING CAST(attribute AS jsonb)' }
    dir.down { change_column :models, :attribute, 'json USING CAST(attribute AS json)' }
  end
end
Run Code Online (Sandbox Code Playgroud)

我不知道这与性能方面的接受答案相比如何,但我在一张有120 000条记录的表上测试了这个,每条记录有四json列,我花了大约一分钟来迁移该表.当然,我想这取决于json结构的复杂程度.

另外,请注意,如果现有记录的默认值为{},则必须添加到上述语句中default: {},否则您将拥有jsonb列,但默认值将保持为'{}'::json.

  • @OzBarry 因为惯例,并且因为将 `change` 与 `reversible` 结合使用是“推荐”的方式。看看 http://edgeguides.rubyonrails.org/active_record_migrations.html#using-the-change-method,特别是 3.8 Using the change Method, 3.9 Using the reversible, 3.10 Using the up/down Methods (2认同)