Postgres 中 jsonb 列表的条件

Where condition on list of jsonb in Postgres

假设我有 table food_articles,它有以下列:name(type ="text") 和 ingredients(type="jsonb []"),其中成分 jsonb 对象如下所示:

{
    ingredient_id: 'string',
    quantity: 'number'
} 

我如何创建一个查询 returns food_articles 中的所有行,这些行在成分 jsonb 数组中具有 ingredient_id = 1337

where子句中将ingredients嵌套到table中并检查是否存在ingredient_id = '1337'.

的记录
select * from food_articles 
where exists
(
 select 
 from unnest(ingredients) arj 
 where arj ->> 'ingredient_id' = '1337' 
);

请注意,如果 ingredients 的类型是包含像这样的数组的 jsonb '[{"ingredient_id":"1337","quantity":1},{"ingredient_id":"1336","quantity":2}]' 而不是 jsonb 元素的 Postgres 数组(即 jsonb[]),那么您可以使用'contains' @> 运算符简单如

where ingredients @> '[{"ingredient_id":"1337"}]'
create table "food_articles" ("name" text, "ingredients" jsonb);

insert into "food_articles" values('food 1', jsonb_build_object('ingredient_id', 1, 'quantity', 1)),
 ('food 2', jsonb_build_object('ingredient_id',2, 'quantity',1337)),
('food 3', jsonb_build_object('ingredient_id',3, 'quantity',1337)),
('food 3', jsonb_build_object('ingredient_id', 3, 'quantity',1332));

select * from "food_articles"
where "ingredients"->>'quantity'='1337';

游乐场link:https://dbfiddle.uk/?rdbms=postgres_13&fiddle=b6ab520a44c65656ebc767a10f5737b6

postgresql jsonb 操作的文档:https://www.postgresql.org/docs/9.5/functions-json.html