PostgreSQL JSON查询数组针对多个值


18

我想针对jsonbPostgres 中的类型编写查询,因为给定的客户ID数组将找到对应的组。

给定此示例表:

CREATE TABLE grp(d JSONB NOT NULL);

INSERT INTO grp VALUES
   ('{"name":"First","arr":["foo"], "customers":[{"id":"1", "name":"one"},{"id":"2", "name":"two"}]}')
 , ('{"name":"Second","arr":["foo","bar"], "customers":[{"id":"3", "name":"three"},{"id":"4", "name":"four"}]}')
 , ('{"name":"Third","arr":["bar","baz"], "customers":[{"id":"5", "name":"five"},{"id":"6", "name":"seven"}]}');

我发现了类似的问题(针对多个值的PostgreSql JSONB SELECT),并使用此查询设法在简单数组上实现了我想要的功能:

SELECT d FROM grp WHERE d->'arr' ?| ARRAY['foo', 'bar'];

但是,当数组包含JSON 对象时,我无法使其工作:

SELECT d FROM grp WHERE d->'customers' ?| ARRAY['{"id":"1"}', '{"id":"5"}'];

这是我对查询的期望:

grp“第一”->客户“ 1”

grp“第三”->客户“ 5”

Answers:


17

有一种方法:将包含运算符@>ANY构造组合

SELECT d
FROM   grp
WHERE  d->'customers' @> ANY (ARRAY ['[{"id":"1"}]', '[{"id":"5"}]']::jsonb[]);

要么:

...
WHERE d->'customers' @> ANY ('{"[{\"id\": \"1\"}]","[{\"id\": \"5\"}]"}'::jsonb[]);

必须将数组jsonb[]显式转换为。并且请注意,每个元素都是内部的JSON 数组,就像操作员@>需要的那样。因此,它是一个JSON数组的数组。

您可以为此使用索引:

手册明确指出该运算符?|仅适用于字符串

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.