postgreSQL JSON Support
Examples
Creating a pure JSON table
To create a pure JSON table you need to provide a single field with the type JSONB:
CREATE TABLE mytable (data JSONB NOT NULL);
You should also create a basic index:
CREATE INDEX mytable_idx ON mytable USING gin (data jsonb_path_ops);
At this point you can insert data in to the table and query it efficiently.
Querying complex JSON documents
Taking a complex JSON document in a table:
CREATE TABLE mytable (data JSONB NOT NULL);
CREATE INDEX mytable_idx ON mytable USING gin (data jsonb_path_ops);
INSERT INTO mytable VALUES($$
{
"name": "Alice",
"emails": [
"alice1@test.com",
"alice2@test.com"
],
"events": [
{
"type": "birthday",
"date": "1970-01-01"
},
{
"type": "anniversary",
"date": "2001-05-05"
}
],
"locations": {
"home": {
"city": "London",
"country": "United Kingdom"
},
"work": {
"city": "Edinburgh",
"country": "United Kingdom"
}
}
}
$$);
Query for a top-level element:
SELECT data->>'name' FROM mytable WHERE data @> '{"name":"Alice"}';
Query for a simple item in an array:
SELECT data->>'name' FROM mytable WHERE data @> '{"emails":["alice1@test.com"]}';
Query for an object in an array:
SELECT data->>'name' FROM mytable WHERE data @> '{"events":[{"type":"anniversary"}]}';
Query for a nested object:
SELECT data->>'name' FROM mytable WHERE data @> '{"locations":{"home":{"city":"London"}}}';