跳至主要内容

刪除 JSONB 資料

同樣的 PostgreSQL Jsonb 操作都可有兩種以上選擇,
  1.使用操作子: #-
  2.使用函數處理: jsonb_set()
#- 操作子可用來移除 Json 屬性值或移除整個 key-value pair
若僅要移除 value 不移除 key 也可使用 jsonb_set function

Jsonb 屬性刪除操作子 #-

  • 範例資料預設情境
    • 假設有一個紀錄標本資訊 table ,其中以 json_data 用來記錄分類樹資料 (界門綱目科屬種)

語法

  • SET data = data #- Array[ 'path_parent', 'child', 'descendent' ]
-- Path 需使用 Array 創建 array 物件
UPDATE your_table
SET data = data #- Array['path_parent', 'child', 'descendent']
WHERE condition;

-- 與 jsonb_set() 一樣,path 可以以大括號物件方式列出
UPDATE your_table
SET data = data #- '{path_parent, child, descendent}'
WHERE condition;

example : #-

    select (insect.classification) classification from insect_specimen insect where id = 2
===original
"{"Class": "Insecta", "Genus": {"name": "Aedes", "Subgenus": {"name": {"value": "Stegomyia-2"}}}, "Order": "Diptera", "Family": "Culicidae", "Phylum": "Arthropoda", "Kingdom": "Animalia", "Species": "albopictus"}"

update insect_specimen SET classification = classification #- array['Order'] where id = 2;
-- update insect_specimen SET classification = classification #- '{Order}' where id = 2;
===
"{"Class": "Insecta", "Genus": {"name": "Aedes", "Subgenus": {"name": {"value": "Stegomyia-2"}}}, "Family": "Culicidae", "Phylum": "Arthropoda", "Kingdom": "Animalia", "Species": "albopictus"}"

-- 資料補回
-- update insect_specimen SET classification = jsonb_set( classification, Array['Order'], '"Diptera"'::jsonb ) where id = 2;

example : jsonb_set

  • jsonb_set(raw, path, new_value) function
    • 'null'::jsonb,null 外包的 single quote 代表的是語法中 arg 必須是字串。此例是 清除 內容。
    • '""'::jsonb,這個範例指的是將舊值以 空字串 取代。
    • '123'::jsonb,帶入數值
    update insect_specimen SET classification = jsonb_set(classification, array['Order'], 'null'::jsonb) where id = 2; 

Jsonb 刪除資料語法變體: -

  • 看得懂就好,再多來記個同功能語法變體腦子就要炸了...
  • #- 可以採用 path TEXT[], 但 - 只能指向單一層。
    • 官方文件說這兩個差別,一個 delete key/value pair, 另一個 delete field! 意思不是相同嗎?
    • 測試結果: 主要 - 只能移除當前 jsonb 物件的次一層資料。
    update insect_specimen SET classification = classification - 'Order' where id = 2;