187

ウサギに関する情報を保存するテーブルがあります。次のようになります。

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

私はそのクエリが好きではありません。それは混乱です。

フルタイムのウサギ飼育員として、データベース スキーマを変更する時間がありません。うさぎにきちんと食べさせたいだけです。そのクエリを実行するためのより読みやすい方法はありますか?

4

7 に答える 7

260

?PostgreSQL 9.4 以降、次の演算子を使用できます。

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 匹のウサギのテーブルで、各ウサギが 2 つの食品を好み、そのうちの 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
于 2014-11-26T08:16:52.013 に答える
44

@> 演算子を使用して、これを次のように行うことができます

SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';
于 2016-07-12T12:29:40.713 に答える
24

スマートではありませんが、よりシンプルです。

select info->>'name' from rabbits WHERE info->>'food' LIKE '%"carrots"%';
于 2013-11-15T10:36:51.023 に答える
15

小さなバリエーションですが、新しい事実はありません。本当に機能が不足しています...

select info->>'name' from rabbits 
where '"carrots"' = ANY (ARRAY(
    select * from json_array_elements(info->'food'))::text[]);
于 2014-04-10T09:23:40.317 に答える
1

シンプルではありませんが、よりスマートです。

select json_path_query(info, '$ ? (@.food[*] == "carrots")') from rabbits
于 2021-08-07T03:05:35.020 に答える