如何使用 = 运算符查询 Postgres JSONB 数组

How to query Postgres JSONB arrays with = operator

我正在寻找一种使用 = 子句查询 PostgreSQL JSONB 数组字段的方法。

假设我有一个 table

CREATE TABLE events(
   id integer,
   tags jsonb,
   PRIMARY KEY(id)
);

标签的值类似于 ['Google', 'Hello World', 'Ruby']

我经历过 并做过类似的事情。

而形成的SQL就像

SELECT "events".* FROM "events" WHERE ("events"."tags" @> '{google}')  ORDER BY "business_events"."id" desc;

通过 运行 这个,我得到了这个错误 =>

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...

有什么想法吗?

the operator @> 的右操作数应该是有效的 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)

请注意 json 个对象的键和文本值用双引号括起来。

运算符按原样接受参数,无法使其工作时不区分大小写。您可以使用函数 jsonb_array_elements_text() 来完成此操作:

SELECT events.*
FROM events 
CROSS JOIN jsonb_array_elements_text(tags)
WHERE lower(value) = 'google';

第二种解决方案要昂贵得多, 中的注释也适用于此。