I've defined a simple table with
create table resources (id serial primary key, fields jsonb);
And it contains data with keys (drawn from a large set) and values between 1 and 100, like:
id | fields
--------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 | {"tex": 23, "blair": 46, "cubic": 50, "raider": 57, "retard": 53, "hoariest": 78, "suturing": 25, "apostolic": 22, "unloosing": 37, "flagellated": 85}
2 | {"egoist": 75, "poshest": 0, "annually": 19, "baptists": 29, "bicepses": 10, "eugenics": 9, "idolizes": 8, "spengler": 60, "scuppering": 13, "cliffhangers": 37}
3 | {"entails": 27, "hideout": 22, "horsing": 98, "abortions": 88, "microsoft": 37, "spectrums": 26, "dilettante": 52, "ringmaster": 84, "floweriness": 72, "vivekananda": 24}
4 | {"wraps": 6, "polled": 68, "coccyges": 63, "internes": 93, "unburden": 61, "aggregate": 76, "cavernous": 98, "stylizing": 65, "vamoosing": 35, "unoriginal": 40}
5 | {"villon": 95, "monthly": 68, "puccini": 30, "samsung": 81, "branched": 33, "congeals": 6, "shriller": 47, "terracing": 27, "patriarchal": 86, "compassionately": 94}
I'd like to search for entries whose value (associated with a particular key) is greater than some benchmark value. I can accomplish this, for example via:
with exploded as (
select id, (jsonb_each_text(fields)).*
from resources)
select distinct id
from exploded
where key='polled' and value::integer>50;
... but of course this does not use an index, and it resorts to a table scan. I wonder if there is:
- A more efficient way to query for resources with "polled" >50
- A way to build indexes that will support this kind of query