将多个路径项添加到 PostgreSQL 中的 JSONB 字段

Adding more than one path item to a JSONB field in PostgreSQL

我在 table 中有一个 jsonb 字段,我想向其中添加数据。该记录存在,但我不知道 json 结构是否存在。

UPDATE 
    car 
SET 
    features = jsonb_set(
        features, 
        '{exterior,colour}', 
        to_jsonb('red'::text)
    ) 
WHERE 
    id = '81782'

PostgreSQL 文档说明如下:

Note: All the items of the path parameter of jsonb_set must be present in the target, unless create_missing is true, in which case all but the last item must be present.

但如果没有,我真的很想创建整个路径。当然,我可以先添加第一层,然后再添加下一层,但我宁愿只使用一个查询。

有什么解决方法吗?

在这种情况下,可以使用 case 语句和 ? 运算符来检查 top-level 键是否存在。

UPDATE语句可以写成AS

UPDATE car 
SET 
  features = 
    CASE
      WHEN features ? 'exterior' THEN
        JSONB_SET(features, '{exterior, color}', TO_JSONB('red'::TEXT))
      ELSE JSONB_SET(features, '{exterior}', '{"color": "red"}'::JSONB)
    END
WHERE id = '81782';