{
"id": "1220",
"title": "PostgreSQL JSON data types",
"subtitle": "NoSQL in SQL?",
"tags": [ "SQL", "NoSQL", "JSON" ],
"author": {
"name": "Nick Moore",
"email": "nick@mnemote.com"
}
}
⇒ Used in NoSQL "Document Store" databases
(MongoDB
CREATE TABLE Profiles (
id SERIAL PRIMARY KEY,
data JSON
);
INSERT INTO Profiles (data) VALUES (
'{
"occupation": "hacker",
"likes": [ "beer", "sql" ]
}'
);
select data->>'occupation' from profiles; select * from profiles where data->>'occupation' = 'hacker';
Builtin JSON Operators and Functions manipulate JSON objects
| ->> | Lookup Element (as text) |
| #>> | Lookup Element Path (as text) |
| row_to_json | Turn a row into a JSON structure |
| json_agg | Aggregate records into a JSON array |
| json_each | Unpack a JSON object into key/value pairs |
| json_array_elements | Unpack a JSON array |
... and many others ...
CREATE INDEX profiles_occupation ON profiles ((data->>'occupation')); SELECT * FROM profiles WHERE data->>'occupation' = 'hacker';
"likes": [ "beer", "sql" ]
CREATE OR REPLACE FUNCTION
public.json_to_text_array(jarr JSON)
RETURNS text[] LANGUAGE sql IMMUTABLE
AS $$
SELECT ARRAY_AGG(ROW_TO_JSON(T)->>'x')
FROM (
SELECT JSON_ARRAY_ELEMENTS(jarr) AS x
) AS T
$$;
CREATE OR REPLACE FUNCTION
public.json_to_text_array(jarr JSON)
RETURNS text[] LANGUAGE sql IMMUTABLE
AS $$
SELECT ARRAY_AGG(ROW_TO_JSON(T)->>'x')
FROM (
SELECT JSON_ARRAY_ELEMENTS(jarr) AS x
) AS T
$$;
CREATE OR REPLACE FUNCTION
public.json_to_text_array(jarr JSON)
RETURNS text[] LANGUAGE sql IMMUTABLE
AS $$
SELECT ARRAY_AGG(ROW_TO_JSON(T)->>'x')
FROM (
SELECT JSON_ARRAY_ELEMENTS(jarr) AS x
) AS T
$$;
CREATE OR REPLACE FUNCTION
public.json_to_text_array(jarr JSON)
RETURNS text[] LANGUAGE sql IMMUTABLE
AS $$
SELECT ARRAY_AGG(ROW_TO_JSON(T)->>'x')
FROM (
SELECT JSON_ARRAY_ELEMENTS(jarr) AS x
) AS T
$$;
CREATE OR REPLACE FUNCTION
public.json_to_text_array(jarr JSON)
RETURNS text[] LANGUAGE sql IMMUTABLE
AS $$
SELECT ARRAY_AGG(ROW_TO_JSON(T)->>'x')
FROM (
SELECT JSON_ARRAY_ELEMENTS(jarr) AS x
) AS T
$$;
CREATE INDEX profiles_likes ON profiles USING gin ( json_to_text_array(data->'likes') ); SELECT * FROM profiles WHERE json_to_text_array(data->'likes') @> ARRAY['beer'];
Benchmarks are fundamentally unhelpful, but ...
I like NoSQL, but I miss ...
Postgres JSON columns are:
Would also work in MS SQL Server, others ...
... really anything which supports indexes on expressions and user-defined functions.