如何修改 PostgreSQL JSONB 数据类型内的单个属性值?

2024-01-02

如何修改 PostgreSQL JSONB 数据类型中的单个字段?

假设我有一张名为“动物”的表,如下所示:

id       info
------------------------------------------------------------
49493   {"habit1":"fly","habit2":"dive","location":"SONOMA NARITE"}

我想简单地更改位置属性的值(例如,将文本更改为大写或小写)。所以更新后的结果是

    id       info
------------------------------------------------------------
49493   {"habit1":"fly","habit2":"dive","location":"sonoma narite"}

我在下面尝试过,但它不起作用

update animal set info=jsonb_set(info, '{location}', LOWER(info->>'location'), true) where id='49493';
----------------------------------
ERROR:  function jsonb_set(jsonb, unknown, text, boolean) does not exist
LINE 7: update animal set info=jsonb_set(info, '{con...
                                           ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
********** Error **********

ERROR: function jsonb_set(jsonb, unknown, text, boolean) does not exist

如果我只是知道更新后的值是什么,那么我可以使用这个:

update animal set info=jsonb_set(info, '{location}', '"sonoma narite"', true) where id='49493';

但是,如果文本值未知,而我们只想做一些简单的操作,例如追加、前置、大写/小写,我无法简单地找到答案。

令我惊讶的是,jsonb set 函数没有提供这样一个简单的操作,即仅尝试更新 jsonb 内文本属性的大小写。

有人可以帮忙吗?


第三个参数jsonb_set()应该是jsonb类型。问题在于将文本字符串转换为 jsonb 字符串时,您需要一个用双引号引起来的字符串。您可以使用concat() or format():

update animal
set info = 
    jsonb_set(info, '{location}', concat('"', lower(info->>'location'), '"')::jsonb, true) 
--  jsonb_set(info, '{location}', format('"%s"', lower(info->>'location'))::jsonb, true) 
where id='49493'
returning *;

  id   |                               info                               
-------+------------------------------------------------------------------
 49493 | {"habit1": "fly", "habit2": "dive", "location": "sonoma narite"}
(1 row)

In Postgres 9.4您应该使用 jsonb_each_text() 取消嵌套 json 列,聚合键和值并动态修改正确的值,最后构建一个 json 对象:

update animal a
set info = u.info
from (
    select id, json_object(
        array_agg(key), 
        array_agg(
            case key when 'location' then lower(value)
            else value end))::jsonb as info
    from animal,
    lateral jsonb_each_text(info) 
    group by 1
    ) u
where u.id = a.id
and a.id = 49493;

如果您可以创建函数,这个解决方案可能会更令人愉快:

create or replace function update_info(info jsonb)
returns jsonb language sql as $$
    select json_object(
        array_agg(key), 
        array_agg(
            case key when 'location' then lower(value)
            else value end))::jsonb
    from jsonb_each_text(info)
$$

update animal
set info = update_info(info)
where id = 49493;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何修改 PostgreSQL JSONB 数据类型内的单个属性值? 的相关文章

随机推荐