On 2014-10-16 17:16, Daniele Varrazzo wrote:
On 2014-10-16 16:38, Carlos Catucci wrote:
Approfitto del thread su psycopg2 per formulare una domnada dborder
line
all'OT.
Sto cercando ddi usre delle colonne JSON con Postgres 9.3/Django 1.6+.
Ovvio che devo usare (*) delle rwa query. Solo che fatico a ottenere
un
risultato con una struttura di questo tipo:
data = '{ "A": { "B": [ { "C": 1, "D": 2 }, { "C": 3, "D": 4 }, {
"C":1,
"D": 6, "E": 3 } ] } }'
per fare una query dove mi deve tornare tutti i record, per dire che
abbianno
tabella.data->'A'->'B'->'C' == 1
Non ci ho ancora giocato troppo con le funzioni json di postgres.
Guardando i doc, json_populate_recordset sembra promettente: ...
Anche json_array_element puo' funzionare: srotola una lista json negli
oggetti che contiene:
piro=# select id, json_array_elements(data-> 'A' -> 'B') from
mydata; id
| json_array_elements
----+----------------------------
1 | { "C": 1, "D": 2 }
1 | { "C": 3, "D": 4 }
1 | { "C":1, "D": 6, "E": 3 }
2 | { "C": 0, "D": 2 }
2 | { "C": 3, "D": 4 }
2 | { "C": 0, "D": 6, "E": 3 }
(6 rows)
quindi puoi filtrare gli elementi che hannno C = 1
piro=# select id from (select id, json_array_elements(data-> 'A' ->
'B') as data from mydata) x where (data -> 'C')::text = '1';
id
----
1
1
(2 rows)
e di nuovo puoi usare exists per prendere i record che ti servono:
piro=# select d.* from mydata d
where exists (
select 1 from (
select id, json_array_elements(data-> 'A' -> 'B') as data
from mydata) x
where (data -> 'C')::text = '1'
and x.id = d.id);
id | data
----+---------------------------------------------------------------------------
1 | { "A": { "B": [ { "C": 1, "D": 2 }, { "C": 3, "D": 4 }, {
"C":1, "D": 6, .
|."E": 3 } ] } }
(1 row)
Questo penso sia meglio perche' non richiede un CREATE TYPE.
-- Daniele
_______________________________________________
Python mailing list
Python@lists.python.it
http://lists.python.it/mailman/listinfo/python