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

标签 json postgresql postgresql-9.3

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

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

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

作为一名全职养兔人,我没有时间更改我的数据库架构。我只想好好喂养我的兔子。有没有更易读的方式来做这个查询?

最佳答案

从 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 只兔子组成的 table 上的性能改进演示,其中每只兔子喜欢两种食物,其中 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

关于json - 检查 Postgres JSON 数组是否包含字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19925641/

相关文章:

java - postgreSQL 会支持 rest API 吗?

PostgreSQL V 和 W 的结果相同

mysql - SQL conditional JOIN - JOIN point defined based on joined_table 条件

javascript - 对 JSON 数据进行数学运算

php - 将 jQuery 与 Selenium WebDriver 结合使用 - 如何将 JSON 对象转换为 WebElement?

asp.net - 将 JSON 传递给 MVC 3 操作

postgresql - 如何在 PostgreSQL 中获取日期的开始时间?

类型为 String 或 List<String> 时的 Java JSON 反序列化

sql - 为包含列表的单元格返回多行

postgresql - 从给定点找到一定半径内的点的最有效方法