[英]how to query array of nested json in 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, "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()
function 更簡單地編寫:
select *
from test
where jsonb_path_exists(testval, '$.type.displayName ? (@ starts with "foo")');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.