PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Interroga postgres jsonb per valore indipendentemente dalle chiavi

Per semplici JSON puoi utilizzare query più appropriate come

select * 
from mytable t 
where exists (
  select 1 
  from jsonb_each_text(t.jsonbfield) j 
  where j.value = 'hello');

Funziona bene per JSON come nel tuo esempio, ma non aiuta per JSON più complessi come {"a":"hello","b":1,"c":{"c":"world"}}

Posso proporre di creare la funzione memorizzata come

create or replace function jsonb_enum_values(in jsonb) returns setof varchar as $$
begin
  case jsonb_typeof($1)
    when 'object' then
      return query select jsonb_enum_values(j.value) from jsonb_each($1) j;
    when 'array' then
      return query select jsonb_enum_values(a) from jsonb_array_elements($1) as a;
    else
      return next $1::varchar;
  end case;
end
$$ language plpgsql immutable;

per elencare tutti i valori inclusi gli oggetti ricorsivi (sta a te decidere cosa fare con gli array).

Ecco un esempio di utilizzo:

with t(x) as (
  values
    ('{"a":"hello","b":"world","c":1,"d":{"e":"win","f":"amp"}}'::jsonb),
    ('{"a":"foo","b":"world","c":2}'),
    ('{"a":[{"b":"win"},{"c":"amp"},"hello"]}'),
    ('[{"a":"win"}]'),
    ('["win","amp"]'))
select * 
from t 
where exists (
  select *
  from jsonb_enum_values(t.x) j(x) 
  where j.x = '"win"');

Nota che le doppie virgolette attorno al valore della stringa.