postgresql 修改屬性

來源:互聯網
上載者:User

標籤:

up vote2down votefavorite

From this article, I tried to update or delete property of a JSONB column:

CREATE TABLE xxx (id BIGSERIAL, data JSONB);

INSERT INTO xxx(data) VALUES( ‘{"a":1,"b":2}‘ );

SELECT * FROM data;

 id |       data      

----+------------------

  1 | {"a": 1, "b": 2}

create the update function:

CREATE FUNCTION jsonb_merge(JSONB, JSONB)

RETURNS JSONB AS $$

WITH json_union AS (

    SELECT * FROM JSONB_EACH($1)

    UNION ALL

    SELECT * FROM JSONB_EACH($2)

) SELECT JSON_OBJECT_AGG(key, value)::JSONB FROM json_union;

$$ LANGUAGE SQL;

testing:

-- replace

UPDATE xxx SET data = jsonb_merge(data,‘{"b":3}‘) WHERE id = 1;

SELECT * FROM xxx;

 id |       data      

----+------------------

  1 | {"a": 1, "b": 3}

 

-- append

UPDATE xxx SET data = jsonb_merge(data,‘{"c":4}‘) WHERE id = 1;

SELECT * FROM xxx;

 id |           data      

----+-------------------------

  1 | {"a": 1, "b": 3, "c": 4}

The question is:

  1. is there any drawback of using JSONB_EACH (jsonb_merge) instead of JSONB_EACH_TEXT (from the article) in this case?
  2. how to modify the jsonb_merge so if the second parameter property value is null (something like {"b":null}) the value would be erased?

.

-- remove

UPDATE xxx SET data = jsonb_merge(data,‘{"b":null}‘) WHERE id = 1;

SELECT * FROM xxx;

 id |       data      

----+-----------------

  1 | {"a": 1, "c": 4}

postgresql postgresql-9.4

shareimprove this question

edited Mar 20 ‘15 at 10:23

asked Mar 20 ‘15 at 6:06

 

 

 

Kokizzu

273312

 

add a comment

1 Answer

activeoldestvotes

up vote3down voteaccepted

Question 1
There should be no signicant drawbacks. As the value is converted back to jsonb anyhow I would guess it would be more efficient to keep it that way the whole time.


Question 2
Just replace your function with the following (only the part WHERE key NOT IN ... added):

CREATE FUNCTION jsonb_merge(JSONB, JSONB)

RETURNS JSONB AS $$

WITH json_union AS (

    SELECT * FROM JSONB_EACH($1)

    UNION ALL

    SELECT * FROM JSONB_EACH($2)

) SELECT JSON_OBJECT_AGG(key, value)::JSONB

     FROM json_union

     WHERE key NOT IN (SELECT key FROM json_union WHERE value =‘null‘);

$$ LANGUAGE SQL;

shareimprove this answer

postgresql 修改屬性

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.