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

编程入门 行业动态 更新时间:2024-10-28 21:17:10
本文介绍了检查Postgres JSON数组是否包含字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一张桌子来存储有关我的兔子的信息.看起来像这样:

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数组是否包含字符串

本文发布于:2023-10-15 12:22:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1494318.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   Postgres   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!