简体   繁体   中英

how update dynamically attribute in jsonb data column with postgres

Hi i have this structure in my column jsonb in postgres

offer_profile_id (PK, FK): bigint
website_id (PK, FK):    bigint
offer_profile_website_detail: jsonb {
    display_vat_included: boolean
    available_services: [{
        service_id: long
        included_by_default: boolean
        extra_service : boolean
    }]
}

I'm trying to add a new attribute named is_active: boolean inside the available_services. The problem is that the table named "offer_profile", full of data with many rows and which can take a long time to write the insert into "offer_profile" VALUES script.

I'm looking for a dynamic way to update my table.

Regards

You can use jsonb_set function available in Postgresql. Here is the link . Below is the non-tested version of the code, tweak the path as needed.

UPDATE table_name
SET offer_profile_website_detail = jsonb_set(
offer_profile_website_detail, '{available_services, 0, is_active}', 'true', true)

Test:

create table test
(
    offer_profile_id             bigint,
    website_id                   bigint,
    offer_profile_website_detail jsonb
)

insert into test values (1, 1, '{"display_vat_included": true, "available_services": [{"service_id": 123}]}');
insert into test values (2, 2, '{"display_vat_included": false, "available_services": [{"service_id": 345}]}');
insert into test values (3, 3, '{"display_vat_included": false, "available_services": [{"service_id": 567}]}');

SELECT offer_profile_id, offer_profile_website_detail,
jsonb_set(offer_profile_website_detail, '{available_services, 0, is_active}', 'true', true)
from test

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM