SlideShare una empresa de Scribd logo
1 de 47
The JSON Feature Tour
5432 … Meet Us!
June 2016
Stefanie Janine Stölting
Head of Product Development
@sjstoelting
Stefanie@paxlife.aero
JSON
JavaScript Object Notation
Don't have to care about encoding, it is always
Unicode, most implementations use UTF8
Used for data exchange in web application
Currently two standards RFC 7159 by Douglas
Crockford and ECMA-404
PostgreSQL implementation is RFC 7159
JSON Datatypes
JSON
Available since 9.2
BSON
Available as extension on GitHub since 2013
JSONB
Available since 9.4
Compressed JSON
Fully transactional
Up to 1 GB (uses TOAST)
JSON Functions
row_to_json({row})
Returns the row as JSON
array_to_json({array})
Returns the array as JSON
jsonb_to_recordset
Returns a recordset from JSONB
JSON Opertators
Array element
->{int}
Array element by name
->{text}
Object element
->> {text}
Value at path
#> {text}
Index on JSON
Index JSONB content for faster access with indexes
GIN index overall
CREATE INDEX idx_1 ON jsonb.actor USING
GIN (jsondata);
Even unique B-Tree indexes are possible
CREATE UNIQUE INDEX actor_id_2 ON
jsonb.actor((CAST(jsondata->>'actor_id' AS
INTEGER)));
New JSON functions
PostgreSQL 9.5 new JSONB functions:
jsonb_pretty: Formats JSONB human readable
jsonb_set: Update or add values
PostgreSQL 9.5 new JSONB operators:
||: Concatenate two JSONB
-: Delete key
Available as extions for 9.4 at PGXN: jsonbx
Data sources
The Chinook database is available
at chinookdatabase.codeplex.com
Amazon book reviews of 1998 are
available at
examples.citusdata.com/customer_review
Chinook Tables
CTE
Common Table Expressions will be used in examples
● Example:
WITH RECURSIVE t(n) AS (
VALUES (1)
UNION ALL
SELECT n+1 FROM t WHERE n < 100
)
SELECT sum(n), min(n), max(n) FROM t;
●
Result:
Live Examples
Let's see, how it does work.
Live with Chinook data
-- Step 1: Tracks as JSON with the album identifier
WITH tracks AS
(
SELECT "AlbumId" AS album_id
, "TrackId" AS track_id
, "Name" AS track_name
FROM "Track"
)
SELECT row_to_json(tracks) AS tracks
FROM tracks
;
Live with Chinook data
-- Step 2 Abums including tracks with aritst identifier
WITH tracks AS
(
SELECT "AlbumId" AS album_id
, "TrackId" AS track_id
, "Name" AS track_name
FROM "Track"
)
, json_tracks AS
(
SELECT row_to_json(tracks) AS tracks
FROM tracks
)
, albums AS
(
SELECT a."ArtistId" AS artist_id
, a."AlbumId" AS album_id
, a."Title" AS album_title
, array_agg(t.tracks) AS album_tracks
FROM "Album" AS a
INNER JOIN json_tracks AS t
ON a."AlbumId" = (t.tracks->>'album_id')::int
GROUP BY a."ArtistId"
, a."AlbumId"
, a."Title"
)
SELECT artist_id
, array_agg(row_to_json(albums)) AS album
FROM albums
GROUP BY artist_id
;
Live with Chinook data
Live with Chinook data
-- Step 3 Return one row for an artist with all albums as VIEW
CREATE OR REPLACE VIEW v_json_artist_data AS
WITH tracks AS
(
SELECT "AlbumId" AS album_id
, "TrackId" AS track_id
, "Name" AS track_name
, "MediaTypeId" AS media_type_id
, "Milliseconds" As milliseconds
, "UnitPrice" AS unit_price
FROM "Track"
)
, json_tracks AS
(
SELECT row_to_json(tracks) AS tracks
FROM tracks
)
, albums AS
(
SELECT a."ArtistId" AS artist_id
, a."AlbumId" AS album_id
, a."Title" AS album_title
, array_agg(t.tracks) AS album_tracks
FROM "Album" AS a
INNER JOIN json_tracks AS t
ON a."AlbumId" = (t.tracks->>'album_id')::int
GROUP BY a."ArtistId"
, a."AlbumId"
, a."Title"
)
, json_albums AS
(
SELECT artist_id
, array_agg(row_to_json(albums)) AS album
FROM albums
GROUP BY artist_id
)
-- -> Next Page
Live with Chinook data
-- Step 3 Return one row for an artist with all albums as VIEW
, artists AS
(
SELECT a."ArtistId" AS artist_id
, a."Name" AS artist
, jsa.album AS albums
FROM "Artist" AS a
INNER JOIN json_albums AS jsa
ON a."ArtistId" = jsa.artist_id
)
SELECT (row_to_json(artists))::jsonb AS artist_data
FROM artists
;
Live with Chinook data
-- Select data from the view
SELECT *
FROM v_json_artist_data
;
Live with Chinook data
-- SELECT data from that VIEW, that does querying
SELECT jsonb_pretty(artist_data)
FROM v_json_artist_data
WHERE artist_data->>'artist' IN ('Miles Davis', 'AC/DC')
;
Live with Chinook data
-- SELECT some data from that VIEW using JSON methods
SELECT artist_data->>'artist' AS artist
, artist_data#>'{albums, 1, album_title}' AS album_title
, jsonb_pretty(artist_data#>'{albums, 1, album_tracks}') AS album_tracks
FROM v_json_artist_data
WHERE artist_data->'albums' @> '[{"album_title":"Miles Ahead"}]'
;
Live with Chinook data
-- Array to records
SELECT artist_data->>'artist_id' AS artist_id
, artist_data->>'artist' AS artist
, jsonb_array_elements(artist_data#>'{albums}')->>'album_title' AS album_title
, jsonb_array_elements(jsonb_array_elements(artist_data#>'{albums}')#>'{album_tracks}')->>'track_name' AS song_titles
, jsonb_array_elements(jsonb_array_elements(artist_data#>'{albums}')#>'{album_tracks}')->>'track_id' AS song_id
FROM v_json_artist_data
WHERE artist_data->>'artist' = 'Metallica'
ORDER BY album_title
, song_id
;
Live with Chinook data
-- Convert albums to a recordset
SELECT *
FROM jsonb_to_recordset(
(
SELECT (artist_data->>'albums')::jsonb
FROM v_json_artist_data
WHERE (artist_data->>'artist_id')::int = 50
)
) AS x(album_id int, artist_id int, album_title text, album_tracks jsonb)
;
Live with Chinook data
-- Convert the tracks to a recordset
SELECT album_id
, track_id
, track_name
, media_type_id
, milliseconds
, unit_price
FROM jsonb_to_recordset(
(
SELECT artist_data#>'{albums, 1, album_tracks}'
FROM v_json_artist_data
WHERE (artist_data->>'artist_id')::int = 50
)
) AS x(album_id int, track_id int, track_name text, media_type_id int, milliseconds int, unit_price float)
;
Live with Chinook data
-- Create a function, which will be used for UPDATE on the view v_artrist_data
CREATE OR REPLACE FUNCTION trigger_v_json_artist_data_update()
RETURNS trigger AS
$BODY$
-- Data variables
DECLARE rec RECORD;
-- Error variables
DECLARE v_state TEXT;
DECLARE v_msg TEXT;
DECLARE v_detail TEXT;
DECLARE v_hint TEXT;
DECLARE v_context TEXT;
BEGIN
-- Update table Artist
IF (OLD.artist_data->>'artist')::varchar(120) <> (NEW.artist_data->>'artist')::varchar(120) THEN
UPDATE "Artist"
SET "Name" = (NEW.artist_data->>'artist')::varchar(120)
WHERE "ArtistId" = (OLD.artist_data->>'artist_id')::int;
END IF;
-- Update table Album with an UPSERT
-- Update table Track with an UPSERT
RETURN NEW;
EXCEPTION WHEN unique_violation THEN
RAISE NOTICE 'Sorry, but the something went wrong while trying to update artist data';
RETURN OLD;
WHEN others THEN
GET STACKED DIAGNOSTICS
v_state = RETURNED_SQLSTATE,
v_msg = MESSAGE_TEXT,
v_detail = PG_EXCEPTION_DETAIL,
v_hint = PG_EXCEPTION_HINT,
v_context = PG_EXCEPTION_CONTEXT;
RAISE NOTICE '%', v_msg;
RETURN OLD;
END;
$BODY$
LANGUAGE plpgsql;
Live with Chinook data
Live with Chinook data
-- The trigger will be fired instead of an UPDATE statement to save data
CREATE TRIGGER v_json_artist_data_instead_update INSTEAD OF UPDATE
ON v_json_artist_data
FOR EACH ROW
EXECUTE PROCEDURE trigger_v_json_artist_data_update()
;
Live with Chinook data
-- Manipulate data with jsonb_set
SELECT artist_data->>'artist_id' AS artist_id
, artist_data->>'artist' AS artist
, jsonb_set(artist_data, '{artist}', '"Whatever we want, it is just text"'::jsonb)->>'artist' AS new_artist
FROM v_json_artist_data
WHERE (artist_data->>'artist_id')::int = 50
;
Live with Chinook data
-- Update a JSONB column with a jsonb_set result
UPDATE v_json_artist_data
SET artist_data= jsonb_set(artist_data, '{artist}', '"NEW Metallica"'::jsonb)
WHERE (artist_data->>'artist_id')::int = 50
;
Live with Chinook data
-- View the changes done by the UPDATE statement
SELECT artist_data->>'artist_id' AS artist_id
, artist_data->>'artist' AS artist
FROM v_json_artist_data
WHERE (artist_data->>'artist_id')::int = 50
;
Live with Chinook data
-- Lets have a view on the explain plans
– SELECT the data from the view
Live with Chinook data
-- View the changes in in the table instead of the JSONB view
-- The result should be the same, only the column name differ
SELECT *
FROM "Artist"
WHERE "ArtistId" = 50
;
Live with Chinook data
-- Lets have a view on the explain plans
– SELECT the data from table Artist
-- Manipulate data with the concatenating / overwrite operator
SELECT artist_data->>'artist_id' AS artist_id
, artist_data->>'artist' AS artist
, jsonb_set(artist_data, '{artist}', '"Whatever we want, it is just text"'::jsonb)->>'artist' AS new_artist
, artist_data || '{"artist":"Metallica"}'::jsonb->>'artist' AS correct_name
FROM v_json_artist_data
WHERE (artist_data->>'artist_id')::int = 50
;
Live with Chinook data
Live with Chinook data
-- Revert the name change of Metallica with in a different way: With the replace operator
UPDATE v_json_artist_data
SET artist_data = artist_data || '{"artist":"Metallica"}'::jsonb
WHERE (artist_data->>'artist_id')::int = 50
;
Live with Chinook data
-- View the changes done by the UPDATE statement with the replace operator
SELECT artist_data->>'artist_id' AS artist_id
, artist_data->>'artist' AS artist
FROM v_json_artist_data
WHERE (artist_data->>'artist_id')::int = 50
;
Live with Chinook data
-- Remove some data with the - operator
SELECT jsonb_pretty(artist_data) AS complete
, jsonb_pretty(artist_data - 'albums') AS minus_albums
, jsonb_pretty(artist_data) = jsonb_pretty(artist_data - 'albums') AS is_different
FROM v_json_artist_data
WHERE artist_data->>'artist' IN ('Miles Davis', 'AC/DC')
;
Live Amazon reviews
-- Create a table for JSON data with 1998 Amazon reviews
CREATE TABLE reviews(review_jsonb jsonb);
Live Amazon reviews
-- Import customer reviews from a file
COPY reviews
FROM '/var/tmp/customer_reviews_nested_1998.json'
;
Live Amazon reviews
-- There should be 589.859 records imported into the table
SELECT count(*)
FROM reviews
;
Live Amazon reviews
SELECT jsonb_pretty(review_jsonb)
FROM reviews
LIMIT 1
;
Live Amazon reviews
-- Select data with JSON
SELECT
review_jsonb#>> '{product,title}' AS title
, avg((review_jsonb#>> '{review,rating}')::int) AS average_rating
FROM reviews
WHERE review_jsonb@>'{"product": {"category": "Sheet Music & Scores"}}'
GROUP BY title
ORDER BY average_rating DESC
;
Without an Index: 248ms
Live Amazon reviews
-- Create a GIN index
CREATE INDEX review_review_jsonb ON reviews USING GIN (review_jsonb);
Live Amazon reviews
-- Select data with JSON
SELECT review_jsonb#>> '{product,title}' AS title
, avg((review_jsonb#>> '{review,rating}')::int) AS average_rating
FROM reviews
WHERE review_jsonb@>'{"product": {"category": "Sheet Music & Scores"}}'
GROUP BY title
ORDER BY average_rating DESC
;
The same query as before with the previously created GIN Index: 7ms
Live Amazon reviews
-- SELECT some statistics from the JSON data
SELECT review_jsonb#>>'{product,category}' AS category
, avg((review_jsonb#>>'{review,rating}')::int) AS average_rating
, count((review_jsonb#>>'{review,rating}')::int) AS count_rating
FROM reviews
GROUP BY category
;
Without an Index: 9747ms
Live Amazon reviews
-- Create a B-Tree index on a JSON expression
CREATE INDEX reviews_product_category ON reviews ((review_jsonb#>>'{product,category}'));
Live Amazon reviews
-- SELECT some statistics from the JSON data
SELECT review_jsonb#>>'{product,category}' AS category
, avg((review_jsonb#>>'{review,rating}')::int) AS average_rating
, count((review_jsonb#>>'{review,rating}')::int) AS count_rating
FROM reviews
GROUP BY category
;
The same query as before with the previously created BTREE Index: 1605ms
JSON by example
This document by Stefanie Janine Stölting is covered by the
Creative Commons Attribution 4.0 International

Más contenido relacionado

La actualidad más candente

Data Munging in R - Chicago R User Group
Data Munging in R - Chicago R User GroupData Munging in R - Chicago R User Group
Data Munging in R - Chicago R User Groupdesignandanalytics
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門Hiromi Ishii
 
Template Haskell とか
Template Haskell とかTemplate Haskell とか
Template Haskell とかHiromi Ishii
 
Efficient Use of indexes in MySQL
Efficient Use of indexes in MySQLEfficient Use of indexes in MySQL
Efficient Use of indexes in MySQLAleksandr Kuzminsky
 
R for Pirates. ESCCONF October 27, 2011
R for Pirates. ESCCONF October 27, 2011R for Pirates. ESCCONF October 27, 2011
R for Pirates. ESCCONF October 27, 2011Mandi Walls
 
Deconstructing the Functional Web with Clojure
Deconstructing the Functional Web with ClojureDeconstructing the Functional Web with Clojure
Deconstructing the Functional Web with ClojureNorman Richards
 
Drools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL SyntaxDrools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL SyntaxMauricio (Salaboy) Salatino
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland
 
Drools5 Community Training HandsOn 1 Drools DRL Syntax
Drools5 Community Training HandsOn 1 Drools DRL SyntaxDrools5 Community Training HandsOn 1 Drools DRL Syntax
Drools5 Community Training HandsOn 1 Drools DRL SyntaxMauricio (Salaboy) Salatino
 
Switching from java to groovy
Switching from java to groovySwitching from java to groovy
Switching from java to groovyPaul Woods
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Waytdc-globalcode
 
API Development and Scala @ SoundCloud
API Development and Scala @ SoundCloudAPI Development and Scala @ SoundCloud
API Development and Scala @ SoundCloudBora Tunca
 

La actualidad más candente (15)

Rug hogan-10-03-2012
Rug hogan-10-03-2012Rug hogan-10-03-2012
Rug hogan-10-03-2012
 
Data Munging in R - Chicago R User Group
Data Munging in R - Chicago R User GroupData Munging in R - Chicago R User Group
Data Munging in R - Chicago R User Group
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門
 
Template Haskell とか
Template Haskell とかTemplate Haskell とか
Template Haskell とか
 
Efficient Use of indexes in MySQL
Efficient Use of indexes in MySQLEfficient Use of indexes in MySQL
Efficient Use of indexes in MySQL
 
R for Pirates. ESCCONF October 27, 2011
R for Pirates. ESCCONF October 27, 2011R for Pirates. ESCCONF October 27, 2011
R for Pirates. ESCCONF October 27, 2011
 
Efficient Indexes in MySQL
Efficient Indexes in MySQLEfficient Indexes in MySQL
Efficient Indexes in MySQL
 
Deconstructing the Functional Web with Clojure
Deconstructing the Functional Web with ClojureDeconstructing the Functional Web with Clojure
Deconstructing the Functional Web with Clojure
 
Drools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL SyntaxDrools5 Community Training Module 3 Drools Expert DRL Syntax
Drools5 Community Training Module 3 Drools Expert DRL Syntax
 
Python Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit TestingPython Ireland Nov 2010 Talk: Unit Testing
Python Ireland Nov 2010 Talk: Unit Testing
 
Drools5 Community Training HandsOn 1 Drools DRL Syntax
Drools5 Community Training HandsOn 1 Drools DRL SyntaxDrools5 Community Training HandsOn 1 Drools DRL Syntax
Drools5 Community Training HandsOn 1 Drools DRL Syntax
 
Switching from java to groovy
Switching from java to groovySwitching from java to groovy
Switching from java to groovy
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 
API Development and Scala @ SoundCloud
API Development and Scala @ SoundCloudAPI Development and Scala @ SoundCloud
API Development and Scala @ SoundCloud
 
Experimental.flow
Experimental.flowExperimental.flow
Experimental.flow
 

Destacado

The NoSQL Way in Postgres
The NoSQL Way in PostgresThe NoSQL Way in Postgres
The NoSQL Way in PostgresEDB
 
Postgres NoSQL - Delivering Apps Faster
Postgres NoSQL - Delivering Apps FasterPostgres NoSQL - Delivering Apps Faster
Postgres NoSQL - Delivering Apps FasterEDB
 
NoSQL on ACID: Meet Unstructured Postgres
NoSQL on ACID: Meet Unstructured PostgresNoSQL on ACID: Meet Unstructured Postgres
NoSQL on ACID: Meet Unstructured PostgresEDB
 
Useful PostgreSQL Extensions
Useful PostgreSQL ExtensionsUseful PostgreSQL Extensions
Useful PostgreSQL ExtensionsEDB
 
EEC_School Funding Memo
EEC_School Funding MemoEEC_School Funding Memo
EEC_School Funding MemoSharonne Navas
 
Nymbus_650_Presentation-short
Nymbus_650_Presentation-shortNymbus_650_Presentation-short
Nymbus_650_Presentation-shortSteven Matthews
 
To travel to the united states presentacion.,,,,,
To travel to the united states presentacion.,,,,,To travel to the united states presentacion.,,,,,
To travel to the united states presentacion.,,,,,Ivan Santy
 
Marcella Marletta - IX Conferenza Nazionale sui Dispositivi Medici
Marcella Marletta - IX Conferenza Nazionale sui Dispositivi MediciMarcella Marletta - IX Conferenza Nazionale sui Dispositivi Medici
Marcella Marletta - IX Conferenza Nazionale sui Dispositivi MediciMarcella Marletta
 
Karls Amended CV 2015
Karls Amended CV 2015Karls Amended CV 2015
Karls Amended CV 2015Karl Starkey
 
Email Converter Tools
Email Converter ToolsEmail Converter Tools
Email Converter ToolsSonika Rawat
 

Destacado (18)

The NoSQL Way in Postgres
The NoSQL Way in PostgresThe NoSQL Way in Postgres
The NoSQL Way in Postgres
 
Postgres NoSQL - Delivering Apps Faster
Postgres NoSQL - Delivering Apps FasterPostgres NoSQL - Delivering Apps Faster
Postgres NoSQL - Delivering Apps Faster
 
NoSQL on ACID: Meet Unstructured Postgres
NoSQL on ACID: Meet Unstructured PostgresNoSQL on ACID: Meet Unstructured Postgres
NoSQL on ACID: Meet Unstructured Postgres
 
Useful PostgreSQL Extensions
Useful PostgreSQL ExtensionsUseful PostgreSQL Extensions
Useful PostgreSQL Extensions
 
Bruno mars
Bruno marsBruno mars
Bruno mars
 
Hen party weekends
Hen party weekendsHen party weekends
Hen party weekends
 
EEC_School Funding Memo
EEC_School Funding MemoEEC_School Funding Memo
EEC_School Funding Memo
 
DB
DBDB
DB
 
Cloud Foundry Foundation Overview
Cloud Foundry Foundation OverviewCloud Foundry Foundation Overview
Cloud Foundry Foundation Overview
 
Nymbus_650_Presentation-short
Nymbus_650_Presentation-shortNymbus_650_Presentation-short
Nymbus_650_Presentation-short
 
Bab iii
Bab iiiBab iii
Bab iii
 
To travel to the united states presentacion.,,,,,
To travel to the united states presentacion.,,,,,To travel to the united states presentacion.,,,,,
To travel to the united states presentacion.,,,,,
 
Marcella Marletta - IX Conferenza Nazionale sui Dispositivi Medici
Marcella Marletta - IX Conferenza Nazionale sui Dispositivi MediciMarcella Marletta - IX Conferenza Nazionale sui Dispositivi Medici
Marcella Marletta - IX Conferenza Nazionale sui Dispositivi Medici
 
Bab vi
Bab viBab vi
Bab vi
 
Karls Amended CV 2015
Karls Amended CV 2015Karls Amended CV 2015
Karls Amended CV 2015
 
Vipra july
Vipra julyVipra july
Vipra july
 
10 Ways To Reduce Stress
10 Ways To Reduce Stress10 Ways To Reduce Stress
10 Ways To Reduce Stress
 
Email Converter Tools
Email Converter ToolsEmail Converter Tools
Email Converter Tools
 

Similar a The PostgreSQL JSON Feature Tour

Postgre(No)SQL - A JSON journey
Postgre(No)SQL - A JSON journeyPostgre(No)SQL - A JSON journey
Postgre(No)SQL - A JSON journeyNicola Moretto
 
Functional Programming in Java 8
Functional Programming in Java 8Functional Programming in Java 8
Functional Programming in Java 8宇 傅
 
I need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdfI need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdfmail931892
 
8.8 Program Playlist (Java)You will be building a linked list. Ma.pdf
8.8 Program Playlist (Java)You will be building a linked list. Ma.pdf8.8 Program Playlist (Java)You will be building a linked list. Ma.pdf
8.8 Program Playlist (Java)You will be building a linked list. Ma.pdfARCHANASTOREKOTA
 
JSON Support in MariaDB: News, non-news and the bigger picture
JSON Support in MariaDB: News, non-news and the bigger pictureJSON Support in MariaDB: News, non-news and the bigger picture
JSON Support in MariaDB: News, non-news and the bigger pictureSergey Petrunya
 
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...Paul Leclercq
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the WildJosé Paumard
 
Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Jung Kim
 
Here is the code.compile g++ Playlist.cpp main.cppPlaylist.h.pdf
Here is the code.compile  g++ Playlist.cpp main.cppPlaylist.h.pdfHere is the code.compile  g++ Playlist.cpp main.cppPlaylist.h.pdf
Here is the code.compile g++ Playlist.cpp main.cppPlaylist.h.pdfANANDSALESINDIA105
 
Whatnot (Re)Compose
Whatnot (Re)Compose Whatnot (Re)Compose
Whatnot (Re)Compose Whatnot3
 
Querier – simple relational database access
Querier – simple relational database accessQuerier – simple relational database access
Querier – simple relational database accessESUG
 
Index management in depth
Index management in depthIndex management in depth
Index management in depthAndrea Giuliano
 
Can someone please help me implement the addSong function .pdf
Can someone please help me implement the addSong function .pdfCan someone please help me implement the addSong function .pdf
Can someone please help me implement the addSong function .pdfakshpatil4
 

Similar a The PostgreSQL JSON Feature Tour (17)

One Database To Rule 'em All
One Database To Rule 'em AllOne Database To Rule 'em All
One Database To Rule 'em All
 
Postgre(No)SQL - A JSON journey
Postgre(No)SQL - A JSON journeyPostgre(No)SQL - A JSON journey
Postgre(No)SQL - A JSON journey
 
Functional Programming in Java 8
Functional Programming in Java 8Functional Programming in Java 8
Functional Programming in Java 8
 
I need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdfI need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdf
 
8.8 Program Playlist (Java)You will be building a linked list. Ma.pdf
8.8 Program Playlist (Java)You will be building a linked list. Ma.pdf8.8 Program Playlist (Java)You will be building a linked list. Ma.pdf
8.8 Program Playlist (Java)You will be building a linked list. Ma.pdf
 
Oh, that ubiquitous JSON !
Oh, that ubiquitous JSON !Oh, that ubiquitous JSON !
Oh, that ubiquitous JSON !
 
JSON Support in MariaDB: News, non-news and the bigger picture
JSON Support in MariaDB: News, non-news and the bigger pictureJSON Support in MariaDB: News, non-news and the bigger picture
JSON Support in MariaDB: News, non-news and the bigger picture
 
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...
Analyze one year of radio station songs aired with Spark SQL, Spotify, and Da...
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법
 
Here is the code.compile g++ Playlist.cpp main.cppPlaylist.h.pdf
Here is the code.compile  g++ Playlist.cpp main.cppPlaylist.h.pdfHere is the code.compile  g++ Playlist.cpp main.cppPlaylist.h.pdf
Here is the code.compile g++ Playlist.cpp main.cppPlaylist.h.pdf
 
Whatnot (Re)Compose
Whatnot (Re)Compose Whatnot (Re)Compose
Whatnot (Re)Compose
 
Querier – simple relational database access
Querier – simple relational database accessQuerier – simple relational database access
Querier – simple relational database access
 
Big Data Analytics Part2
Big Data Analytics Part2Big Data Analytics Part2
Big Data Analytics Part2
 
Index management in depth
Index management in depthIndex management in depth
Index management in depth
 
Neo4j (Part 1)
Neo4j (Part 1)Neo4j (Part 1)
Neo4j (Part 1)
 
Can someone please help me implement the addSong function .pdf
Can someone please help me implement the addSong function .pdfCan someone please help me implement the addSong function .pdf
Can someone please help me implement the addSong function .pdf
 

Último

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Último (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

The PostgreSQL JSON Feature Tour

  • 1. The JSON Feature Tour 5432 … Meet Us! June 2016 Stefanie Janine Stölting Head of Product Development @sjstoelting Stefanie@paxlife.aero
  • 2.
  • 3. JSON JavaScript Object Notation Don't have to care about encoding, it is always Unicode, most implementations use UTF8 Used for data exchange in web application Currently two standards RFC 7159 by Douglas Crockford and ECMA-404 PostgreSQL implementation is RFC 7159
  • 4. JSON Datatypes JSON Available since 9.2 BSON Available as extension on GitHub since 2013 JSONB Available since 9.4 Compressed JSON Fully transactional Up to 1 GB (uses TOAST)
  • 5. JSON Functions row_to_json({row}) Returns the row as JSON array_to_json({array}) Returns the array as JSON jsonb_to_recordset Returns a recordset from JSONB
  • 6. JSON Opertators Array element ->{int} Array element by name ->{text} Object element ->> {text} Value at path #> {text}
  • 7. Index on JSON Index JSONB content for faster access with indexes GIN index overall CREATE INDEX idx_1 ON jsonb.actor USING GIN (jsondata); Even unique B-Tree indexes are possible CREATE UNIQUE INDEX actor_id_2 ON jsonb.actor((CAST(jsondata->>'actor_id' AS INTEGER)));
  • 8. New JSON functions PostgreSQL 9.5 new JSONB functions: jsonb_pretty: Formats JSONB human readable jsonb_set: Update or add values PostgreSQL 9.5 new JSONB operators: ||: Concatenate two JSONB -: Delete key Available as extions for 9.4 at PGXN: jsonbx
  • 9. Data sources The Chinook database is available at chinookdatabase.codeplex.com Amazon book reviews of 1998 are available at examples.citusdata.com/customer_review
  • 11. CTE Common Table Expressions will be used in examples ● Example: WITH RECURSIVE t(n) AS ( VALUES (1) UNION ALL SELECT n+1 FROM t WHERE n < 100 ) SELECT sum(n), min(n), max(n) FROM t; ● Result:
  • 12. Live Examples Let's see, how it does work.
  • 13. Live with Chinook data -- Step 1: Tracks as JSON with the album identifier WITH tracks AS ( SELECT "AlbumId" AS album_id , "TrackId" AS track_id , "Name" AS track_name FROM "Track" ) SELECT row_to_json(tracks) AS tracks FROM tracks ;
  • 14. Live with Chinook data -- Step 2 Abums including tracks with aritst identifier WITH tracks AS ( SELECT "AlbumId" AS album_id , "TrackId" AS track_id , "Name" AS track_name FROM "Track" ) , json_tracks AS ( SELECT row_to_json(tracks) AS tracks FROM tracks ) , albums AS ( SELECT a."ArtistId" AS artist_id , a."AlbumId" AS album_id , a."Title" AS album_title , array_agg(t.tracks) AS album_tracks FROM "Album" AS a INNER JOIN json_tracks AS t ON a."AlbumId" = (t.tracks->>'album_id')::int GROUP BY a."ArtistId" , a."AlbumId" , a."Title" ) SELECT artist_id , array_agg(row_to_json(albums)) AS album FROM albums GROUP BY artist_id ;
  • 16. Live with Chinook data -- Step 3 Return one row for an artist with all albums as VIEW CREATE OR REPLACE VIEW v_json_artist_data AS WITH tracks AS ( SELECT "AlbumId" AS album_id , "TrackId" AS track_id , "Name" AS track_name , "MediaTypeId" AS media_type_id , "Milliseconds" As milliseconds , "UnitPrice" AS unit_price FROM "Track" ) , json_tracks AS ( SELECT row_to_json(tracks) AS tracks FROM tracks ) , albums AS ( SELECT a."ArtistId" AS artist_id , a."AlbumId" AS album_id , a."Title" AS album_title , array_agg(t.tracks) AS album_tracks FROM "Album" AS a INNER JOIN json_tracks AS t ON a."AlbumId" = (t.tracks->>'album_id')::int GROUP BY a."ArtistId" , a."AlbumId" , a."Title" ) , json_albums AS ( SELECT artist_id , array_agg(row_to_json(albums)) AS album FROM albums GROUP BY artist_id ) -- -> Next Page
  • 17. Live with Chinook data -- Step 3 Return one row for an artist with all albums as VIEW , artists AS ( SELECT a."ArtistId" AS artist_id , a."Name" AS artist , jsa.album AS albums FROM "Artist" AS a INNER JOIN json_albums AS jsa ON a."ArtistId" = jsa.artist_id ) SELECT (row_to_json(artists))::jsonb AS artist_data FROM artists ;
  • 18. Live with Chinook data -- Select data from the view SELECT * FROM v_json_artist_data ;
  • 19. Live with Chinook data -- SELECT data from that VIEW, that does querying SELECT jsonb_pretty(artist_data) FROM v_json_artist_data WHERE artist_data->>'artist' IN ('Miles Davis', 'AC/DC') ;
  • 20. Live with Chinook data -- SELECT some data from that VIEW using JSON methods SELECT artist_data->>'artist' AS artist , artist_data#>'{albums, 1, album_title}' AS album_title , jsonb_pretty(artist_data#>'{albums, 1, album_tracks}') AS album_tracks FROM v_json_artist_data WHERE artist_data->'albums' @> '[{"album_title":"Miles Ahead"}]' ;
  • 21. Live with Chinook data -- Array to records SELECT artist_data->>'artist_id' AS artist_id , artist_data->>'artist' AS artist , jsonb_array_elements(artist_data#>'{albums}')->>'album_title' AS album_title , jsonb_array_elements(jsonb_array_elements(artist_data#>'{albums}')#>'{album_tracks}')->>'track_name' AS song_titles , jsonb_array_elements(jsonb_array_elements(artist_data#>'{albums}')#>'{album_tracks}')->>'track_id' AS song_id FROM v_json_artist_data WHERE artist_data->>'artist' = 'Metallica' ORDER BY album_title , song_id ;
  • 22. Live with Chinook data -- Convert albums to a recordset SELECT * FROM jsonb_to_recordset( ( SELECT (artist_data->>'albums')::jsonb FROM v_json_artist_data WHERE (artist_data->>'artist_id')::int = 50 ) ) AS x(album_id int, artist_id int, album_title text, album_tracks jsonb) ;
  • 23. Live with Chinook data -- Convert the tracks to a recordset SELECT album_id , track_id , track_name , media_type_id , milliseconds , unit_price FROM jsonb_to_recordset( ( SELECT artist_data#>'{albums, 1, album_tracks}' FROM v_json_artist_data WHERE (artist_data->>'artist_id')::int = 50 ) ) AS x(album_id int, track_id int, track_name text, media_type_id int, milliseconds int, unit_price float) ;
  • 24. Live with Chinook data -- Create a function, which will be used for UPDATE on the view v_artrist_data CREATE OR REPLACE FUNCTION trigger_v_json_artist_data_update() RETURNS trigger AS $BODY$ -- Data variables DECLARE rec RECORD; -- Error variables DECLARE v_state TEXT; DECLARE v_msg TEXT; DECLARE v_detail TEXT; DECLARE v_hint TEXT; DECLARE v_context TEXT; BEGIN -- Update table Artist IF (OLD.artist_data->>'artist')::varchar(120) <> (NEW.artist_data->>'artist')::varchar(120) THEN UPDATE "Artist" SET "Name" = (NEW.artist_data->>'artist')::varchar(120) WHERE "ArtistId" = (OLD.artist_data->>'artist_id')::int; END IF; -- Update table Album with an UPSERT -- Update table Track with an UPSERT RETURN NEW; EXCEPTION WHEN unique_violation THEN RAISE NOTICE 'Sorry, but the something went wrong while trying to update artist data'; RETURN OLD; WHEN others THEN GET STACKED DIAGNOSTICS v_state = RETURNED_SQLSTATE, v_msg = MESSAGE_TEXT, v_detail = PG_EXCEPTION_DETAIL, v_hint = PG_EXCEPTION_HINT, v_context = PG_EXCEPTION_CONTEXT; RAISE NOTICE '%', v_msg; RETURN OLD; END; $BODY$ LANGUAGE plpgsql;
  • 26. Live with Chinook data -- The trigger will be fired instead of an UPDATE statement to save data CREATE TRIGGER v_json_artist_data_instead_update INSTEAD OF UPDATE ON v_json_artist_data FOR EACH ROW EXECUTE PROCEDURE trigger_v_json_artist_data_update() ;
  • 27. Live with Chinook data -- Manipulate data with jsonb_set SELECT artist_data->>'artist_id' AS artist_id , artist_data->>'artist' AS artist , jsonb_set(artist_data, '{artist}', '"Whatever we want, it is just text"'::jsonb)->>'artist' AS new_artist FROM v_json_artist_data WHERE (artist_data->>'artist_id')::int = 50 ;
  • 28. Live with Chinook data -- Update a JSONB column with a jsonb_set result UPDATE v_json_artist_data SET artist_data= jsonb_set(artist_data, '{artist}', '"NEW Metallica"'::jsonb) WHERE (artist_data->>'artist_id')::int = 50 ;
  • 29. Live with Chinook data -- View the changes done by the UPDATE statement SELECT artist_data->>'artist_id' AS artist_id , artist_data->>'artist' AS artist FROM v_json_artist_data WHERE (artist_data->>'artist_id')::int = 50 ;
  • 30. Live with Chinook data -- Lets have a view on the explain plans – SELECT the data from the view
  • 31. Live with Chinook data -- View the changes in in the table instead of the JSONB view -- The result should be the same, only the column name differ SELECT * FROM "Artist" WHERE "ArtistId" = 50 ;
  • 32. Live with Chinook data -- Lets have a view on the explain plans – SELECT the data from table Artist
  • 33. -- Manipulate data with the concatenating / overwrite operator SELECT artist_data->>'artist_id' AS artist_id , artist_data->>'artist' AS artist , jsonb_set(artist_data, '{artist}', '"Whatever we want, it is just text"'::jsonb)->>'artist' AS new_artist , artist_data || '{"artist":"Metallica"}'::jsonb->>'artist' AS correct_name FROM v_json_artist_data WHERE (artist_data->>'artist_id')::int = 50 ; Live with Chinook data
  • 34. Live with Chinook data -- Revert the name change of Metallica with in a different way: With the replace operator UPDATE v_json_artist_data SET artist_data = artist_data || '{"artist":"Metallica"}'::jsonb WHERE (artist_data->>'artist_id')::int = 50 ;
  • 35. Live with Chinook data -- View the changes done by the UPDATE statement with the replace operator SELECT artist_data->>'artist_id' AS artist_id , artist_data->>'artist' AS artist FROM v_json_artist_data WHERE (artist_data->>'artist_id')::int = 50 ;
  • 36. Live with Chinook data -- Remove some data with the - operator SELECT jsonb_pretty(artist_data) AS complete , jsonb_pretty(artist_data - 'albums') AS minus_albums , jsonb_pretty(artist_data) = jsonb_pretty(artist_data - 'albums') AS is_different FROM v_json_artist_data WHERE artist_data->>'artist' IN ('Miles Davis', 'AC/DC') ;
  • 37. Live Amazon reviews -- Create a table for JSON data with 1998 Amazon reviews CREATE TABLE reviews(review_jsonb jsonb);
  • 38. Live Amazon reviews -- Import customer reviews from a file COPY reviews FROM '/var/tmp/customer_reviews_nested_1998.json' ;
  • 39. Live Amazon reviews -- There should be 589.859 records imported into the table SELECT count(*) FROM reviews ;
  • 40. Live Amazon reviews SELECT jsonb_pretty(review_jsonb) FROM reviews LIMIT 1 ;
  • 41. Live Amazon reviews -- Select data with JSON SELECT review_jsonb#>> '{product,title}' AS title , avg((review_jsonb#>> '{review,rating}')::int) AS average_rating FROM reviews WHERE review_jsonb@>'{"product": {"category": "Sheet Music & Scores"}}' GROUP BY title ORDER BY average_rating DESC ; Without an Index: 248ms
  • 42. Live Amazon reviews -- Create a GIN index CREATE INDEX review_review_jsonb ON reviews USING GIN (review_jsonb);
  • 43. Live Amazon reviews -- Select data with JSON SELECT review_jsonb#>> '{product,title}' AS title , avg((review_jsonb#>> '{review,rating}')::int) AS average_rating FROM reviews WHERE review_jsonb@>'{"product": {"category": "Sheet Music & Scores"}}' GROUP BY title ORDER BY average_rating DESC ; The same query as before with the previously created GIN Index: 7ms
  • 44. Live Amazon reviews -- SELECT some statistics from the JSON data SELECT review_jsonb#>>'{product,category}' AS category , avg((review_jsonb#>>'{review,rating}')::int) AS average_rating , count((review_jsonb#>>'{review,rating}')::int) AS count_rating FROM reviews GROUP BY category ; Without an Index: 9747ms
  • 45. Live Amazon reviews -- Create a B-Tree index on a JSON expression CREATE INDEX reviews_product_category ON reviews ((review_jsonb#>>'{product,category}'));
  • 46. Live Amazon reviews -- SELECT some statistics from the JSON data SELECT review_jsonb#>>'{product,category}' AS category , avg((review_jsonb#>>'{review,rating}')::int) AS average_rating , count((review_jsonb#>>'{review,rating}')::int) AS count_rating FROM reviews GROUP BY category ; The same query as before with the previously created BTREE Index: 1605ms
  • 47. JSON by example This document by Stefanie Janine Stölting is covered by the Creative Commons Attribution 4.0 International