如何过滤一个包含多个元素的JSON阵列

发布于 2025-02-06 16:44:19 字数 448 浏览 3 评论 0原文

这是示例表:

create table leadtime.test (
    id serial primary key,
    name jsonb
)

数据测试:

insert into leadtime.test (name)
values ('["abc", "def", "ghi"]');

我想检查名称是否包含此数组中的任何值[“ ABC”,“ 132”,“ 456”]'

我必须执行此代码:

select * from leadtime.test
where (name ? 'abc') or (name ? '132') or (name ? '456');

我被告知多个'ED过滤器或不是最佳性能。
有更好的方法吗?

This is the sample table:

create table leadtime.test (
    id serial primary key,
    name jsonb
)

Data test:

insert into leadtime.test (name)
values ('["abc", "def", "ghi"]');

I want to check if name contains any value in this array '["abc", "132", "456"]'

I have to do this code:

select * from leadtime.test
where (name ? 'abc') or (name ? '132') or (name ? '456');

I was told that multiple OR'ed filters or not optimal for performance.
Is there a better way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幼儿园老大 2025-02-13 16:44:19

将您的搜索术语数量传递为实际的postgres数组,并使用 |? 操作员

SELECT *
FROM   test
WHERE  name ?| '{abc, def, ghi}';

手册:

jsonb?|文本[]→布尔值

执行文本数组中的任何字符串作为顶级键或
数组元素?

可以用普通的 gin Index on > (名称)也是。

Pass your array of search terms as actual Postgres array and use the |? operator:

SELECT *
FROM   test
WHERE  name ?| '{abc, def, ghi}';

The manual:

jsonb ?| text[] → boolean

Do any of the strings in the text array exist as top-level keys or
array elements?

Can be supported with a plain GIN index on (name), too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文