一尘不染

检查Postgres JSON数组是否包含字符串

json

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

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"]}');

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

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

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

作为专职兔子管理员,我没有时间更改数据库架构。我只想适当地喂兔子。有没有更可读的方法来执行该查询?


阅读 602

收藏
2020-07-27

共1个答案

一尘不染

从PostgreSQL
9.4开始,您可以使用?operator

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

如果改用 jsonb 类型,甚至可以?"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';

当然,作为专职兔子饲养员,您可能没有时间这样做。

更新: 这是在一张1,000,000只兔子的桌子上性能改进的演示,其中每只兔子喜欢两种食物,其中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
2020-07-27