检查一个Postgres JSON数组是否包含一个string

我有一张桌子来存储关于我的兔子的信息。 它看起来像这样:

create table rabbits (rabbit_id bigserial primary key, info json not null); insert into rabbits (info) values ('{"name":"Henry", "food":["lettuce","carrots"]}'), ('{"name":"Herald","food":["carrots","zucchini"]}'), ('{"name":"Helen", "food":["lettuce","cheese"]}'); 

我应该如何find喜欢胡萝卜的兔子? 我想出了这个:

 select info->>'name' from rabbits where exists ( select 1 from json_array_elements(info->'food') as food where food::text = '"carrots"' ); 

我不喜欢那个查询。 一团糟。

作为一个全职的兔子守门员,我没有时间去改变我的数据库模式。 我只是想适当地喂我的兔子。 有一个更可读的方式来做这个查询吗?

从PostgreSQL 9.4开始,你可以使用? 操作员 :

 select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots'; 

你甚至可以索引? 如果切换到jsonbtypes,则在"food"键上查询:

 alter table rabbits alter info type jsonb using info::jsonb; create index on rabbits using gin ((info->'food')); select info->>'name' from rabbits where info->'food' ? 'carrots'; 

当然,你可能没有时间去做一个全职的守门员。

更新:下面是一张100万只兔子的performance改善示范,每只兔子喜欢两种食物,其中10%喜欢胡萝卜:

 d=# -- Postgres 9.3 solution d=# explain analyze select info->>'name' from rabbits where exists ( d(# select 1 from json_array_elements(info->'food') as food d(# where food::text = '"carrots"' d(# ); Execution time: 3084.927 ms d=# -- Postgres 9.4+ solution d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots'; Execution time: 1255.501 ms d=# alter table rabbits alter info type jsonb using info::jsonb; d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots'; Execution time: 465.919 ms d=# create index on rabbits using gin ((info->'food')); d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots'; Execution time: 256.478 ms 

不是更聪明,更简单:

 select info->>'name' from rabbits WHERE info->>'food' LIKE '%"carrots"%'; 

一个小的变化,但没有新的事实。 这是真的缺less一个function…

 select info->>'name' from rabbits where '"carrots"' = ANY (ARRAY( select * from json_array_elements(info->'food'))::text[]); 

你可以使用@>运算符来做这个事情

 SELECT info->>'name' FROM rabbits WHERE info->'food' @> '"carrots"';