jsob内部根据自身值递增计数器

问题描述 投票:0回答:1

我有一个示例表来演示问题。

create table myteble  (
    id   serial primary key ,
    metadata  jsonb
--   other fields
--   ......
)

metadata
是一个 jsonb 列,它可能并且很可能包含半任意数据的某些部分。我想要在更新期间执行的操作是,在该列数据的顶层创建类似
{api_cnt: {'some_api_name': 1, 'other_api_name': 2, ...}
的内容,并在每次更新时增加此计数器 (+1)(即 1+1 -> 2、2+1 -> 3 等) 。重要的是,该键的
api_cnt
或(和)嵌套键(例如
some_api_name
)可能事先不存在。

我能到达的最接近的地方如下:

update myteble
set metadata = jsonb_set(metadata, '{api_cnt}', '2', true)
where id = 1;

但我不知道如何创建嵌套记录

api_cnt -> some_api_name
以及如何基于自身增加值(new_value = old_value + 1)

示例 1,其中密钥事先不存在:

--PSEUDOCODE
id=1, metadata = {'inner something': [1,2,3,4,5]}
update myteble set ...{api_cnt: {'some_api_name': increment+1, 'other_api_name': increment+1} ... where id = 1
RESULT -- {'inner something': [1,2,3,4,5], {api_cnt: {'some_api_name': 1, 'other_api_name': 1}}

示例 2 中密钥确实存在:

--PSEUDOCODE
id=1, metadata = {'inner something': [1,2,3,4,5], {api_cnt: {'some_api_name': 1, 'other_api_name': 8}}
update myteble set ...{api_cnt: {'some_api_name': increment+1, 'other_api_name': increment+1} ... where id = 1
RESULT -- {'inner something': [1,2,3,4,5], {api_cnt: {'some_api_name': 2, 'other_api_name': 9}}
postgresql postgresql-12
1个回答
0
投票
UPDATE myteble SET metadata =
  jsonb_set(
        COALESCE(metadata, '{}'),
        array['api_cnt'],
        jsonb_set(
                COALESCE("metadata"->'api_cnt', '{}'), array['api_one'],(COALESCE(metadata->'api_cnt'->'api_one','0')::int + 1)::text::jsonb
        )
  ) WHERE "id" = 1
© www.soinside.com 2019 - 2024. All rights reserved.