从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 solutiond=# explain analyze select info->>'name' from rabbits where exists (d(# select 1 from json_array_elements(info->'food') as foodd(# where food::text = '"carrots"'d(# ); Execution time: 3084.927 msd=# -- Postgres 9.4+ solutiond=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots'; Execution time: 1255.501 msd=# 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 msd=# 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



