Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querying JSONB with array fields

If I have a jsonb column called value with fields such as:

{"id": "5e367554-bf4e-4057-8089-a3a43c9470c0",
 "tags": ["principal", "reversal", "interest"],,, etc}

how would I find all the records containing given tags, e.g: if given: ["reversal", "interest"] it should find all records with either "reversal" or "interest" or both.

My experimentation got me to this abomination so far:

select value from account_balance_updated 
where value @> '{}' :: jsonb and value->>'tags' LIKE '%"principal"%';

of course this is completely wrong and inefficient

like image 712
iLemming Avatar asked Dec 31 '25 14:12

iLemming


2 Answers

Assuming you are using PG 9.4+, you can use the jsonb_array_elements() function:

SELECT DISTINCT abu.*
FROM account_balance_updated abu,
     jsonb_array_elements(abu.value->'tags') t
WHERE t.value <@ '["reversal", "interest"]'::jsonb;
like image 93
Patrick Avatar answered Jan 06 '26 09:01

Patrick


As it turned out you can use cool jsonb operators described here:

https://www.postgresql.org/docs/9.5/static/functions-json.html

so original query doesn't have to change much:

select value from account_balance_updated 
where value @> '{}' :: jsonb and value->'tags' ?| array['reversal', 'interest'];

in my case I also needed to escape the ? (??|) because I am using so called "prepared statement" where you pass query string and parameters to jdbc and question marks are like placeholders for params:

https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

like image 34
iLemming Avatar answered Jan 06 '26 09:01

iLemming



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!