简体   繁体   English

Postgres - JSONB - 嵌套列 - 查询嵌套 Jsonb 数组列

[英]Postgres - JSONB - Nested Columns - Query Nested Jsonb array column

I have a table with the following structure -我有一个具有以下结构的表 -

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

An example profile field would be something like -一个示例配置文件字段将类似于 -

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

I want to query this table for users contain one of the following races (for example) - "white", "african american"我想查询此表以查找包含以下种族之一的用户(例如)-“白人”、“非裔美国人”

I would expect my example user above to be returned since their races field contains "white".我希望我上面的示例用户会被返回,因为他们的比赛字段包含“白色”。

I have tried something like this with no success -我尝试过这样的事情但没有成功 -

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

Using Postgres 13.x使用 Postgres 13.x

Thank you!谢谢!

Use the ?|使用?| operator:操作员:

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

According to the documentation:根据文档:

jsonb?| jsonb?| text[] -> boolean文本[] -> boolean

Do any of the strings in the text array exist as top-level keys or array elements?文本数组中的任何字符串是否作为顶级键或数组元素存在?

tl;dr use the ?| tl;博士使用?| operator . 运营商


There's two problems with your query.您的查询有两个问题。

->> returns text not jsonb. ->>返回text而不是 jsonb。 So you're asking if the text ["white", "asian"] matches white or african american .所以你问的是文本["white", "asian"]是否匹配whiteafrican american

You probably did that because otherwise you got type errors trying to use any with JSONB.您可能这样做是因为否则您在尝试将any与 JSONB 一起使用时会出现类型错误。 any wants a Postgres array of things to compare, and it has to be an array of jsonb. any人都想要一个 Postgres 数组来比较,它必须是一个 jsonb 数组。 We can do that...我们能做到这一点...

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

But this has the same problem as before, it's checking if the json array [ "white", "asian" ] equals "white" or "african american" .但这和以前有同样的问题,它正在检查 json 数组[ "white", "asian" ]是否等于"white""african american"

You need an operator which will match against each element of the JSON.您需要一个与 JSON 的每个元素匹配的运算符。 Use the ?|使用?| operator . 运营商

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM