问题
I'm looking for a way to query postgres jsonb array field with kind of = clause.
Let's assume I have a table
CREATE TABLE events(
id integer,
tags jsonb,
PRIMARY KEY(id)
);
tags having values like ['Google', 'Hello World', 'Ruby']
I have gone through Stackover Flow and done similar things.
And the SQL formed is like SELECT "events".* FROM "events" WHERE ("events"."tags" @> '{google}') ORDER BY "business_events"."id" desc;
By running this, I'm getting this error =>
ERROR: invalid input syntax for type json
LINE 1: ...siness_events" WHERE ("business_events"."tags" @> '{google}'...
^
DETAIL: Token "google" is invalid.
CONTEXT: JSON data, line 1: {google...
Any Idea ?
回答1:
The right operand of the operator @> should be a valid json
:
WITH events(id, tags) AS (
VALUES
(1, '["Google", "Hello World", "Ruby"]'::jsonb)
)
SELECT events.*
FROM events
WHERE tags @> '["Google"]'
id | tags
----+-----------------------------------
1 | ["Google", "Hello World", "Ruby"]
(1 row)
Note that keys and text values of json objects are enclosed in double quotes.
The operator takes arguments as they are and there is no way to make it work case insensitive. You can use the function jsonb_array_elements_text()
to accomplish this:
SELECT events.*
FROM events
CROSS JOIN jsonb_array_elements_text(tags)
WHERE lower(value) = 'google';
The second solution is much more expensive, notes in the cited answer apply here as well.
来源:https://stackoverflow.com/questions/55004460/how-to-query-postgres-jsonb-arrays-with-operator