如何在postgresql中查询嵌套json数组
我正在抓取大型复杂数据,在一个包含嵌套json数组的列中遇到问题。要模拟问题,请执行以下操作:-如何在postgresql中查询嵌套json数组,json,postgresql,Json,Postgresql,我正在抓取大型复杂数据,在一个包含嵌套json数组的列中遇到问题。要模拟问题,请执行以下操作:- CREATE TABLE public.test ( id integer NOT NULL DEFAULT nextval('test_id_seq'::regclass), testval jsonb ) 样本数据 INSERT INTO test (id, test) VALUES (111, '[{"type": {"value": 0,
CREATE TABLE public.test
(
id integer NOT NULL DEFAULT nextval('test_id_seq'::regclass),
testval jsonb
)
样本数据
INSERT INTO test (id, test)
VALUES
(111,
'[{"type": {"value": 0, "displayName": "test0"}, "value": "outertestvalue0"}, {"type": {"value": 1, "displayName": "test1"}, "value": "outertestvalue1"}]'
);
INSERT INTO test (id, test)
VALUES
(222,
'[{"type": {"value": 2, "displayName": "test2"}, "value": "outertestvalue2"}, {"type": {"value": 3, "displayName": "test3"}, "value": "outertestvalue3"}]'
);
问题是如何根据具体情况过滤掉
select * from test where testval->'type' ->>'displayName'='test1';
这不管用。有人能给我指出正确的方向吗?使用JSON包含运算符:
WHERE testval @> '[ { "type": { "displayName": "test1" } } ]'
这可以通过列上的GIN索引来支持。如果要使用通配符搜索(例如,LIKE),则需要取消数组的测试:
select t.*
from test t
where exists (select *
from jsonb_array_elements(t.testval) as a(x)
where a.x -> 'type' ->> 'displayName' like 'foo%');
对于Postgres 12,使用新的jsonb_path_exists()
函数可以更简单地编写:
select *
from test
where jsonb_path_exists(testval, '$.type.displayName ? (@ starts with "foo")');
谢谢。键“type”是否可以在通配符中完成?否。如果数据是在正常的关系结构中,这不会是一个问题。。。