2015-05-14 15 views
7

Ho la seguente struttura jsonb:Come posso eseguire una query LIKE per una chiave jsonb?

{'this': '1', 'this_that': '0', 'this_and_that': '5'} 

Come faccio a selezionare le righe che contengono un operatore LIKE?

SELECT * FROM myjson WHERE j ? 'this_%' 

Restituisce 0 righe ... sperava che corrispondesse 'this_that' e 'this_and_that'. (Nota: i caratteri che seguono '_' potrebbero variare notevolmente e quindi non sono in grado di fare una corrispondenza esatta).

+0

qual è la versione esatta di PostgreSQL che stai utilizzando? eseguire 'select version()' –

+0

PostgreSQL 9.4.1 su x86_64-unknown-linux-gnu, compilato da gcc (Ubuntu 4.9.1-16ubuntu6) 4.9.1, 64-bit –

risposta

8

L'esempio non dovrebbe funzionare perché non vi sono cast impliciti tra i tipi jsonb e text. Puoi imporre il casting:

SELECT '{"this": 1, "this_that": 0, "this_and_that": 5}'::jsonb::text 
      like '%"this%'; 

Non è una soluzione pulita. Un po 'meglio è decomprimere json e filtrare su dati non compressi con join laterale

postgres=# SELECT key FROM myjson, lateral jsonb_each_text(j) 
      WHERE key LIKE 'this\_%'; 
┌───────────────┐ 
│  key  │ 
╞═══════════════╡ 
│ this_that  │ 
│ this_and_that │ 
└───────────────┘ 
(2 rows) 
Problemi correlati