I am using postgres 9.4. How to use regular operands such as < , > <= etc with json postgres where key is a numeric, and value is a text till a limit of key numeric value is reached?
This is my table:
create table foo (
id numeric,
x json
);
The values for the json are as follows:
id | x
----+--------------------
1 | '{"1":"A","2":"B"}'
2 | '{"3":"C","4":"A"}'
3 | '{"5":"B","6":"C"}'
so on randomly till key is 100
I am trying to get all the id, keys, values of the json key where key is <= 20.
I have tried:
select *
from foo
where x->>'key' <='5';
The above query ran, and should have given me 20 rows of output, instead it gave me 0. The below query ran, and gave me 20 rows but it took over 30 mins!
select
id
, key::bigint as key
, value::text as value
from foo
, jsonb_each(x::jsonb)
where key::numeric <= 100;
Is there a way to use a for loop or a do-while loop until x = 20 for json? Is there a way the run time be reduced?
Any help appreciated!
{"1":"A","2":"B"},{"3":"C","4":"A"}, etc. (What you gave is not valid JSON.) Quering for a JSON's key is not easy. The only operator which can use an index is?forjsonb(I assume you have at least 9.4, because you used thejsonbcast). If all of my assumptions are correct, you can usegenerate_series(1, 20) s& then join onx ? s::textto filter for keys 1-20.