2016-02-26 53 views
2

我使用jsonb_set來部分更新postgres中的jsonb對象。遞歸更新PostgreSQL v9.5中的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(默認情況下爲真)將導致unexisting路徑出現在我的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 + unexisting子對象的對象?

回答

0

您可以使用類似的東西,在那裏,而不是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參數)您可以自由創建任何種類的嵌套元素(陣列,嵌套文檔,st環整數值); 另一方面,在path參數中做它會非常棘手。

+0

感謝您的回答,但它似乎不適合我。如果我目前的'data = {foo:{bar:{spam:1,more:2,eggs:3}}'怎麼辦?難道我不完全覆蓋'bar'而不是添加'baz'屬性?我在'data'對象中已經有了一些小小的功能,比如'bar'屬性如果它已經存在就會是子對象。 –