0

i was scraping large and complex data and have problem in a column that has array of nested json. to simulate the issue: -

CREATE TABLE public.test
(
  id integer NOT NULL DEFAULT nextval('test_id_seq'::regclass),
  testval jsonb
)

sample data

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"}]'
);

question is how to filter out base on specific conditions

select * from test where testval->'type' ->>'displayName'='test1';

this didnt work. can anyone point me to right direction?

0

2 Answers 2

1

Use the JSON containment operator:

WHERE testval @> '[ { "type": { "displayName": "test1" } } ]'

This can be supported with a GIN index on the column.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. is the key 'type' be able to be done in wildcard?
No. If the data were in a normal relational structure, it wouldn't be a problem...
0

If you want to use a wildcard search (e.g. LIKE) you need to unnest the array:

select t.*
from test t
where exists (select *
              from jsonb_array_elements(t.testval) as a(x)
              where a.x -> 'type' ->> 'displayName' like 'foo%');

With Postgres 12 this can be written a bit simpler using the new jsonb_path_exists() function:

select *
from test
where jsonb_path_exists(testval, '$.type.displayName ? (@ starts with "foo")');

Online example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.