A partir de PostgreSQL 9.4, puede usar ?
operador:
select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
Incluso puedes indexar el ?
consulta sobre el "food"
clave si cambia a jsonb escriba en su lugar:
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';
Por supuesto, probablemente no tengas tiempo para eso como cuidador de conejos a tiempo completo.
Actualización: Aquí hay una demostración de las mejoras de rendimiento en una tabla de 1,000,000 de conejos donde a cada conejo le gustan dos alimentos y al 10 % le gustan las zanahorias:
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