Gestire JSON in PostgreSQL
PostgreSQL ha una gestione del JSON veramente avanzata rispetto ad altri database.
Addirittura c'è chi lo usa al posto di db NoSQL.
Non entro nel merito della scelta, ma in effetti è molto comodo.
Ad esempio per attributi di un prodotto, o per un'anagrafica utenti; per dei logs, ecc.
Vediamo un esempio:
CREATE TABLE test_prodotti
(
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
nome TEXT NOT NULL,
prezzo NUMERIC(10, 2) NOT NULL,
attributi JSONB DEFAULT '{}'
);
Come vedete abbiamo impostato il campo come JSONB.
Inseriamo dei dati:
INSERT INTO test_prodotti (nome, prezzo, attributi)
VALUES ('Prodotto 1',
999.00,
'{
"brand": "Apple",
"colore": "Blue",
"disponibile": true
}'),
('Prodotto 2',
120.00,
'{
"brand": "Nike",
"misura": "S",
"colore": "Bianco/Nero",
"style": "Running"
}'),
('Libro 3',
39.99,
'{
"autore": "Clive Cussler",
"isbn": "978-0135-99999",
"pagine": 352,
"editore": "Mondadori"
}');
E facciamo qualche query specifica, andando a cercare dentro al JSON:
SELECT *
FROM test_prodotti
WHERE attributi @> '{"disponibile": true}';
SELECT *
FROM test_prodotti
WHERE attributi ->> 'brand' = 'Apple';
Enjoy!
database postgresql jsonb
Commentami!