Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在postgresql中查询嵌套json数组_Json_Postgresql - Fatal编程技术网

如何在postgresql中查询嵌套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,

我正在抓取大型复杂数据,在一个包含嵌套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, "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”是否可以在通配符中完成?否。如果数据是在正常的关系结构中,这不会是一个问题。。。