Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres JSON array contains given array element

I have been searching for this answer for long on stackoverflow, but did not find anything useful. I have data in my_tbl as:

folder_id |  links                                                                                                     
--------------+----------------------------------------------------------------
   761 | [{"ids": "[82293,82292]", "index": "index_1"}, {"ids": "[82293,82292]", "index": "index_2"}]
   769 | [{"ids": "[82323,82324]", "index": "index_3"}]
   572 | [{"ids": "[80031,79674,78971]", "index": "index_4"}]
   785 | [{"ids": "[82367,82369]", "index": "index_5"}, {"ids": "[82368,82371]", "index": "index_6"}]
   768 | [{"ids": "[82292,82306]", "index": "index_7"}]

I want to get all the rows where links->>'ids' contain 82292. So in this case, it should return me folder_id 761 and 768.

I achieved so far is separating ids arrays from links by - jsonb_array_elements(links) ->> 'ids'

not sure how to proceed further.

like image 732
stack_d_code Avatar asked Dec 14 '22 00:12

stack_d_code


1 Answers

You can use jsonb_array_elements to convert a json array to a rowset. You can use this to at the value of "ids". Using the @> operator you can check if the array contains a value:

select  distinct folder_id
from    YourTable
cross join lateral
        jsonb_array_elements(links) ids(ele)      
where   (ele->>'ids')::jsonb @> '[82292]'

A tricky part is that "[82293,82292]" is stored as a string, not an array. The ele->>'ids' expression retrieves "[82293,82292]" as string using the ->> operator (the double > makes it return text instead of jsonb.) The content of the string is converted to an array by ::jsonb.

Example at rextester.com.

like image 156
Andomar Avatar answered Dec 29 '22 06:12

Andomar