在 postgresql 9.4 中,新的 JSONB 已经被纳入。在 postgresql 9.3 的实时数据库中,我有一个 JSON 列。我想将其迁移到 JSONB。假设我先使用 pg_upgrade 将数据库迁移到 9.4,接下来该怎么做?
ALTER TABLE table_with_json
ALTER COLUMN my_json
SET DATA TYPE jsonb
USING my_json::jsonb;
在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
我不知道这种方法在性能方面与被接受的答案相比如何,但是我在一个有120,000个记录的表上测试了一下,每个记录都有四个json
列,迁移该表花费了大约一分钟的时间。当然,我猜这取决于json
结构的复杂程度。
另外,请注意,如果您现有的记录具有默认值{}
,则必须在上述语句中添加default: {}
,否则您将拥有jsonb
列,但默认值仍将保持为'{}'::json
。
reversible do ... end
而不是def up ... end
和def down ... end
? - OzBarrychange
与reversible
结合的方式是“推荐”的方式。请参阅http://edgeguides.rubyonrails.org/active_record_migrations.html#using-the-change-method,特别是3.8使用更改方法,3.9使用可逆性,3.10使用上/下方法。 - Alexander Popov
ActiveRecord::Base.connection.execute('ALTER TABLE table_with_json ALTER COLUMN my_json SET DATA TYPE jsonb USING my_json::jsonb')
- Miguel Peniche