4

我用来jsonb_set在 postgres 中部分更新我的 jsonb 对象。

这就是文档关于这个功能的说法。

 jsonb_set(
   target jsonb,           # The jsonb value you're amending.
   path text[],            # The path to the value you wish to add to or change, represented as a text array.
   new_value jsonb,        # The new object, key : value pair or array value(s) to add to or change.
   create_missing boolean  # An optional field that, if true (default), creates the value if the key doesn't already exist.
                           #   If false, the path must exist for the update to happen, or the value won't be updated.
 )

我认为create_missing(默认情况下是这样)会导致不存在的路径出现在我的 jsonb 对象中,但似乎这只适用于最后一步(例如,不是递归的)。

查询

UPDATE myScheme.myTable SET data = jsonb_set(data, $1, $2, true) where id = $3;

$1 = {foo,bar,baz}如果和我的电流将失败data = {foo: {}}

问题是:如何jsonb在 PostgreSQL v9.5+ 中通过递归创建不存在的子对象来更新我的对象?

4

1 回答 1

1

您可以使用类似的东西,而不是t放置表的名称:

UPDATE t SET data = jsonb_set(data,'{foo,bar}','{"baz":{"key1":{},"key2":[2],"key3":3,"key4":"val4"}}'::JSONB);

结果将是:

SELECT jsonb_pretty(data) FROM t;

          jsonb_pretty          
--------------------------------
 {                             +
     "foo": {                  +
         "bar": {              +
             "baz": {          +
                 "key1": {     +
                 },            +
                 "key2": [     +
                     2         +
                 ],            +
                 "key3": 3,    +
                 "key4": "val4"+
             }                 +
         }                     +
     }                         +
 }
(1 row)

使用这种方法(当所有结构都在new_value参数内定义时),您可以自由创建任何类型的嵌套元素(数组、嵌套文档字符串数值);另一方面,在path参数中执行此操作将非常棘手。

于 2016-02-27T00:15:01.233 回答