SlideShare ist ein Scribd-Unternehmen logo
1 von 54
BreizhCamp 2015 #BzhCmp
#pgnosql
Not only SQL avec
PostgreSQL
Pierre-Alban DEWITTE - @__pad__
dev.myscript.com
TROLL
Source : http://www.enterprisedb.com/nosql-for-enterprise
JSONB et Postgresql
Histoire du type JSONB
● 2006 – HSTORE – Stockage
clef/valeur
● 2012 – JSON - JavaScript Object
Notation
● 2014 – JSONB – JSON Binaire
Introduit par Oleg Bartunov, Teodor
Sigaev, Peter Geoghegan and
Andrew Dunstan dans Postgresql 9.4
Caractéristiques du type JSONB
• Permet de stocker un document JSON
synthaxiquement valide
• Stocker en interne sous une forme binaire
permettant l’indexation
En comparaison du format JSON
• Léger surcout à l’insertion
• Attention, contrairement à un chaine de
charactère, l’ordre des objets n’est pas
conservé
• Les attributs avec le même nom ne sont pas
conservés
Modélisation
Possibilités offertes
• Ajouter simplement de la flexibilité au
schéma
• Modéliser les données en fonction des use
cases
• Regroupement dans une même entités
l’ensemble des informations constituant
sont identité
Application de démo
● Utilisation des données MovieLens
http://grouplens.org/datasets/movielens/
Modèle Conceptuel de Données
Movie
Integer id
String year
String title
Integer imdbId
Integer tmdbId
Ratings
Integer userId
Integer movieId
Float rating
Date date
0.. n
1
Tags
Integer userId
Integer movieId
String tag
Date date
1
0.. n
Modèle orienté document
{ "id" : 0, //Integer
"year" : "...", //String
"title" : "...", //String
"imdbId" : "...", //Integer
"tmdbId" : "...", //Integer
"tags" : [{ //Array of tags
"userId" : 0, //Integer
"tag" : "...", //String
"date" : "..." //String
}],
"ratings" : [{ //Array of ratings
"userId" : 0, //Integer
"rating" : "...", //String
"date" : "..." //String
}]
}
Modèle hybride – PGsql 9.4
Movie
Integer id
String year
String title
Integer imdbId
Integer tmdbId
Jsonb otherInformations
{
"tags" : [{
"userId" : 0,
"tag" : "...",
"date" : "..."
}],
"ratings" : [{
"userId" : 0,
"rating" : "...",
"date" : "..."
}]
}
Créer le schéma
Colonne JSONB
CREATE TABLE movies
(
id integer primary key,
name character varying(200),
year character varying(4),
imdbid integer,
tmdbid integer,
otherInformations jsonb
);
ALTER TABLE books
ADD COLUMN "otherInformations" jsonb;
Insérer un enregistrement
INSERT INTO movies
(id, name, year, imdbid, tmdbid,
otherInformations)
VALUES (666666, 'Diabolic movie', 1966, 666, 6666,
'{"ratings" : [
{"userId" : 4,"rating" : 3},
{"userId" : 5,"rating" : 5},
]
}'
);
• Insertion des champs JSON dans
un chaine de charactère.
• Validation synthaxique effectuée
par le moteur
Insérer un enregistrement
● Nombreuses fonctions permettant de convertir
un enregistrement en jsonb
● Et vis-versa
Construire un champ JSON
SELECT row_to_json(movies.*)
FROM movies
LIMIT 1
-- Résultats
{"id":370,"name":"Naked Gun 33 1/3: The Final Insult
","year":"1994","imdbid":110622,"tmdbid":36593,"otherin
formations":{"tags": [{"tag": "foqam", "date":
1139200469000, "userId": 14260}, {"tag": "Leslie
Neilsen", "date": 1158438794000, "userId": 18390},
{"tag": "nazi", "date": 1161646656000, "userId":
18390}, {"tag": "sequel", "date": 1354555994000,
Fonctions de construction JSON
● to_json : convertit une valeur
● row_to_json : convertit un tuple
● json_build_array : convertit un tableau
● json_build_object : construit un object JSON
depuis un “varidic”
● json_object : construit à partir d’une chaine
● array_to_json : convertit un tableau
Requete
Requêtes
Lecture brute d'un champ
-- Lecture brute d’un champ JSON
SELECT otherinformations
FROM movies
WHERE otherinformations IS NOT NULL
LIMIT 2
-- Résultats
{"tags": [{"tag": "foqam", "date": 1139200469000,
"userId": 14260}, {"tag": "Leslie Neilsen", "date":
1158438794000, "userId": 18390}, {"tag": "nazi",
"date": 1161646656000, "userId": 18390}, {"tag":
"sequel", "date": 1354555994000, "userId": 42640},
{"tag": "Comedy", "date": 1248035546000, "userId":
60710}, {"tag": "parody", "date": 1248035543000,
Ce n’est pas du texte
-- Requête avec like
SELECT otherinformations
FROM movies
WHERE otherinformations LIKE '%tags%'
LIMIT 2
//Résultats
Could not execute SQL statement. ERROR: operator does
not exist: jsonb ~~ unknown
Indice : No operator matches the given name and
argument type(s). You might need to add explicit type
casts.
Ce n’est pas du texte
-- Requête avec like et cast
SELECT otherinformations
FROM movies
WHERE otherinformations::text LIKE '%tags%'
LIMIT 2
-- Résultats
{"tags": [{"tag": "foqam", "date": 1139200469000,
"userId": 14260}, {"tag": "Leslie Neilsen", "date":
1158438794000, "userId": 18390}, {"tag": "nazi",
"date": 1161646656000, "userId": 18390}, {"tag":
"sequel", "date": 1354555994000, "userId": 42640},
{"tag": "Comedy", "date": 1248035546000, "userId":
60710}, {"tag": "parody", "date": 1248035543000,
Modèle orienté document
{ "id" : 0, //Integer
"year" : "...", //String
"title" : "...", //String
"imdbId" : "...", //Integer
"tmdbId" : "...", //Integer
"otherInformations" : {
"averageRating" : "...",
"nbOfRatings" : "...",
"tags" : [{ //Array of tags
"userId" : 0, //Integer
"tag" : "...", //String
"date" : "..." //String
}],
"ratings" : [{ //Array of ratings
"userId" : 0, //Integer
"rating" : "...", //String
"date" : "..." //String
}]
}
Lecture d’un champ
--Lecture d'un champ
SELECT otherinformations->'averageRating'
FROM movies
WHERE (otherinformations->>'averageRating')::float > 4
-- Résultats
4.00200100050025
4.081620314389359
4.089572192513369
4.216110019646365
4.126740947075209
4.078947368421052
Lecture d’un tableau (texte)
-- Lecture texte d'un élément de tableau
SELECT otherinformations::jsonb->'tags'->>3
FROM movies
LIMIT 2
-- Résultats
{"tag": "sequel", "date": 1354555994000, "userId": 42640}
{"tag": "Nudity (Full Frontal)", "date": 1298520169000, "userId": 33860}
Lecture d’un tableau (JSON)
-- Lecture JSON d'un élément de tableau
SELECT otherinformations::jsonb->'tags'->3->'tag'
FROM movies
LIMIT 2
-- Résultats
"sequel"
"Nudity (Full Frontal)"
Tester l’existence d’un champ
-- Tester l’existence d’un champ
SELECT count(*)
FROM movies
WHERE otherinformations ? 'nbOfRatings'
-- Résultats
1715
Recherche JSON
-- Recherche JSON
SELECT id, otherinformations->'nbOfRatings'
FROM movies
WHERE
otherinformations @> '{"nbOfRatings" : 50}'::jsonb
-- Résultats
1180 50
4000 50
8690 50
Lecture avec chemin
-- Lecture avec chemin en pseudo JSON
-- Recherche du champ tag du cinquième élément du
tableau tags
-- Equivalent jsonb_extract_path et
jsonb_extract_path_text
SELECT otherinformations #> '{tags, 5, tag}'
FROM movies
LIMIT 2
-- Résultats
"parody"
"Monty Python"
Fonctions de manipulation JSON
● jsonb_array_length : nb d’éléments
d’un tableau JSONB
● jsonb_each & jsonb_each_text :
transforme chaque clé valeur en une
ligne
● jsonb_object_keys : liste des clefs
d’un object json
Fonctions de manipulation JSON
● jsonb_array_elements &
jsonb_array_elements_text : transform un
tableau JSON en tuple d’objets
● jsonb_typeof : indique le type parmi object,
array, string, number, boolean et null.
Fonctions de manipulation JSON
● jsonb_populate_record &
jsonb_populate_recordset : construit
implicitement un tuple
● json_to_record & json_to_recordset
: construit explicitement un tuple
Démo
Et les indexes ?
Et les indexes ?
-- Création d'un index sur l'ensemble du document
CREATE INDEX IDX_GIN_otherInformations
ON movies
USING GIN (otherInformations);
Un index gin améliore les requêtes suivantes :
• JSON @> JSON is a subset
• JSON ? TEXT contains a value
• JSON ?& TEXT[] contains all the values
• JSON ?| TEXT[] contains at least one value
Et les indexes ?
-- Création d'un index sur l'ensemble du document
CREATE INDEX IDX_GIN_otherInformations_opt
ON movies
USING GIN (otherInformations jsonb_path_ops);
Paramètre jsonb_path_ops optimise uniquement
les recherches avec @>
Démo
Et en JAVA ?
JDBC
● Un champ JSONB se manipule
comme un DBObject ou comme
du TEXT
● Pas de particularité dans le driver
JDBC PostgreSQL
● Nécessité d’utiliser un mapper
objet / JSON
Démo
DAO Insert
//Using Jackson to convert additional field to JSON
String ratingsAsString = new
ObjectMapper().writeValueAsString(overallRating);
… pstSetter = new PreparedStatementSetter() {
public void setValues(PreparedStatement preparedStatement)
throws SQLException {
//Using a PGObject to store otherInformations
PGobject dataObject = new PGobject();
dataObject.setType("jsonb");
dataObject.setValue(ratingsAsString);
preparedStatement.setObject(1, dataObject);
…
}
};
jdbcTemplateObject.update("UPDATE movies SET
otherInformations = ? WHERE id = ?", pstSetter);
DAO Select
jdbcTemplateObject.query("SELECT id, otherinformations::text
as text_otherinformations FROM movies WHERE otherinformations
is not null limit 2", new RowCallbackHandler() {
public void processRow(ResultSet resultSet) {
while (resultSet.next()) {
…
movie.setId(resultSet.getLong("id"));
…
movie.setOther( mapper.readValue(
resultSet.getString("text_otherinformations"),
OtherInformations.class));
…
}}});
Avec un ORM
https://github.com/pires/hibernate-postgres-jsonb
Update
Et un update ?
● Postgresql 9.4 ne possède pas
nativement d’opérateur
permettant de manipuler un
champ json
● Nécessité de lire / modifier /
updater
Manipulation avec plv8
CREATE OR REPLACE FUNCTION json_data_update(data json,
field text,
value text)
RETURNS jsonb
LANGUAGE plv8 STABLE STRICT
AS $$
var data = data;
var val = value;
data[field] = val;
return JSON.stringify(data);
$$;
Jsonbx
● Extension jsonbx en cours de
portage dans PG 9.5
-- Update avec chemin en pseudo JSON
UPDATE movies
SET otherinformations =
jsonb_replace(otherinformations, '{"tags",3,"tag"}',
'{"SUPER"}'::jsonb)
WHERE id = 1
Nouveautés PGSql 9.5
-- Add values to a jsonb object:
SELECT '{"name": "Joe", "age": 30}'::jsonb || '{"town":
"London"}'::jsonb;
-- Replace
SELECT '{"town": "Dataville", "population":
4096}'::jsonb || '{"population": 8192}'::jsonb;
-- Résultats
{"age": 30, "name": "Joe", "town": "London"}
{"town": "Dataville", "population": 8192}
Nouveautés PGSql 9.5
-- Remove a key
SELECT '{"name": "James", "email":
"james@localhost"}'::jsonb - 'email';
-- Résultats
{"name": "James"}
PG vs MongoDB
PG vs MongoDB
PG 9.4 répond aux besoins en
lecture
Puissance du SQL sous réserve
de bien maitriser les fonctions de
convertion
PG ne permet pas simplement de
mettre à jour un object JSON
PG vs MongoDB ?
Sharding plus facile
Haute disponibilité
Suivre l’actualité
http://postgresweekly.com/
http://www.craigkerstiens.com/
https://planet.postgresql.org/
http://blog.2ndquadrant.com/
@tapoueh
@petervgeoghegan
@g_lelarge
@EnterpriseDB
@craigkerstiens
Questions
#pgnosql
@__pad__
https://github.com/padewitte/bzhcamp_pgjson
Sources
Requete :
• http://www.postgresql.org/docs/9.4/static/functions-json.html
• http://adpgtech.blogspot.fr/2015/05/new-jsonb-features-for-95.html
Index
• http://blog.2ndquadrant.com/jsonb-type-performance-postgresql-9-4/
JSONB et Postgresql
• http://blog.2ndquadrant.com/postgresql-anti-patterns-unnecessary-
jsonhstore-dynamic-columns/
• http://www.pgcon.org/2014/schedule/attachments/313_xml-hstore-json.pdf
• https://www.compose.io/articles/is-postgresql-your-next-json-database/

Weitere ähnliche Inhalte

Was ist angesagt?

Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...
Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...
Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...Bruno Bonnin
 
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01-rev.
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01-rev.2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01-rev.
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01-rev.MongoDB
 
2014 04-09-fr - app dev series - session 4 - indexing
2014 04-09-fr - app dev series - session 4 - indexing2014 04-09-fr - app dev series - session 4 - indexing
2014 04-09-fr - app dev series - session 4 - indexingMongoDB
 
Elasticsearch - Montpellier JUG
Elasticsearch - Montpellier JUGElasticsearch - Montpellier JUG
Elasticsearch - Montpellier JUGDavid Pilato
 
Elasticsearch - Devoxx France 2012
Elasticsearch - Devoxx France 2012Elasticsearch - Devoxx France 2012
Elasticsearch - Devoxx France 2012David Pilato
 
Créer des applications Java avec MongoDB
Créer des applications Java avec MongoDBCréer des applications Java avec MongoDB
Créer des applications Java avec MongoDBMongoDB
 
Journées SQL 2014 - Hive ou la convergence entre datawarehouse et Big Data
Journées SQL 2014 - Hive ou la convergence entre datawarehouse et Big DataJournées SQL 2014 - Hive ou la convergence entre datawarehouse et Big Data
Journées SQL 2014 - Hive ou la convergence entre datawarehouse et Big DataDavid Joubert
 
Migrer une application existante vers Elasticsearch - Nuxeo Tour 2014 - workshop
Migrer une application existante vers Elasticsearch - Nuxeo Tour 2014 - workshopMigrer une application existante vers Elasticsearch - Nuxeo Tour 2014 - workshop
Migrer une application existante vers Elasticsearch - Nuxeo Tour 2014 - workshopNuxeo
 
Présentation mongoDB et mongoId
Présentation mongoDB et mongoIdPrésentation mongoDB et mongoId
Présentation mongoDB et mongoIdvtabary
 
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...MongoDB
 
SSL 2011 : Présentation de 2 bases noSQL
SSL 2011 : Présentation de 2 bases noSQLSSL 2011 : Présentation de 2 bases noSQL
SSL 2011 : Présentation de 2 bases noSQLHervé Leclerc
 
ElasticSearch : Architecture et Développement
ElasticSearch : Architecture et DéveloppementElasticSearch : Architecture et Développement
ElasticSearch : Architecture et DéveloppementMohamed hedi Abidi
 
MongoDB : la base NoSQL qui réinvente la gestion de données
MongoDB : la base NoSQL qui réinvente la gestion de donnéesMongoDB : la base NoSQL qui réinvente la gestion de données
MongoDB : la base NoSQL qui réinvente la gestion de donnéesSOAT
 
Finist JUG - Elasticsearch
Finist JUG - ElasticsearchFinist JUG - Elasticsearch
Finist JUG - ElasticsearchDavid Pilato
 
Découverte de Elastic search
Découverte de Elastic searchDécouverte de Elastic search
Découverte de Elastic searchJEMLI Fathi
 
Poitou charentes JUG - Elasticsearch
Poitou charentes JUG - ElasticsearchPoitou charentes JUG - Elasticsearch
Poitou charentes JUG - ElasticsearchDavid Pilato
 
Tout ce que le getting started mongo db ne vous dira pas
Tout ce que le getting started mongo db ne vous dira pasTout ce que le getting started mongo db ne vous dira pas
Tout ce que le getting started mongo db ne vous dira pasPierre-Alban DEWITTE
 

Was ist angesagt? (20)

Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...
Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...
Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...
 
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01-rev.
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01-rev.2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01-rev.
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01-rev.
 
2014 04-09-fr - app dev series - session 4 - indexing
2014 04-09-fr - app dev series - session 4 - indexing2014 04-09-fr - app dev series - session 4 - indexing
2014 04-09-fr - app dev series - session 4 - indexing
 
Elasticsearch - Montpellier JUG
Elasticsearch - Montpellier JUGElasticsearch - Montpellier JUG
Elasticsearch - Montpellier JUG
 
Elasticsearch - Devoxx France 2012
Elasticsearch - Devoxx France 2012Elasticsearch - Devoxx France 2012
Elasticsearch - Devoxx France 2012
 
Créer des applications Java avec MongoDB
Créer des applications Java avec MongoDBCréer des applications Java avec MongoDB
Créer des applications Java avec MongoDB
 
Mongo DB
Mongo DBMongo DB
Mongo DB
 
Journées SQL 2014 - Hive ou la convergence entre datawarehouse et Big Data
Journées SQL 2014 - Hive ou la convergence entre datawarehouse et Big DataJournées SQL 2014 - Hive ou la convergence entre datawarehouse et Big Data
Journées SQL 2014 - Hive ou la convergence entre datawarehouse et Big Data
 
Migrer une application existante vers Elasticsearch - Nuxeo Tour 2014 - workshop
Migrer une application existante vers Elasticsearch - Nuxeo Tour 2014 - workshopMigrer une application existante vers Elasticsearch - Nuxeo Tour 2014 - workshop
Migrer une application existante vers Elasticsearch - Nuxeo Tour 2014 - workshop
 
Présentation mongoDB et mongoId
Présentation mongoDB et mongoIdPrésentation mongoDB et mongoId
Présentation mongoDB et mongoId
 
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...
 
SSL 2011 : Présentation de 2 bases noSQL
SSL 2011 : Présentation de 2 bases noSQLSSL 2011 : Présentation de 2 bases noSQL
SSL 2011 : Présentation de 2 bases noSQL
 
ElasticSearch : Architecture et Développement
ElasticSearch : Architecture et DéveloppementElasticSearch : Architecture et Développement
ElasticSearch : Architecture et Développement
 
MongoDB : la base NoSQL qui réinvente la gestion de données
MongoDB : la base NoSQL qui réinvente la gestion de donnéesMongoDB : la base NoSQL qui réinvente la gestion de données
MongoDB : la base NoSQL qui réinvente la gestion de données
 
Finist JUG - Elasticsearch
Finist JUG - ElasticsearchFinist JUG - Elasticsearch
Finist JUG - Elasticsearch
 
Découverte de Elastic search
Découverte de Elastic searchDécouverte de Elastic search
Découverte de Elastic search
 
introduction à MongoDB
introduction à MongoDBintroduction à MongoDB
introduction à MongoDB
 
Poitou charentes JUG - Elasticsearch
Poitou charentes JUG - ElasticsearchPoitou charentes JUG - Elasticsearch
Poitou charentes JUG - Elasticsearch
 
L'avenir de LAMP
L'avenir de LAMPL'avenir de LAMP
L'avenir de LAMP
 
Tout ce que le getting started mongo db ne vous dira pas
Tout ce que le getting started mongo db ne vous dira pasTout ce que le getting started mongo db ne vous dira pas
Tout ce que le getting started mongo db ne vous dira pas
 

Andere mochten auch

PostgreSQL 9.4: NoSQL on ACID
PostgreSQL 9.4: NoSQL on ACIDPostgreSQL 9.4: NoSQL on ACID
PostgreSQL 9.4: NoSQL on ACIDOleg Bartunov
 
Node.js Module Resolution by visual example
Node.js Module Resolution by visual exampleNode.js Module Resolution by visual example
Node.js Module Resolution by visual exampleJeff Kunkle
 
µServices Architecture @ EPAM WOW 2015
µServices Architecture @ EPAM WOW 2015µServices Architecture @ EPAM WOW 2015
µServices Architecture @ EPAM WOW 2015Izzet Mustafaiev
 
Realtime Web avec Kafka, Spark et Mesos
Realtime Web avec Kafka, Spark et MesosRealtime Web avec Kafka, Spark et Mesos
Realtime Web avec Kafka, Spark et Mesosebiznext
 
Twitter + Lambda Architecture (Spark, Kafka, FLume, Cassandra) + Machine Lear...
Twitter + Lambda Architecture (Spark, Kafka, FLume, Cassandra) + Machine Lear...Twitter + Lambda Architecture (Spark, Kafka, FLume, Cassandra) + Machine Lear...
Twitter + Lambda Architecture (Spark, Kafka, FLume, Cassandra) + Machine Lear...Beatriz Martín @zigiella
 
DataStax Enterprise - La plateforme de base de données pour le Cloud
DataStax Enterprise - La plateforme de base de données pour le CloudDataStax Enterprise - La plateforme de base de données pour le Cloud
DataStax Enterprise - La plateforme de base de données pour le CloudVictor Coustenoble
 
Machine Learning - Spark / MLlib
Machine Learning - Spark / MLlibMachine Learning - Spark / MLlib
Machine Learning - Spark / MLlibebiznext
 
Datastax Cassandra + Spark Streaming
Datastax Cassandra + Spark StreamingDatastax Cassandra + Spark Streaming
Datastax Cassandra + Spark StreamingVictor Coustenoble
 
Les modèles NoSQL
Les modèles NoSQLLes modèles NoSQL
Les modèles NoSQLebiznext
 
Introduction aux bases de données NoSQL
Introduction aux bases de données NoSQLIntroduction aux bases de données NoSQL
Introduction aux bases de données NoSQLAntoine Augusti
 

Andere mochten auch (10)

PostgreSQL 9.4: NoSQL on ACID
PostgreSQL 9.4: NoSQL on ACIDPostgreSQL 9.4: NoSQL on ACID
PostgreSQL 9.4: NoSQL on ACID
 
Node.js Module Resolution by visual example
Node.js Module Resolution by visual exampleNode.js Module Resolution by visual example
Node.js Module Resolution by visual example
 
µServices Architecture @ EPAM WOW 2015
µServices Architecture @ EPAM WOW 2015µServices Architecture @ EPAM WOW 2015
µServices Architecture @ EPAM WOW 2015
 
Realtime Web avec Kafka, Spark et Mesos
Realtime Web avec Kafka, Spark et MesosRealtime Web avec Kafka, Spark et Mesos
Realtime Web avec Kafka, Spark et Mesos
 
Twitter + Lambda Architecture (Spark, Kafka, FLume, Cassandra) + Machine Lear...
Twitter + Lambda Architecture (Spark, Kafka, FLume, Cassandra) + Machine Lear...Twitter + Lambda Architecture (Spark, Kafka, FLume, Cassandra) + Machine Lear...
Twitter + Lambda Architecture (Spark, Kafka, FLume, Cassandra) + Machine Lear...
 
DataStax Enterprise - La plateforme de base de données pour le Cloud
DataStax Enterprise - La plateforme de base de données pour le CloudDataStax Enterprise - La plateforme de base de données pour le Cloud
DataStax Enterprise - La plateforme de base de données pour le Cloud
 
Machine Learning - Spark / MLlib
Machine Learning - Spark / MLlibMachine Learning - Spark / MLlib
Machine Learning - Spark / MLlib
 
Datastax Cassandra + Spark Streaming
Datastax Cassandra + Spark StreamingDatastax Cassandra + Spark Streaming
Datastax Cassandra + Spark Streaming
 
Les modèles NoSQL
Les modèles NoSQLLes modèles NoSQL
Les modèles NoSQL
 
Introduction aux bases de données NoSQL
Introduction aux bases de données NoSQLIntroduction aux bases de données NoSQL
Introduction aux bases de données NoSQL
 

Ähnlich wie Pg jsonb format 16-9

JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDB
JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDBJugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDB
JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDBSébastien Prunier
 
Construisez votre première application MongoDB
Construisez votre première application MongoDBConstruisez votre première application MongoDB
Construisez votre première application MongoDBMongoDB
 
Azure Camp 9 Décembre - slides session développeurs webmedia
Azure Camp 9 Décembre - slides session développeurs webmediaAzure Camp 9 Décembre - slides session développeurs webmedia
Azure Camp 9 Décembre - slides session développeurs webmediaMicrosoft
 
2014 03-12-fr schema design and app architecture-2
2014 03-12-fr schema design and app architecture-22014 03-12-fr schema design and app architecture-2
2014 03-12-fr schema design and app architecture-2MongoDB
 
MongoDB_presentation_xmls.pptx
MongoDB_presentation_xmls.pptxMongoDB_presentation_xmls.pptx
MongoDB_presentation_xmls.pptxZALIMAZA
 
MongoDB_presentation_p.pptx
MongoDB_presentation_p.pptxMongoDB_presentation_p.pptx
MongoDB_presentation_p.pptxZALIMAZA
 
MongoDB_presentation_tts.pptx
MongoDB_presentation_tts.pptxMongoDB_presentation_tts.pptx
MongoDB_presentation_tts.pptxZALIMAZA
 
Les Z'ApéroTech Toulouse #2 - Présentation des nouveautés de JakartaEE 8
Les Z'ApéroTech Toulouse #2 - Présentation des nouveautés de JakartaEE 8Les Z'ApéroTech Toulouse #2 - Présentation des nouveautés de JakartaEE 8
Les Z'ApéroTech Toulouse #2 - Présentation des nouveautés de JakartaEE 8DocDoku
 
ch5_indexation.pdf
ch5_indexation.pdfch5_indexation.pdf
ch5_indexation.pdfnihedattia2
 
OWF12/HTML 5 local storage , olivier thomas, cto at webtyss
OWF12/HTML 5 local storage , olivier thomas, cto at webtyssOWF12/HTML 5 local storage , olivier thomas, cto at webtyss
OWF12/HTML 5 local storage , olivier thomas, cto at webtyssParis Open Source Summit
 
MongoDB_presentation_example.pptx
MongoDB_presentation_example.pptxMongoDB_presentation_example.pptx
MongoDB_presentation_example.pptxZALIMAZA
 
PostgreSQL, plus qu'une base de données, une plateforme aux multiples usages
PostgreSQL, plus qu'une base de données, une plateforme aux multiples usagesPostgreSQL, plus qu'une base de données, une plateforme aux multiples usages
PostgreSQL, plus qu'une base de données, une plateforme aux multiples usagesOpen Source Experience
 
Initiation à Express js
Initiation à Express jsInitiation à Express js
Initiation à Express jsAbdoulaye Dieng
 
MongoDB_presentation_Moyou.pptx
MongoDB_presentation_Moyou.pptxMongoDB_presentation_Moyou.pptx
MongoDB_presentation_Moyou.pptxZALIMAZA
 
MongoDB_presentation_ye.pptx
MongoDB_presentation_ye.pptxMongoDB_presentation_ye.pptx
MongoDB_presentation_ye.pptxZALIMAZA
 
Enib cours c.a.i. web - séance #1 - html5 css3-js - 2
Enib   cours c.a.i. web - séance #1 - html5 css3-js - 2Enib   cours c.a.i. web - séance #1 - html5 css3-js - 2
Enib cours c.a.i. web - séance #1 - html5 css3-js - 2Horacio Gonzalez
 

Ähnlich wie Pg jsonb format 16-9 (20)

JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDB
JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDBJugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDB
JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDB
 
Construisez votre première application MongoDB
Construisez votre première application MongoDBConstruisez votre première application MongoDB
Construisez votre première application MongoDB
 
Hello mongo
Hello mongoHello mongo
Hello mongo
 
Azure Camp 9 Décembre - slides session développeurs webmedia
Azure Camp 9 Décembre - slides session développeurs webmediaAzure Camp 9 Décembre - slides session développeurs webmedia
Azure Camp 9 Décembre - slides session développeurs webmedia
 
Adopte une BDD
Adopte une BDDAdopte une BDD
Adopte une BDD
 
Présentation nouveauté java7
Présentation nouveauté java7Présentation nouveauté java7
Présentation nouveauté java7
 
2014 03-12-fr schema design and app architecture-2
2014 03-12-fr schema design and app architecture-22014 03-12-fr schema design and app architecture-2
2014 03-12-fr schema design and app architecture-2
 
MongoDB_presentation_xmls.pptx
MongoDB_presentation_xmls.pptxMongoDB_presentation_xmls.pptx
MongoDB_presentation_xmls.pptx
 
Mongo db et nosql
Mongo db et nosqlMongo db et nosql
Mongo db et nosql
 
MongoDB_presentation_p.pptx
MongoDB_presentation_p.pptxMongoDB_presentation_p.pptx
MongoDB_presentation_p.pptx
 
MongoDB_presentation_tts.pptx
MongoDB_presentation_tts.pptxMongoDB_presentation_tts.pptx
MongoDB_presentation_tts.pptx
 
Les Z'ApéroTech Toulouse #2 - Présentation des nouveautés de JakartaEE 8
Les Z'ApéroTech Toulouse #2 - Présentation des nouveautés de JakartaEE 8Les Z'ApéroTech Toulouse #2 - Présentation des nouveautés de JakartaEE 8
Les Z'ApéroTech Toulouse #2 - Présentation des nouveautés de JakartaEE 8
 
ch5_indexation.pdf
ch5_indexation.pdfch5_indexation.pdf
ch5_indexation.pdf
 
OWF12/HTML 5 local storage , olivier thomas, cto at webtyss
OWF12/HTML 5 local storage , olivier thomas, cto at webtyssOWF12/HTML 5 local storage , olivier thomas, cto at webtyss
OWF12/HTML 5 local storage , olivier thomas, cto at webtyss
 
MongoDB_presentation_example.pptx
MongoDB_presentation_example.pptxMongoDB_presentation_example.pptx
MongoDB_presentation_example.pptx
 
PostgreSQL, plus qu'une base de données, une plateforme aux multiples usages
PostgreSQL, plus qu'une base de données, une plateforme aux multiples usagesPostgreSQL, plus qu'une base de données, une plateforme aux multiples usages
PostgreSQL, plus qu'une base de données, une plateforme aux multiples usages
 
Initiation à Express js
Initiation à Express jsInitiation à Express js
Initiation à Express js
 
MongoDB_presentation_Moyou.pptx
MongoDB_presentation_Moyou.pptxMongoDB_presentation_Moyou.pptx
MongoDB_presentation_Moyou.pptx
 
MongoDB_presentation_ye.pptx
MongoDB_presentation_ye.pptxMongoDB_presentation_ye.pptx
MongoDB_presentation_ye.pptx
 
Enib cours c.a.i. web - séance #1 - html5 css3-js - 2
Enib   cours c.a.i. web - séance #1 - html5 css3-js - 2Enib   cours c.a.i. web - séance #1 - html5 css3-js - 2
Enib cours c.a.i. web - séance #1 - html5 css3-js - 2
 

Pg jsonb format 16-9

  • 1. BreizhCamp 2015 #BzhCmp #pgnosql Not only SQL avec PostgreSQL Pierre-Alban DEWITTE - @__pad__
  • 4. Histoire du type JSONB ● 2006 – HSTORE – Stockage clef/valeur ● 2012 – JSON - JavaScript Object Notation ● 2014 – JSONB – JSON Binaire Introduit par Oleg Bartunov, Teodor Sigaev, Peter Geoghegan and Andrew Dunstan dans Postgresql 9.4
  • 5. Caractéristiques du type JSONB • Permet de stocker un document JSON synthaxiquement valide • Stocker en interne sous une forme binaire permettant l’indexation En comparaison du format JSON • Léger surcout à l’insertion • Attention, contrairement à un chaine de charactère, l’ordre des objets n’est pas conservé • Les attributs avec le même nom ne sont pas conservés
  • 7. Possibilités offertes • Ajouter simplement de la flexibilité au schéma • Modéliser les données en fonction des use cases • Regroupement dans une même entités l’ensemble des informations constituant sont identité
  • 8. Application de démo ● Utilisation des données MovieLens http://grouplens.org/datasets/movielens/
  • 9. Modèle Conceptuel de Données Movie Integer id String year String title Integer imdbId Integer tmdbId Ratings Integer userId Integer movieId Float rating Date date 0.. n 1 Tags Integer userId Integer movieId String tag Date date 1 0.. n
  • 10. Modèle orienté document { "id" : 0, //Integer "year" : "...", //String "title" : "...", //String "imdbId" : "...", //Integer "tmdbId" : "...", //Integer "tags" : [{ //Array of tags "userId" : 0, //Integer "tag" : "...", //String "date" : "..." //String }], "ratings" : [{ //Array of ratings "userId" : 0, //Integer "rating" : "...", //String "date" : "..." //String }] }
  • 11. Modèle hybride – PGsql 9.4 Movie Integer id String year String title Integer imdbId Integer tmdbId Jsonb otherInformations { "tags" : [{ "userId" : 0, "tag" : "...", "date" : "..." }], "ratings" : [{ "userId" : 0, "rating" : "...", "date" : "..." }] }
  • 13. Colonne JSONB CREATE TABLE movies ( id integer primary key, name character varying(200), year character varying(4), imdbid integer, tmdbid integer, otherInformations jsonb ); ALTER TABLE books ADD COLUMN "otherInformations" jsonb;
  • 14. Insérer un enregistrement INSERT INTO movies (id, name, year, imdbid, tmdbid, otherInformations) VALUES (666666, 'Diabolic movie', 1966, 666, 6666, '{"ratings" : [ {"userId" : 4,"rating" : 3}, {"userId" : 5,"rating" : 5}, ] }' ); • Insertion des champs JSON dans un chaine de charactère. • Validation synthaxique effectuée par le moteur
  • 15. Insérer un enregistrement ● Nombreuses fonctions permettant de convertir un enregistrement en jsonb ● Et vis-versa
  • 16. Construire un champ JSON SELECT row_to_json(movies.*) FROM movies LIMIT 1 -- Résultats {"id":370,"name":"Naked Gun 33 1/3: The Final Insult ","year":"1994","imdbid":110622,"tmdbid":36593,"otherin formations":{"tags": [{"tag": "foqam", "date": 1139200469000, "userId": 14260}, {"tag": "Leslie Neilsen", "date": 1158438794000, "userId": 18390}, {"tag": "nazi", "date": 1161646656000, "userId": 18390}, {"tag": "sequel", "date": 1354555994000,
  • 17. Fonctions de construction JSON ● to_json : convertit une valeur ● row_to_json : convertit un tuple ● json_build_array : convertit un tableau ● json_build_object : construit un object JSON depuis un “varidic” ● json_object : construit à partir d’une chaine ● array_to_json : convertit un tableau
  • 19. Lecture brute d'un champ -- Lecture brute d’un champ JSON SELECT otherinformations FROM movies WHERE otherinformations IS NOT NULL LIMIT 2 -- Résultats {"tags": [{"tag": "foqam", "date": 1139200469000, "userId": 14260}, {"tag": "Leslie Neilsen", "date": 1158438794000, "userId": 18390}, {"tag": "nazi", "date": 1161646656000, "userId": 18390}, {"tag": "sequel", "date": 1354555994000, "userId": 42640}, {"tag": "Comedy", "date": 1248035546000, "userId": 60710}, {"tag": "parody", "date": 1248035543000,
  • 20. Ce n’est pas du texte -- Requête avec like SELECT otherinformations FROM movies WHERE otherinformations LIKE '%tags%' LIMIT 2 //Résultats Could not execute SQL statement. ERROR: operator does not exist: jsonb ~~ unknown Indice : No operator matches the given name and argument type(s). You might need to add explicit type casts.
  • 21. Ce n’est pas du texte -- Requête avec like et cast SELECT otherinformations FROM movies WHERE otherinformations::text LIKE '%tags%' LIMIT 2 -- Résultats {"tags": [{"tag": "foqam", "date": 1139200469000, "userId": 14260}, {"tag": "Leslie Neilsen", "date": 1158438794000, "userId": 18390}, {"tag": "nazi", "date": 1161646656000, "userId": 18390}, {"tag": "sequel", "date": 1354555994000, "userId": 42640}, {"tag": "Comedy", "date": 1248035546000, "userId": 60710}, {"tag": "parody", "date": 1248035543000,
  • 22. Modèle orienté document { "id" : 0, //Integer "year" : "...", //String "title" : "...", //String "imdbId" : "...", //Integer "tmdbId" : "...", //Integer "otherInformations" : { "averageRating" : "...", "nbOfRatings" : "...", "tags" : [{ //Array of tags "userId" : 0, //Integer "tag" : "...", //String "date" : "..." //String }], "ratings" : [{ //Array of ratings "userId" : 0, //Integer "rating" : "...", //String "date" : "..." //String }] }
  • 23. Lecture d’un champ --Lecture d'un champ SELECT otherinformations->'averageRating' FROM movies WHERE (otherinformations->>'averageRating')::float > 4 -- Résultats 4.00200100050025 4.081620314389359 4.089572192513369 4.216110019646365 4.126740947075209 4.078947368421052
  • 24. Lecture d’un tableau (texte) -- Lecture texte d'un élément de tableau SELECT otherinformations::jsonb->'tags'->>3 FROM movies LIMIT 2 -- Résultats {"tag": "sequel", "date": 1354555994000, "userId": 42640} {"tag": "Nudity (Full Frontal)", "date": 1298520169000, "userId": 33860}
  • 25. Lecture d’un tableau (JSON) -- Lecture JSON d'un élément de tableau SELECT otherinformations::jsonb->'tags'->3->'tag' FROM movies LIMIT 2 -- Résultats "sequel" "Nudity (Full Frontal)"
  • 26. Tester l’existence d’un champ -- Tester l’existence d’un champ SELECT count(*) FROM movies WHERE otherinformations ? 'nbOfRatings' -- Résultats 1715
  • 27. Recherche JSON -- Recherche JSON SELECT id, otherinformations->'nbOfRatings' FROM movies WHERE otherinformations @> '{"nbOfRatings" : 50}'::jsonb -- Résultats 1180 50 4000 50 8690 50
  • 28. Lecture avec chemin -- Lecture avec chemin en pseudo JSON -- Recherche du champ tag du cinquième élément du tableau tags -- Equivalent jsonb_extract_path et jsonb_extract_path_text SELECT otherinformations #> '{tags, 5, tag}' FROM movies LIMIT 2 -- Résultats "parody" "Monty Python"
  • 29. Fonctions de manipulation JSON ● jsonb_array_length : nb d’éléments d’un tableau JSONB ● jsonb_each & jsonb_each_text : transforme chaque clé valeur en une ligne ● jsonb_object_keys : liste des clefs d’un object json
  • 30. Fonctions de manipulation JSON ● jsonb_array_elements & jsonb_array_elements_text : transform un tableau JSON en tuple d’objets ● jsonb_typeof : indique le type parmi object, array, string, number, boolean et null.
  • 31. Fonctions de manipulation JSON ● jsonb_populate_record & jsonb_populate_recordset : construit implicitement un tuple ● json_to_record & json_to_recordset : construit explicitement un tuple
  • 32. Démo
  • 34. Et les indexes ? -- Création d'un index sur l'ensemble du document CREATE INDEX IDX_GIN_otherInformations ON movies USING GIN (otherInformations); Un index gin améliore les requêtes suivantes : • JSON @> JSON is a subset • JSON ? TEXT contains a value • JSON ?& TEXT[] contains all the values • JSON ?| TEXT[] contains at least one value
  • 35. Et les indexes ? -- Création d'un index sur l'ensemble du document CREATE INDEX IDX_GIN_otherInformations_opt ON movies USING GIN (otherInformations jsonb_path_ops); Paramètre jsonb_path_ops optimise uniquement les recherches avec @>
  • 36. Démo
  • 38. JDBC ● Un champ JSONB se manipule comme un DBObject ou comme du TEXT ● Pas de particularité dans le driver JDBC PostgreSQL ● Nécessité d’utiliser un mapper objet / JSON
  • 39. Démo
  • 40. DAO Insert //Using Jackson to convert additional field to JSON String ratingsAsString = new ObjectMapper().writeValueAsString(overallRating); … pstSetter = new PreparedStatementSetter() { public void setValues(PreparedStatement preparedStatement) throws SQLException { //Using a PGObject to store otherInformations PGobject dataObject = new PGobject(); dataObject.setType("jsonb"); dataObject.setValue(ratingsAsString); preparedStatement.setObject(1, dataObject); … } }; jdbcTemplateObject.update("UPDATE movies SET otherInformations = ? WHERE id = ?", pstSetter);
  • 41. DAO Select jdbcTemplateObject.query("SELECT id, otherinformations::text as text_otherinformations FROM movies WHERE otherinformations is not null limit 2", new RowCallbackHandler() { public void processRow(ResultSet resultSet) { while (resultSet.next()) { … movie.setId(resultSet.getLong("id")); … movie.setOther( mapper.readValue( resultSet.getString("text_otherinformations"), OtherInformations.class)); … }}});
  • 44. Et un update ? ● Postgresql 9.4 ne possède pas nativement d’opérateur permettant de manipuler un champ json ● Nécessité de lire / modifier / updater
  • 45. Manipulation avec plv8 CREATE OR REPLACE FUNCTION json_data_update(data json, field text, value text) RETURNS jsonb LANGUAGE plv8 STABLE STRICT AS $$ var data = data; var val = value; data[field] = val; return JSON.stringify(data); $$;
  • 46. Jsonbx ● Extension jsonbx en cours de portage dans PG 9.5 -- Update avec chemin en pseudo JSON UPDATE movies SET otherinformations = jsonb_replace(otherinformations, '{"tags",3,"tag"}', '{"SUPER"}'::jsonb) WHERE id = 1
  • 47. Nouveautés PGSql 9.5 -- Add values to a jsonb object: SELECT '{"name": "Joe", "age": 30}'::jsonb || '{"town": "London"}'::jsonb; -- Replace SELECT '{"town": "Dataville", "population": 4096}'::jsonb || '{"population": 8192}'::jsonb; -- Résultats {"age": 30, "name": "Joe", "town": "London"} {"town": "Dataville", "population": 8192}
  • 48. Nouveautés PGSql 9.5 -- Remove a key SELECT '{"name": "James", "email": "james@localhost"}'::jsonb - 'email'; -- Résultats {"name": "James"}
  • 50. PG vs MongoDB PG 9.4 répond aux besoins en lecture Puissance du SQL sous réserve de bien maitriser les fonctions de convertion PG ne permet pas simplement de mettre à jour un object JSON
  • 51. PG vs MongoDB ? Sharding plus facile Haute disponibilité
  • 54. Sources Requete : • http://www.postgresql.org/docs/9.4/static/functions-json.html • http://adpgtech.blogspot.fr/2015/05/new-jsonb-features-for-95.html Index • http://blog.2ndquadrant.com/jsonb-type-performance-postgresql-9-4/ JSONB et Postgresql • http://blog.2ndquadrant.com/postgresql-anti-patterns-unnecessary- jsonhstore-dynamic-columns/ • http://www.pgcon.org/2014/schedule/attachments/313_xml-hstore-json.pdf • https://www.compose.io/articles/is-postgresql-your-next-json-database/

Hinweis der Redaktion

  1. Source : http://www.enterprisedb.com/postgres-plus-edb-blog/marc-linster/postgres-outperforms-mongodb-and-ushers-new-developer-reality Un benchmark reste un benchmark et celui ci est tres douteux mais il donne envie de comprendre
  2. Source : https://speakerdeck.com/theory/xml-hstore-json-jsonb-oh-my http://www.postgresql.org/message-id/E1WRpmB-0002et-MT@gemulon.postgresql.org http://www.postgresql.org/docs/9.4/static/release.html http://rhaas.blogspot.fr/2014/04/why-clock-is-ticking-for-mongodb.html PostgreSQL's hstore, which provides the ability to store and index collections of key-value pairs in a fashion similar to what MongoDB provides, was first released in December of 2006, the year before MongoDB development began. True JSON capabilities were added to the PostgreSQL core as part of the 9.2 release, which went GA in September of 2012.  
  3. The new format accepts exactly the same data as the json type. However, it is stored in a format that does not require reparsing the orgiginal text in order to process it, making it much more suitable for indexing and other operations. Insignificant whitespace is discarded, and the order of object keys is not preserved. Neither are duplicate object keys kept - the later value for a given key is the only one stored. http://rfc7159.net/rfc7159 http://www.postgresql.org/docs/devel/static/datatype-json.html
  4. Chaque entité peux évoluer indépendament l’une de l’autre
  5. Manipulation d’un document avec l’ensemble des enregistrements
  6. MAJ du schéma
  7. Manipulation d’un document avec l’ensemble des enregistrements
  8. EXPLAIN (FORMAT JSON) http://stormatics.com/howto-use-jsonb-the-binary-formatted-jsons-in-postgresql/
  9. http://www.aquarianonline.com/wp-content/uploads/2014/01/ID-100197117.jpg
  10. http://www.aquarianonline.com/wp-content/uploads/2014/01/ID-100197117.jpg
  11. http://info.enterprisedb.com/rs/enterprisedb/images/EDB_White_Paper_Using_the_NoSQL_Features_in_Postgres.pdf