Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql migrating JSON to JSONB [duplicate]

In postgresql 9.4 the new JSONB was incorporated.

On a live DB in postgresql 9.3 I have a JSON column.

I want to migrate it to JSONB.

Assuming I migrated the DB first to 9.4 (using pg_upgrade). What do I do next?

like image 886
Boaz Avatar asked Jan 28 '15 20:01

Boaz


People also ask

Should I use JSON or Jsonb Postgres?

If duplicate keys are specified in the input, only the last value is kept. In general, most applications should prefer to store JSON data as jsonb , unless there are quite specialized needs, such as legacy assumptions about ordering of object keys. RFC 7159 specifies that JSON strings should be encoded in UTF8.

Is Jsonb faster than JSON?

Json processes input faster than jsonb as there is no conversion involved in this. Jsonb converts the JSON data into the binary form so it has slightly slower input due to the binary conversion overhead. There is no change in the Schema design while working with JSON.

Is Postgres Jsonb fast?

Significantly faster to process. Supports indexing (which can be a significant advantage, as we'll see later). simpler schema designs (replacing entity-attribute-value (EAV) tables with JSONB columns, which can be queried, indexed, and joined, allowing for performance improvements up until 1000X!)

Is Jsonb efficient?

Most applications should use JSONB for schemaless data. It stores parsed JSON in a binary format, so queries are efficient.


2 Answers

ALTER TABLE table_with_json   ALTER COLUMN my_json   SET DATA TYPE jsonb   USING my_json::jsonb; 
like image 152
Marth Avatar answered Sep 21 '22 11:09

Marth


In the context of Rails, here is an ActiveRecord migration alternative:

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 

I don't know how this compares to the accepted answer performance-wise, 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.

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.

like image 38
Alexander Popov Avatar answered Sep 24 '22 11:09

Alexander Popov