问题
Working with Postgres 9.3, Python 2.7, psycopg2.
I have a table called SomeTable
with a json field some_json_array
and row_id
key.
some_json_array
looks something like this:
"[{'key': 'value_one'}, {'key': 'value_two'}, etc]"
I also have a function in which I'm trying to add some elements to the json array of SomeTable
corresponding to the given row_id
.
My code is as follows:
CREATE OR REPLACE FUNCTION add_elements (insertion_id smallint, new_elements_json json)
RETURNS void AS $$
BEGIN
UPDATE SomeTable
SET some_json_array = (SELECT array_to_json(array_agg(some_json_array) || array_agg(new_elements_json)))
WHERE row_id = insertion_id;
END;
$$ LANGUAGE plpgsql;
I get the following error:
Cannot use aggregate function in UPDATE
which I believe is complaining about array_agg()
.
How would I modify this function to make it work? I can stick the WHERE
clause into the SELECT
statement if necessary.
回答1:
Aggregate functions cannot be used like plain functions, only in an aggregate context.
Since Postgres cannot manipulate JSON arrays directly (it's just a valid json value to Postgres, not an array) you have to ...
- either cast the
json
value totext
, concatenate the new element, generating valid JSON syntax and transform back, - or transform to a Postgres array of
json
:json[]
, append the new element and transform this Postgres array back to ajson
value.array_to_json()
is smart enough to not encode thejson
elements of the Postgres array another time.
The first approach is much more error prone. You would have to build valid JSON by hand. Here is an implementation of the second variant:
CREATE OR REPLACE FUNCTION add_elements (_id int2, _elem json)
RETURNS void AS
$func$
BEGIN
UPDATE SomeTable s
SET some_json_array = array_to_json(ARRAY(
SELECT * FROM json_array_elements(s.some_json_array)
UNION ALL SELECT _elem
))
WHERE s.row_id = _id;
END
$func$ LANGUAGE plpgsql;
The function wrapper is mostly irrelevant to the problem. Could just be a plain SQL statement.
Related:
- How to turn json array into postgres array?
来源:https://stackoverflow.com/questions/28621738/update-json-array-using-aggregrate-function