SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
Anders Karlsson
anders@skysql.com
Using JSON with MariaDB and
MySQL
Agenda
• About Anders Karlsson
• JSON, the new CSV – The basics!
• mysqljson - JSON import and export
with MariaDB and MySQL
• MariaDB JSON Support Extensions
• Dynamic columns
• MariaDB 10.0.1 new stuff
• Examples
• Questions and Answers
About Anders Karlsson
• Senior Sales Engineer at SkySQL
• Former Database Architect at Recorded Future, Sales
Engineer and Consultant with Oracle, Informix,
TimesTen, MySQL / Sun / Oracle etc.
• Has been in the RDBMS business for 20+ years
• Has also worked as Tech Support engineer, Porting
Engineer and in many other roles
• Outside SkySQL I build websites (www.papablues.com),
develop Open Source software (MyQuery,
mycleaner etc), am a keen photographer, has
an affection for English Real Ales and a great
interest in computer history
29/04/2013 SkySQL Ab 2011 Confidential 3
JSON, The new CSV – The basics
• JSON = Java Script Object Notation
– Not for Java Script only!
• JSON is easy to use, write and read
• JSON is reasonably well standardized
– Not to the extent that it is standardized to
become useless to mere mortals (Like XML)
– Rather, a simple, no frills, standard
– But more so than, say, CSV
• JSON is not tied to a specific platform,
database or application
JSON, The new CSV – The basics
• The JSON value types are simple
– Number
– String
– NULL
– TRUE / FALSE
– Object
– Array
• An object is a collection of elements, each
with a unique name and a value of one of the
basic types (including object)
• An array is a unordered list of values
JSON, The new CSV – The basics
• An example of a simple JSON value:
[
{"name": "Smith", "age": 57},
{"name": "Allen", "salary": 1600},
{"name": "King", "job": "Manager", "salary": "5000"}
]
• Another example:
{
"John": "The first name",
"Doe": "The last name"
}
JSON, The new CSV – The basics
• So what about this example:
{
"John": "The first name",
"Doe": "The last name",
"John": "Some other guys name"
}
• How many members does this
object have?
– 3?
– 2?
– 57?
JSON, The new CSV – The basics
• String specifics
– UNICODE / UTF8 only
– Backslash escapes, so binary data can be
represented
• Numbers are implementation defined,
regrettable, but mostly you get
– 32-bit signed integer
– 64-bit IEEE Double
JSON in a file
• JSON can appear in multiple ways in files, for
example (not exhaustive):
– As separate objects
{"col1": "value1", "col2": "value2"}
{"col1": "value1_2", "col3": "value3"}
– As an array of objects
[{"emp": [{"name": "Smith"},{"name": "Allen"}]},
{"dept": {"name": "dev"}}]
– As an array of simple, non-object, values
[{"col1": "value1", "col2": "value2"},
{"col1": "value1_2", "col3": "value3"}]
So, why is JSON useful?
• JSON works with more complex data than CSV
• JSON is better standardized than CSV
• JSON is great for interoperability
– If you want to use both relational data, with the
stricter schema and datatypes with a the more
flexible schema-less NoSQL options, than JSON is
great!
• JSON is used by JavaScript (of course),
MongoDB, Elasticsearch, CouchDB and many
others and can be used with many more!
• JSON is also a bit of fun!
Why JSON? Why not XML?
• JSON has numerous good support libraries
that are well-thought-out, stable and easy to
use
– I tend to use Jansson, a C-library for manipulating
JSON
– Most script languages has JSON parsers, so that, a
JSON object can easily be transformed into a Ruby
or Python object
• XML on the other hand is complex and
requires a rocket scientist to use and is also
hard to read.
mysqljson – Export and Import
• My project for JSON import and export for
MySQL and MariaDB
• Available on sourceforge
• Supports several file formats
– Object format import is still not released, although
the code is mostly done
• Table and column name mapping
• Column values can be generated
– Fixed
– Incremental
mysqljson – Export and Import
• Does not resolve, say, Foreign Key lookups
• Export allows simple table exports, as well as
ad-hoc SQL export
• Import is parallel
– Parallel on table by table
– Parallel on table level
JSON support in MariaDB
• MariaDB supports dynamic columns in version
5.3 and up
– Dynamic columns is a column type that allows
structured data to be stored in it
– Dynamic columns are stored in as BLOBs
– Dynamic columns consists of arbitrary key-value
pairs, similar to JSON objects. Key is unique within
an object
– Supported by a client-side API
JSON support in recent MariaDB
• MariaDB 10.0.1 adds a lot to dynamic columns
– Support for named keys (pre MariaDB 10.0.1 the
key was an integer)
– Support for JSON export of dynamic columns
• To be added are
– Support for JSON arrays
– Support for parsing JSON objects
– Support for more advanced JSON manipulation
MariaDB dynamic columns functions
• COLUMN_CREATE
– Create a dynamic column
– Dynamic columns may be nested
• COLUMN_GET
– Get the value of an item in a dynamic column
• COLUMN_ADD / COLUMN_DELETE
– Add / update / delete an item from a dynamic
column
• And more…
MariaDB 10.0.1 additions
• COLUMN_JSON
– Extract the value of a dynamic column as a correct
valid JSON object
• COLUMN_CHECK
– Check that the format of a BLOB is a correct
dynamic column
JSON with MariaDB 10.0.1
CREATE TABLE presidents(id INT NOT NULL
PRIMARY KEY AUTO_INCREMENT, info BLOB);
INSERT INTO presidents(id, info)
VALUES(NULL, COLUMN_CREATE('firstname',
'Richard', 'nickname', 'Tricky Dick',
'lastname', 'Nixon'));
INSERT INTO presidents(id, info)
VALUES(NULL, COLUMN_CREATE('firstname',
'George', 'lastname', 'Bush'));
JSON with MariaDB 10.0.1
mysql> SELECT id, COLUMN_JSON(info) FROM presidents;
+----+---------------------------------------------------------------------+
| id | COLUMN_JSON(info) |
+----+---------------------------------------------------------------------+
| 1 | {"lastname":"Nixon","nickname":"Tricky Dick","firstname":"Richard"} |
| 2 | {"lastname":"Bush","firstname":"George"} |
+----+---------------------------------------------------------------------+
mysql> UPDATE presidents SET info = COLUMN_ADD(info, 'nickname', 'W') WHERE
id = 2;
mysql> SELECT id, COLUMN_JSON(info) FROM presidents;
+----+---------------------------------------------------------------------+
| id | COLUMN_JSON(info) |
+----+---------------------------------------------------------------------+
| 1 | {"lastname":"Nixon","nickname":"Tricky Dick","firstname":"Richard"} |
| 2 | {"lastname":"Bush","nickname":"W","firstname":"George"} |
+----+---------------------------------------------------------------------+
Indexing JSON in MariaDB
• JSON items can be indexed in MariaDB, using
Virtual columns
• This is not optimal, but it is what is currently
available
CREATE TABLE presidents(id INT NOT NULL
PRIMARY KEY AUTO_INCREMENT, info BLOB,
lastname VARCHAR(64) AS (COLUMN_GET(info,
'lastname' AS CHAR(64))) PERSISTENT);
CREATE INDEX president_lastname ON
presidents(lastname);
Indexing JSON in MariaDB
mysql> SELECT rows_read FROM information_schema.index_statistics WHERE index_name =
'president_lastname';
+-----------+
| rows_read |
+-----------+
| 6 |
+-----------+
1 row in set (0.00 sec)
mysql> select COLUMN_JSON(info) from presidents where lastname = 'Bush';
+---------------------------------------------------------+
| COLUMN_JSON(info) |
+---------------------------------------------------------+
| {"lastname":"Bush","nickname":"W","firstname":"George"} |
+---------------------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT rows_read FROM information_schema.index_statistics WHERE index_name =
'president_lastname';
+-----------+
| rows_read |
+-----------+
| 7 |
+-----------+
1 row in set (0.00 sec)
Triggers on JSON in MariaDB
• Again: Use virtual columns
mysql> CREATE TRIGGER presidents_change AFTER UPDATE ON
presidents FOR EACH ROW INSERT INTO changelog VALUES(NOW(),
CONCAT('Name change from ', old.lastname, ' to ', new.lastname));
Query OK, 0 rows affected (0.10 sec)
mysql> UPDATE presidents SET info = column_add(info, 'lastname',
'Obama') WHERE lastname = 'Bush';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> SELECT * FROM changelog;
+---------------------+--------------------------------+
| logtime | logtext |
+---------------------+--------------------------------+
| 2013-04-18 22:06:07 | Name change from Bush to Obama |
+---------------------+--------------------------------+
1 row in set (0.00 sec)
The missing stuff
• JSON Parser for JSON input
• Support for all JSON datatypes
– NULL
– Numeric
– Boolean
• Support for JSON arrays
• Better indexing without resorting
to virtual columns
The missing stuff
• More JSON manipulation functions
• A proper JSON datatype
– Enforced UTF8
– JSON even in the SCHEMA
– Default JSON output format
• To SELECT a JSON column without having to resort to
COLUMN_JSON to get JSON out
Questions? Answers!
Anders Karlsson
anders@skysql.com
http://karlssonondatabases.blogspot.com
The question is not “What is the
answer?”, the question is “What is the
question?”.
Henri Poincaré
The question is not “What is the
answer?”, the question is “What is the
question?”.
Henri Poincaré

Contenu connexe

Tendances

Tendances (20)

Rich Internet Applications
Rich Internet ApplicationsRich Internet Applications
Rich Internet Applications
 
Introduction to SQL Antipatterns
Introduction to SQL AntipatternsIntroduction to SQL Antipatterns
Introduction to SQL Antipatterns
 
Php with mysql ppt
Php with mysql pptPhp with mysql ppt
Php with mysql ppt
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
MySQL Spider Architecture
MySQL Spider ArchitectureMySQL Spider Architecture
MySQL Spider Architecture
 
Chapter2 j2ee
Chapter2 j2eeChapter2 j2ee
Chapter2 j2ee
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Responsive web designing
Responsive web designingResponsive web designing
Responsive web designing
 
MySQL Cookbook: Recipes for Your Business
MySQL Cookbook: Recipes for Your BusinessMySQL Cookbook: Recipes for Your Business
MySQL Cookbook: Recipes for Your Business
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
 
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
 
Java Web Programming [1/9] : Introduction to Web Application
Java Web Programming [1/9] : Introduction to Web ApplicationJava Web Programming [1/9] : Introduction to Web Application
Java Web Programming [1/9] : Introduction to Web Application
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
[Pgday.Seoul 2017] 6. GIN vs GiST 인덱스 이야기 - 박진우
[Pgday.Seoul 2017] 6. GIN vs GiST 인덱스 이야기 - 박진우[Pgday.Seoul 2017] 6. GIN vs GiST 인덱스 이야기 - 박진우
[Pgday.Seoul 2017] 6. GIN vs GiST 인덱스 이야기 - 박진우
 
Express js
Express jsExpress js
Express js
 
Camel JBang - Quarkus Insights.pdf
Camel JBang - Quarkus Insights.pdfCamel JBang - Quarkus Insights.pdf
Camel JBang - Quarkus Insights.pdf
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 
Node.js in 2020 - part 3
Node.js in 2020 - part 3Node.js in 2020 - part 3
Node.js in 2020 - part 3
 
MySQL 5.7 NF – JSON Datatype 활용
MySQL 5.7 NF – JSON Datatype 활용MySQL 5.7 NF – JSON Datatype 활용
MySQL 5.7 NF – JSON Datatype 활용
 
Javascript
JavascriptJavascript
Javascript
 

En vedette

Redesigning Xen Memory Sharing (Grant) Mechanism
Redesigning Xen Memory Sharing (Grant) MechanismRedesigning Xen Memory Sharing (Grant) Mechanism
Redesigning Xen Memory Sharing (Grant) Mechanism
The Linux Foundation
 
JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
Stephan Schmidt
 
RESTful JSON web databases
RESTful JSON web databasesRESTful JSON web databases
RESTful JSON web databases
kriszyp
 
Uncle Ben's Recipe Video Contest Flyer
Uncle Ben's Recipe Video Contest FlyerUncle Ben's Recipe Video Contest Flyer
Uncle Ben's Recipe Video Contest Flyer
aeiser
 

En vedette (20)

MySQL JSON Functions
MySQL JSON FunctionsMySQL JSON Functions
MySQL JSON Functions
 
HTTP Plugin for MySQL!
HTTP Plugin for MySQL!HTTP Plugin for MySQL!
HTTP Plugin for MySQL!
 
MySQL 5.7 + JSON
MySQL 5.7 + JSONMySQL 5.7 + JSON
MySQL 5.7 + JSON
 
Kokemuksia Cassandra NoSQL:stä - Vincit Teatime 2014
Kokemuksia Cassandra NoSQL:stä - Vincit Teatime 2014Kokemuksia Cassandra NoSQL:stä - Vincit Teatime 2014
Kokemuksia Cassandra NoSQL:stä - Vincit Teatime 2014
 
Anatomi sendi panggul
Anatomi sendi panggulAnatomi sendi panggul
Anatomi sendi panggul
 
Pelvic dr.kas
Pelvic dr.kasPelvic dr.kas
Pelvic dr.kas
 
Redesigning Xen Memory Sharing (Grant) Mechanism
Redesigning Xen Memory Sharing (Grant) MechanismRedesigning Xen Memory Sharing (Grant) Mechanism
Redesigning Xen Memory Sharing (Grant) Mechanism
 
Extensible Data Modeling
Extensible Data ModelingExtensible Data Modeling
Extensible Data Modeling
 
Askep kehamilan dengan DM gestasional
Askep kehamilan dengan DM gestasional Askep kehamilan dengan DM gestasional
Askep kehamilan dengan DM gestasional
 
JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
 
RESTful JSON web databases
RESTful JSON web databasesRESTful JSON web databases
RESTful JSON web databases
 
The NoSQL Way in Postgres
The NoSQL Way in PostgresThe NoSQL Way in Postgres
The NoSQL Way in Postgres
 
Redis Labs and SQL Server
Redis Labs and SQL ServerRedis Labs and SQL Server
Redis Labs and SQL Server
 
Mars
MarsMars
Mars
 
Advanced Json
Advanced JsonAdvanced Json
Advanced Json
 
Uncle Ben's Recipe Video Contest Flyer
Uncle Ben's Recipe Video Contest FlyerUncle Ben's Recipe Video Contest Flyer
Uncle Ben's Recipe Video Contest Flyer
 
Seattle SeaHawks
Seattle SeaHawksSeattle SeaHawks
Seattle SeaHawks
 
Мероприятия как инструмент работы с молодыми специалистами и продвижения брен...
Мероприятия как инструмент работы с молодыми специалистами и продвижения брен...Мероприятия как инструмент работы с молодыми специалистами и продвижения брен...
Мероприятия как инструмент работы с молодыми специалистами и продвижения брен...
 
CouchDB Day NYC 2017: JSON Documents
CouchDB Day NYC 2017: JSON DocumentsCouchDB Day NYC 2017: JSON Documents
CouchDB Day NYC 2017: JSON Documents
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLHTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
 

Similaire à Using JSON with MariaDB and MySQL

Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Alex Sharp
 
PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...
PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...
PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...
pgdayrussia
 

Similaire à Using JSON with MariaDB and MySQL (20)

Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling StrategiesWebscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
 
5_MariaDB_What's New in MariaDB Server 10.2 and Big Data Analytics with Maria...
5_MariaDB_What's New in MariaDB Server 10.2 and Big Data Analytics with Maria...5_MariaDB_What's New in MariaDB Server 10.2 and Big Data Analytics with Maria...
5_MariaDB_What's New in MariaDB Server 10.2 and Big Data Analytics with Maria...
 
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)Postgres vs Mongo / Олег Бартунов (Postgres Professional)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
 
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to SphinxMYSQL Query Anti-Patterns That Can Be Moved to Sphinx
MYSQL Query Anti-Patterns That Can Be Moved to Sphinx
 
R data interfaces
R data interfacesR data interfaces
R data interfaces
 
Mongodb intro
Mongodb introMongodb intro
Mongodb intro
 
How to Use JSON in MySQL Wrong
How to Use JSON in MySQL WrongHow to Use JSON in MySQL Wrong
How to Use JSON in MySQL Wrong
 
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
Practical Ruby Projects with MongoDB - Ruby Kaigi 2010
 
Json in Postgres - the Roadmap
 Json in Postgres - the Roadmap Json in Postgres - the Roadmap
Json in Postgres - the Roadmap
 
Python redis talk
Python redis talkPython redis talk
Python redis talk
 
No sql way_in_pg
No sql way_in_pgNo sql way_in_pg
No sql way_in_pg
 
Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...
Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...
Типы данных JSONb, соответствующие индексы и модуль jsquery – Олег Бартунов, ...
 
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander KorotkovPostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
PostgreSQL Moscow Meetup - September 2014 - Oleg Bartunov and Alexander Korotkov
 
Alasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User ManualAlasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User Manual
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction2011 Mongo FR - MongoDB introduction
2011 Mongo FR - MongoDB introduction
 
PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...
PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...
PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
 
PostgreSQL 9.4 JSON Types and Operators
PostgreSQL 9.4 JSON Types and OperatorsPostgreSQL 9.4 JSON Types and Operators
PostgreSQL 9.4 JSON Types and Operators
 

Dernier

Dernier (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Using JSON with MariaDB and MySQL

  • 2. Agenda • About Anders Karlsson • JSON, the new CSV – The basics! • mysqljson - JSON import and export with MariaDB and MySQL • MariaDB JSON Support Extensions • Dynamic columns • MariaDB 10.0.1 new stuff • Examples • Questions and Answers
  • 3. About Anders Karlsson • Senior Sales Engineer at SkySQL • Former Database Architect at Recorded Future, Sales Engineer and Consultant with Oracle, Informix, TimesTen, MySQL / Sun / Oracle etc. • Has been in the RDBMS business for 20+ years • Has also worked as Tech Support engineer, Porting Engineer and in many other roles • Outside SkySQL I build websites (www.papablues.com), develop Open Source software (MyQuery, mycleaner etc), am a keen photographer, has an affection for English Real Ales and a great interest in computer history 29/04/2013 SkySQL Ab 2011 Confidential 3
  • 4. JSON, The new CSV – The basics • JSON = Java Script Object Notation – Not for Java Script only! • JSON is easy to use, write and read • JSON is reasonably well standardized – Not to the extent that it is standardized to become useless to mere mortals (Like XML) – Rather, a simple, no frills, standard – But more so than, say, CSV • JSON is not tied to a specific platform, database or application
  • 5. JSON, The new CSV – The basics • The JSON value types are simple – Number – String – NULL – TRUE / FALSE – Object – Array • An object is a collection of elements, each with a unique name and a value of one of the basic types (including object) • An array is a unordered list of values
  • 6. JSON, The new CSV – The basics • An example of a simple JSON value: [ {"name": "Smith", "age": 57}, {"name": "Allen", "salary": 1600}, {"name": "King", "job": "Manager", "salary": "5000"} ] • Another example: { "John": "The first name", "Doe": "The last name" }
  • 7. JSON, The new CSV – The basics • So what about this example: { "John": "The first name", "Doe": "The last name", "John": "Some other guys name" } • How many members does this object have? – 3? – 2? – 57?
  • 8. JSON, The new CSV – The basics • String specifics – UNICODE / UTF8 only – Backslash escapes, so binary data can be represented • Numbers are implementation defined, regrettable, but mostly you get – 32-bit signed integer – 64-bit IEEE Double
  • 9. JSON in a file • JSON can appear in multiple ways in files, for example (not exhaustive): – As separate objects {"col1": "value1", "col2": "value2"} {"col1": "value1_2", "col3": "value3"} – As an array of objects [{"emp": [{"name": "Smith"},{"name": "Allen"}]}, {"dept": {"name": "dev"}}] – As an array of simple, non-object, values [{"col1": "value1", "col2": "value2"}, {"col1": "value1_2", "col3": "value3"}]
  • 10. So, why is JSON useful? • JSON works with more complex data than CSV • JSON is better standardized than CSV • JSON is great for interoperability – If you want to use both relational data, with the stricter schema and datatypes with a the more flexible schema-less NoSQL options, than JSON is great! • JSON is used by JavaScript (of course), MongoDB, Elasticsearch, CouchDB and many others and can be used with many more! • JSON is also a bit of fun!
  • 11. Why JSON? Why not XML? • JSON has numerous good support libraries that are well-thought-out, stable and easy to use – I tend to use Jansson, a C-library for manipulating JSON – Most script languages has JSON parsers, so that, a JSON object can easily be transformed into a Ruby or Python object • XML on the other hand is complex and requires a rocket scientist to use and is also hard to read.
  • 12. mysqljson – Export and Import • My project for JSON import and export for MySQL and MariaDB • Available on sourceforge • Supports several file formats – Object format import is still not released, although the code is mostly done • Table and column name mapping • Column values can be generated – Fixed – Incremental
  • 13. mysqljson – Export and Import • Does not resolve, say, Foreign Key lookups • Export allows simple table exports, as well as ad-hoc SQL export • Import is parallel – Parallel on table by table – Parallel on table level
  • 14. JSON support in MariaDB • MariaDB supports dynamic columns in version 5.3 and up – Dynamic columns is a column type that allows structured data to be stored in it – Dynamic columns are stored in as BLOBs – Dynamic columns consists of arbitrary key-value pairs, similar to JSON objects. Key is unique within an object – Supported by a client-side API
  • 15. JSON support in recent MariaDB • MariaDB 10.0.1 adds a lot to dynamic columns – Support for named keys (pre MariaDB 10.0.1 the key was an integer) – Support for JSON export of dynamic columns • To be added are – Support for JSON arrays – Support for parsing JSON objects – Support for more advanced JSON manipulation
  • 16. MariaDB dynamic columns functions • COLUMN_CREATE – Create a dynamic column – Dynamic columns may be nested • COLUMN_GET – Get the value of an item in a dynamic column • COLUMN_ADD / COLUMN_DELETE – Add / update / delete an item from a dynamic column • And more…
  • 17. MariaDB 10.0.1 additions • COLUMN_JSON – Extract the value of a dynamic column as a correct valid JSON object • COLUMN_CHECK – Check that the format of a BLOB is a correct dynamic column
  • 18. JSON with MariaDB 10.0.1 CREATE TABLE presidents(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, info BLOB); INSERT INTO presidents(id, info) VALUES(NULL, COLUMN_CREATE('firstname', 'Richard', 'nickname', 'Tricky Dick', 'lastname', 'Nixon')); INSERT INTO presidents(id, info) VALUES(NULL, COLUMN_CREATE('firstname', 'George', 'lastname', 'Bush'));
  • 19. JSON with MariaDB 10.0.1 mysql> SELECT id, COLUMN_JSON(info) FROM presidents; +----+---------------------------------------------------------------------+ | id | COLUMN_JSON(info) | +----+---------------------------------------------------------------------+ | 1 | {"lastname":"Nixon","nickname":"Tricky Dick","firstname":"Richard"} | | 2 | {"lastname":"Bush","firstname":"George"} | +----+---------------------------------------------------------------------+ mysql> UPDATE presidents SET info = COLUMN_ADD(info, 'nickname', 'W') WHERE id = 2; mysql> SELECT id, COLUMN_JSON(info) FROM presidents; +----+---------------------------------------------------------------------+ | id | COLUMN_JSON(info) | +----+---------------------------------------------------------------------+ | 1 | {"lastname":"Nixon","nickname":"Tricky Dick","firstname":"Richard"} | | 2 | {"lastname":"Bush","nickname":"W","firstname":"George"} | +----+---------------------------------------------------------------------+
  • 20. Indexing JSON in MariaDB • JSON items can be indexed in MariaDB, using Virtual columns • This is not optimal, but it is what is currently available CREATE TABLE presidents(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, info BLOB, lastname VARCHAR(64) AS (COLUMN_GET(info, 'lastname' AS CHAR(64))) PERSISTENT); CREATE INDEX president_lastname ON presidents(lastname);
  • 21. Indexing JSON in MariaDB mysql> SELECT rows_read FROM information_schema.index_statistics WHERE index_name = 'president_lastname'; +-----------+ | rows_read | +-----------+ | 6 | +-----------+ 1 row in set (0.00 sec) mysql> select COLUMN_JSON(info) from presidents where lastname = 'Bush'; +---------------------------------------------------------+ | COLUMN_JSON(info) | +---------------------------------------------------------+ | {"lastname":"Bush","nickname":"W","firstname":"George"} | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT rows_read FROM information_schema.index_statistics WHERE index_name = 'president_lastname'; +-----------+ | rows_read | +-----------+ | 7 | +-----------+ 1 row in set (0.00 sec)
  • 22. Triggers on JSON in MariaDB • Again: Use virtual columns mysql> CREATE TRIGGER presidents_change AFTER UPDATE ON presidents FOR EACH ROW INSERT INTO changelog VALUES(NOW(), CONCAT('Name change from ', old.lastname, ' to ', new.lastname)); Query OK, 0 rows affected (0.10 sec) mysql> UPDATE presidents SET info = column_add(info, 'lastname', 'Obama') WHERE lastname = 'Bush'; Query OK, 1 row affected (0.05 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> SELECT * FROM changelog; +---------------------+--------------------------------+ | logtime | logtext | +---------------------+--------------------------------+ | 2013-04-18 22:06:07 | Name change from Bush to Obama | +---------------------+--------------------------------+ 1 row in set (0.00 sec)
  • 23. The missing stuff • JSON Parser for JSON input • Support for all JSON datatypes – NULL – Numeric – Boolean • Support for JSON arrays • Better indexing without resorting to virtual columns
  • 24. The missing stuff • More JSON manipulation functions • A proper JSON datatype – Enforced UTF8 – JSON even in the SCHEMA – Default JSON output format • To SELECT a JSON column without having to resort to COLUMN_JSON to get JSON out
  • 25. Questions? Answers! Anders Karlsson anders@skysql.com http://karlssonondatabases.blogspot.com The question is not “What is the answer?”, the question is “What is the question?”. Henri Poincaré The question is not “What is the answer?”, the question is “What is the question?”. Henri Poincaré