我有一张桌子来存储有关我的兔子的信息.看起来像这样:
I have a table to store information about my rabbits. It looks like this:
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"]}');我该如何找到喜欢胡萝卜的兔子?我想到了这个:
How should I find the rabbits who like carrots? I came up with this:
select info->>'name' from rabbits where exists ( select 1 from json_array_elements(info->'food') as food where food::text = '"carrots"' );我不喜欢该查询.真是一团糟.
I don't like that query. It's a mess.
作为专职兔子管理员,我没有时间更改数据库架构.我只想适当地喂兔子.有没有更可读的方法来执行该查询?
As a full-time rabbit-keeper, I don't have time to change my database schema. I just want to properly feed my rabbits. Is there a more readable way to do that query?
推荐答案从PostgreSQL 9.4开始,您可以使用 ?运算符:
As of PostgreSQL 9.4, you can use the ? operator:
select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';如果您改为使用 jsonb 类型,甚至可以在"food"键上为?查询建立索引:
You can even index the ? query on the "food" key if you switch to the jsonb type instead:
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';当然,您可能没有时间担任专职兔子饲养员.
Of course, you probably don't have time for that as a full-time rabbit keeper.
更新:这是在一张1,000,000只兔子的桌子上性能改进的演示,其中每只兔子喜欢两种食物,其中10%像胡萝卜:
Update: Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:
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更多推荐
检查Postgres JSON数组是否包含字符串
发布评论