如何将ActiveRecord模型属性从json迁移到jsonb? [英] How do I migrate an ActiveRecord model attribute from json to jsonb?
问题描述
迁移应该是什么样的?我想利用jsonb数组查询技术.
What should the migration look like? I would like to take advantage of the jsonb array querying technique.
推荐答案
我会这样写迁移:
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条记录的表上对此进行了测试,每条记录具有4个json
列,迁移该表花了我大约一分钟的时间.当然,我想这取决于json
结构的复杂程度.
I don't know how this compares performance-wise to other solutions, but I tested this on a table with 120,000 records, each record having four json
columns and it took me about a minute to migrate that table. Of course, I guess it depends on how complex the json
structure is.
此外,请注意,如果您现有的记录的默认值是{}
,则必须添加到上述语句default: {}
,因为否则您将拥有jsonb
列,但是默认值将保留为'{}'::json
.
Also, notice that if your existing records have a default value of {}
, you have to add to the above statements default: {}
, because otherwise you'll have jsonb
columns, but the default value will remain as '{}'::json
.
这篇关于如何将ActiveRecord模型属性从json迁移到jsonb?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!