In my database I have table which has a column calleditems, this column hasjsonb type and almost every record has data like this one:
{"items": [{"id": "item-id", "sku": "some-sku", "quantity": 1, "master_sku": "some-master-sku"}]}I need to create a migration which addtype to every item, so it should looks like this:
{"items": [{"id": "item-id", "sku": "some-sku", "quantity": 1, "master_sku": "some-master-sku", "type": "product"}]}I must addtype to every record, and every record looks the same.The problem is, that i have about milion records in my table, and I cannot iterate every item and add newtype because it can take too long time and my deploy script may crash.
Guys, how can i do that in the simplest way?
- Will it always be
"type": "product"or will the value of"type"potentially have some other value? If so, where do you get it from?404– 4042018-10-23 16:23:50 +00:00CommentedOct 23, 2018 at 16:23 - @eurotrash it will be always
productDawid Sajdak– Dawid Sajdak2018-10-23 16:29:53 +00:00CommentedOct 23, 2018 at 16:29
1 Answer1
As long as the format/content is always more or less the same, the fastest way to do it would probably be as a string operation, something like this:
UPDATE your_tableSET your_field = REGEXP_REPLACE(your_field::TEXT, '\}(.+?)', ', "type": "product"}\1', 'g')::JSONBWHERE your_field IS NOT NULL;Example:https://www.db-fiddle.com/f/fsHoFKz9szpmV5aF4dt7r/1
This just checks for any} character which is followed by something (so we know it's not the final one from the "items" object, and replaces it with the missing key/value (and whatever character was following).
Of course this performs practically no validation, such as whether that key/value already exists. Where you want to be between performance and correctness depends on what you know about your data.
6 Comments
{"items":[<zero or more item objects here>]} and nothing further?Explore related questions
See similar questions with these tags.