Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgres query on nested array failing to return results

I have the following query:

SELECT * FROM post p
 , jsonb_array_elements(p.meta #> '{tags, tag}') d
WHERE  d->>'tag' LIKE '%mytag%';

Which isn’t returning any results, I have an object in the post table that looks like this:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m not sure why this is failing, my understanding was jsonb_array_elements flattens out arrays and by selecting {tags, tag} it would get the tag string

>Solution :

The path to the nested array is meta #> '{tags}', not meta #> '{tags, tag}', so this should work

select *
from 
    post p,
    jsonb_array_elements(p.meta #> '{tags}') d
where d->>'tag' like '%mytag%';

-- or simpler

select *
from 
    post p,
    jsonb_array_elements(p.meta -> 'tags') d
where d->>'tag' like '%mytag%';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading