Postgres - JSONB - Nested Columns - 查询嵌套的Jsonb数组列

Postgres - JSONB - Nested Columns - Query Nested Jsonb array column

我有一个具有以下结构的 table -

Column Name | Data Type
--------------------------
user_id     | uuid
profile     | jsonb

示例配置文件字段类似于 -

{ "data": { "races": [ "white", "asian" ] } }

我想查询此 table 用户是否包含以下种族之一(例如)-“白人”、“非裔美国人”

我希望上面的示例用户返回,因为他们的种族字段包含“白色”。

我试过类似的方法但没有成功 -

SELECT user_id from table
WHERE profile -> 'data' ->> 'races' = ANY('{"white", "african american"}')

使用 Postgres 13.x

谢谢!

使用?|运算符:

select user_id 
from my_table
where profile -> 'data' -> 'races' ?| array['white', 'african american']

根据the documentation:

jsonb ?| text[] -> boolean

Do any of the strings in the text array exist as top-level keys or array elements?

tl;dr 使用 ?| operator.


您的查询有两个问题。

->> returns text 不是 jsonb。所以你问 text ["white", "asian"] 是否匹配 whiteafrican american.

您可能这样做了,因为否则您在尝试将 any 与 JSONB 一起使用时会遇到类型错误。 any 想要一个 Postgres 数组来比较,它必须是 jsonb 的数组。我们可以做到...

select user_id
from user
where profile -> 'data' -> 'races' = ANY(array['"white"', '"african american"']::jsonb[]);

但这和以前有同样的问题,它正在检查 json 数组 [ "white", "asian" ] 等于 "white""african american".

您需要一个运算符来匹配 JSON 的每个元素。使用 ?| operator.

select user_id
from users
where profile -> 'data' -> 'races' ?| array['white', 'african american'];