当前位置: 首页 > 面试题库 >

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

乐正育
2023-03-14
问题内容

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

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


 类似资料:
  • 问题内容: 我发现的大多数问题都偏向于他们正在寻找数字中的字母这一事实,而我正在寻找我想成为无数字符串的数字。我需要输入一个字符串,并检查它是否包含任何数字以及是否确实拒绝它。 仅当所有字符均为数字时,该函数才返回。我只想看看用户是否输入了一个数字,例如“我拥有一只狗”之类的句子。 有任何想法吗? 问题答案: 你可以像这样使用函数和函数 另外,你可以使用正则表达式,如下所示

  • 问题内容: 我正在编写一个程序,其中用户以以下格式输入字符串: 我需要检查字符串中是否有数字 然后只提取数字。 如果我使用或,则无论输入的内容是什么,程序都无法在字符串中找到数字,但是仅在只有数字的情况下才能使用。 我可以使用什么作为查找和提取的解决方案? 问题答案: 我使用的解决方案如下所示: 我确信这不是一个完美的解决方案,但它满足了我的需求。谢谢大家的帮助。:)

  • 问题内容: 我想检查a是否仅包含数字。我用这个: 但意识到它也允许和。基本上,我要确保只能包含数字,而不能包含其他字符。由于和都是数字,所以不是正确的方法。也许我需要一个正则表达式?有小费吗? 问题答案: 怎么样

  • 问题内容: 我正在尝试检测字符串是否包含至少一个存储在数组中的URL。 这是我的数组: 该字符串由用户输入并通过PHP提交。在确认页面上,我想检查输入的URL是否在数组中。 我尝试了以下方法: 无论输入什么,返回值始终为“找不到匹配项”。 这是正确的做事方式吗? 问题答案: 尝试这个。 如果要检查不区分大小写,请使用stristr()或stripos()。

  • 我正在寻找一个运算符,它允许我检查字段的值是否包含某个字符串。 比如: 可能吗?

  • 所以我一辈子也想不出来。我正在尝试编写一个程序,提示用户输入电话号码。这将作为字符串输入,并在稍后的程序中转换为整数数组。然而,我现在遇到的情况是验证用户输入的字符串是否仅限于!!!包含2-9之间的数字。我已经尝试了。Contains方法和。Match方法,但是使用这些方法总是提供错误的结果。如果有人能提供一些关于如何解决这个问题,我将非常感谢。提前感谢。 以下是我目前掌握的信息: