I have a table, let's call it my_table with the following structure
ID | data
____________
uuid | jsonb
The data in the jsonb field is an object structured in the following way:
{
"A":[
{"index":"1", "index2":"50"},
{"index":"2"},
{"index":"3"},
{"index":"4", "index2":"10"},
],
"B": "something",
"C": "something_else",
}
I want to add an "index2" key to each object within "A" with a value of null, but only if that key does not already exist.
This is the result I want:
{
"A":[
{"index":"1", "index2":"50"},
{"index":"2", "index2":null},
{"index":"3", "index2":null},
{"index":"4", "index2":"10"},
],
"B": "something",
"C": "something_else",
}
I have the following query that works but is extraordinarily slow. After running EXPLAIN on my query, it shows that for every row, it is scanning the entire table (essentially n^2 complexity).
Here's the current query:
UPDATE my_table
SET data = JSONB_SET(my_table.data, '{A}', (
SELECT JSONB_AGG( element || '{"index2": null}' )
FROM JSONB_ARRAY_ELEMENTS(my_table.data -> 'A') element
))
FROM my_table as my_table_2, JSONB_ARRAY_ELEMENTS(
my_table_2.data -> 'A'
) as element
WHERE jsonb_array_length(my_table.data -> 'A') > 0
AND element#>'{index2}' IS NULL;
How can I speed this up to get to a linear run time?