Answer the question
In order to leave comments, you need to log in
How to update jsonb field?
Dear developers, please help with building a query, although I assume that in a particular case it will be necessary to write a procedure.
There is the following table structure:
CREATE TABLE public.rules (
id integer NOT NULL,
user_id integer NOT NULL,
tags jsonb,
query jsonb
);
{
"{1}": {
"mark": "some_mark_word",
"stat": 11844
},
"{27}": {
"mark": "another_mark_word",
"stat": 7911
},
"{9}": {
"mark": "again_mark_word",
"stat": 10503
}
}
WITH dataset AS (SELECT jsonb_object_keys(tags) AS tag FROM rules WHERE user_id = $1)
UPDATE rules
SET tags = (rules.tags || jsonb_build_object(dataset.tag, (rules.tags->tag || '{"stat":0}'::jsonb)))
FROM dataset
WHERE user_id = $1 AND rules.tags ? dataset.tag;
CREATE FUNCTION clear_by_uid(in int) RETURNS BOOLEAN AS $$
DECLARE
tg_field rules.tags%TYPE;
BEGIN
SELECT tags INTO tg_field FROM rules AS r WHERE r.user_id = $1;
FOR set IN key value FROM jsonb_each(tg_field)
LOOP
UPDATE rules
SET tags = (rules.tags || jsonb_build_object(set.key, (set.value || '{"stat":0}'::jsonb)))
WHERE rules.user_id = $1;
END LOOP
RETURN TRUE;
END;
$$ LANGUAGE plpgsql;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question