Last active
November 12, 2019 23:38
-
-
Save DaddyMoe/076a47c80a68ffb85110702d48195eb2 to your computer and use it in GitHub Desktop.
postgres jsonb string find and replacement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Create table | |
create table t1(doc jsonb); | |
-- Verify | |
SELECT * FROM t1; | |
-- insert some data | |
INSERT INTO t1 | |
VALUES | |
('{"param1": 10, "param2": 15}'), | |
('{"param1": 10, "param2": 5}'); | |
-- Verify | |
SELECT * FROM t1; | |
SELECT doc::text FROM t1; | |
-- Play Jsonb String pattern replace | |
SELECT replace(replace(doc->>'param1', '0', '**'), '1', '2') | |
FROM t1; | |
SELECT replace(replace(doc::text, 'm1": ', 'm1": 9999'), '2": ', '2": 777') | |
FROM t1; | |
SELECT replace(replace(doc::text, 'm1": ', 'm1": 9999'), '2": ', '2": 777')::jsonb | |
FROM t1; | |
-- adds in column to add a WHERE clause on | |
ALTER TABLE t1 | |
ADD COLUMN name varchar | |
UPDATE t1 | |
SET name = '4543534534' | |
WHERE doc->>'param2'::text = '15' | |
--- Regex with case sensitivity on Last token block meaning [i=insensitive, g=global replacement] | |
-- More here: https://stackoverflow.com/a/31583547/837005 | |
UPDATE t1 | |
SET doc = regexp_replace(regexp_replace(doc::text, 'M1": ', 'M1": 303', 'g'), 'M2": ', 'M2": 22', 'g')::jsonb | |
WHERE t1.name like '999%'; | |
--- worked but case insensitive | |
UPDATE t1 | |
SET doc = replace(replace(doc::text, 'M1": ', 'M1": 44'), '2": ', '2": 444')::jsonb | |
WHERE t1.name like '999%'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment