postgres upsert json 道具

postgres upsert json props

我不确定这是否可能,但我正在尝试深入了解我在 postgres 9.6.1 中可以做什么,这似乎是可能的。所以给定这个 table:

DROP TABLE IF EXISTS live_data;
CREATE TABLE live_data (
rec_id TEXT,
control_data JSONB
);
CREATE UNIQUE INDEX rec_id_idx ON live_data (rec_id);

我希望能够在 control_data json 上插入单个道具,而不必插入一个全新的 json 字符串。

table 中没有行,但我试过这个:

INSERT INTO live_data(rec_id, control_data) VALUES ('1', '{"set":{"some_prop": 99}}')
ON CONFLICT (rec_id) DO UPDATE SET control_data->'set'->'some_prop' = 99;

FWIW 我在该查询中收到此错误:

syntax error at or near "->"

我是不是写错了查询and/or我想做的目前不可能?

使用jsonb_set():

INSERT INTO live_data(rec_id, control_data) 
VALUES ('1', '{"set":{"some_prop": 99}}');

INSERT INTO live_data(rec_id, control_data) 
VALUES ('1', '{"set":{"some_prop": 88}}')
ON CONFLICT (rec_id) DO 
UPDATE SET control_data = 
    jsonb_set(live_data.control_data, array['set','some_prop'], '88', true)
RETURNING *;

 rec_id |        control_data        
--------+----------------------------
 1      | {"set": {"some_prop": 88}}
(1 row)

如果您的 json 列的值如下所示,

[
   {
      "Code":"xyz",
      "Amount":[
         {
            "Type":"Pay1",
            "Amount":"999",
            "username":"henry"
         },
         {
            "Type":"Pay2",
            "Amount":"499",
            "username":"rohilpatel",
            "Bonus":"100"
         }
      ],
      "Currency":"$"
   }
]

下面的 sql 查询将添加键值对或更新(如果存在于指定路径)。 [Upsert 将以这种方式工作]

update tableName
SET  columnName = jsonb_set(columnName, '{0,Amount,1,Bonus}', '200')