SlideShare a Scribd company logo
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Python and the
MySQL Document Store
Jesper Wisborg Krogh
Senior Principal Technical Support Engineer
Oracle MySQL Support
October 2018
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Safe Harbor Statement
The following is intended to outline our general product direction. It is intended for
information purposes only, and may not be incorporated into any contract. It is not a
commitment to deliver any material, code, or functionality, and should not be relied upon
in making purchasing decisions. The development, release, timing, and pricing of any
features or functionality described for Oracle’s products may change and remains at the
sole discretion of Oracle Corporation.
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Who Am I?
• Started to use MySQL in 2006
• Been a MySQL Support engineer since 2011
• Contributed to the Oracle Certified Professional exams for MySQL:
– MySQL 5.7 Database Administrator
– MySQL 5.6 Database Administrator
– MySQL 5.6 Developer
• Contributed to the MySQL sys schema
• Author of MySQL Connector/Python Revealed (Apress, 2018)
• Coauthor of Pro MySQL NDB Cluster (Apress, 2017)
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Program Agenda
MySQL and JSON Documents
What is the MySQL Document Store and the X DevAPI?
Let’s Have Fun and Look at Some Code
1
2
3
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
MySQL and JSON
How MySQL Works with JSON
5
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
JavaScript Object Notation (JSON)
{
"_id": "00005badb71c0000000000000001",
"FirstName": "Jane",
"Surname": "Doe",
"Address": {
"City": "Pacific City",
"PostCode": "1234",
"Street": "1 Pacific Ave"
},
"Birthday": "1970-10-22",
"Hobbies": [
"Hiking",
"Basketball"
]
}
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
MySQL has Native JSON Support
• JSON data type since MySQL 5.7
• Stored as binary object
• Support for partial updates in MySQL 8
• 27 JSON functions
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
JSON Paths
• $ – the root of the document
• . – path leg separator
• [N] – Nth value in array (0 based)
• * – wildcard:
– .* – all members in the object
– [*] – all values in the array
– [prefix]**suffix – path beginning with prefix and
ending in suffix.
$.geography.States[*]
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
MySQL JSON Functions in Action
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
The MySQL Document Store
And the X DevAPI
10
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
The MySQL Document Store
• Connector/Python: mysqlx
• X DevAPI
• X Protocol
• Server-side: X Plugin
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
The X DevAPI
• Developed from scratch for modern development
• Supports:
– SQL
– NoSQL – JSON documents
– NoSQL – SQL tables
• Uniform API across programming languages
• Supported in MySQL Shell
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
The X DevAPI
• Full ACID support
• Savepoints
• Connection pools (as of 8.0.13)
• Failover
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Let’s Code
Some Simple Examples Using MySQL Connector/Python or Shell with the MySQL
Document Store
14
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Create a Test User
mysql> CREATE USER pyuser@localhost IDENTIFIED BY 'my_password';
mysql> GRANT ALL ON world_x.* TO pyuser@localhost;
mysql> GRANT ALL ON py_test_db.* TO pyuser@localhost;
The examples in this presentation are simplified.
Please add the required checks in your programs,
particularly check for warnings and errors.
connect_args = {
"user": "pyuser",
"password": "my_password",
"host": "127.0.0.1",
"port": 33060,
}
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Create a Collection
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Create an Index
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
What Does a Collection with Index Look Like in SQL?
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
X DevAPI with Collections
Source: MySQL Connector/Python Revealed
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
General Workflow
import mysqlx
import config
session = mysqlx.get_session(**config.connect_args)
schema = session.get_schema("py_test_db")
people = schema.get_collection("people")
print("Session is open …..: {0}".format(people.schema.session.is_open()))
print("Schema name .......: {0}".format(people.schema.name))
print("Collection name ...: {0}".format(people.name))
# ... Use the collection ...
session.close()
Session is open …..: True
Schema name .......: py_test_db
Collection name ...: people
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Full Transactional Support
import mysqlx
import config
session = mysqlx.get_session(**config.connect_args)
schema = session.get_schema("py_test_db")
people = schema.get_collection("people")
session.start_transaction()
# ...
session.set_savepoint("my_savepoint")
# ...
session.release_savepoint("my_savepoint")
# ...
session.set_savepoint("my_savepoint_2")
# ...
session.rollback_to("my_savepoint_2")
# ...
session.commit()
session.close()
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Adding Documents
...
joe = {
"FirstName": "Joe",
"Surname": "Doe",
"Birthday": "1970-12-21",
}
jane = {
"FirstName": "Jane",
"Surname": "Doe",
"Birthday": "1972-03-12",
}
session.start_transaction()
result = people.add(joe).add(jane).execute()
if result.get_warnings_count() > 0:
session.rollback()
print(result.get_warnings())
else:
session.commit()
print("Documents added: {0}".format(result.get_affected_items_count()))
print("Doc Ids:")
for docid in result.get_generated_ids():
print(docid)
...
Documents added: 2
Doc Ids:
00005bbac3970000000000000007
00005bbac3970000000000000008
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Document IDs – the Primary Key of Documents
• Recall the table definition:
• Three parts – all hex encoded:
– Prefix
– Timestamp when the MySQL Server instance was started
– Auto-increment counter
• Globally unique IDs
• Optimized for underlying storage
• Examples: 00005bbac3970000000000000007
00005bbac3970000000000000008
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
The Workflow to Find Documents
dev.mysql.com/doc/x-devapi-userguide/en/crud-ebnf-collection-crud-functions.html
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Five Most Populous Countries in North America
import mysqlx
import config
session = mysqlx.get_session(**config.connect_args)
world = session.get_schema("world_x")
countryinfo = world.get_collection("CountryInfo")
stmt = countryinfo.find(
"geography.Continent = :continent AND demographics.Population > :min_pop")
stmt.fields("Name", "demographics AS Demographics")
stmt.sort("demographics.Population DESC", "Name").limit(3)
result = stmt.bind("continent", "North America") 
.bind("min_pop", 10*1000*1000).execute()
for doc in result.fetch_all():
print(doc)
session.close()
{"Name": "United States", "Demographics": {"Population": 278357000, "LifeExpectancy": 77.0999984741211}}
{"Name": "Mexico", "Demographics": {"Population": 98881000, "LifeExpectancy": 71.5}}
{"Name": "Canada", "Demographics": {"Population": 31147000, "LifeExpectancy": 79.4000015258789}}
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
The Workflow to Modify Documents
dev.mysql.com/doc/x-devapi-userguide/en/crud-ebnf-collection-crud-functions.html
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Update the Population of the United States
...
country_code = "USA"
find_stmt = countryinfo.find("_id = :country_code") 
.fields("demographics.Population AS Population")
before_result = find_stmt.bind("country_code", country_code).execute()
before_doc = before_result.fetch_one()
print("Before Population ...: {0}".format(before_doc["Population"]))
session.start_transaction()
stmt = countryinfo.modify("_id = :country_code") 
.set("demographics.Population", 326*1000*1000)
result = stmt.bind("country_code", country_code).execute()
session.commit()
after_result = find_stmt.bind("country_code", country_code).execute()
after_doc = after_result.fetch_one()
print("After Population ....: {0}".format(after_doc["Population"]))
...
Before Population ...: 278357000
After Population ....: 326000000
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Patch: Before Document for Australia
{
"GNP": 351182,
"IndepYear": 1901,
"Name": "Australia",
"_id": "AUS",
"demographics": {
"LifeExpectancy": 79.80000305175781,
"Population": 18886000
},
"geography": {
"Continent": "Oceania",
"Region": "Australia and New Zealand",
"SurfaceArea": 7741220
},
"government": {
"GovernmentForm": "Constitutional Monarchy, Federation",
"HeadOfState": "Elisabeth II"
}
}
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Patch the Country Info for Australia
...
# gnp = mysqlx.expr("$.GNP")
patch = {
"demographics": {
"LifeExpectancy": None,
"Population": 25*1000*1000,
},
"economy": {
"Currency": "Australian dollar",
"GNP": "($.GNP)",
},
"GNP": None,
}
session.start_transaction()
stmt = countryinfo.modify("_id = :country_code").patch(patch)
result = stmt.bind("country_code", "AUS").execute()
session.commit()
print("Docs updated: {0}".format(result.get_affected_items_count()))
...
Docs updated: 1
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
Patch: After Document for Australia
{
"IndepYear": 1901,
"Name": "Australia",
"_id": "AUS",
"demographics": {
"Population": 25000000
},
"economy": {
"Currency": "Australian dollar",
"GNP": 351182
},
"geography": {
"Continent": "Oceania",
"Region": "Australia and New Zealand",
"SurfaceArea": 7741220
},
"government": {
"GovernmentForm": "Constitutional Monarchy, Federation",
"HeadOfState": "Elisabeth II"
}
}
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
The Workflow to Removed Documents
dev.mysql.com/doc/x-devapi-userguide/en/crud-ebnf-collection-crud-functions.html
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. |
MySQL Shell – Great for Interactive Use
Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | 33
Python and the MySQL Document Store

More Related Content

What's hot

What's hot (20)

How to Integrate Spark MLlib and Apache Solr to Build Real-Time Entity Type R...
How to Integrate Spark MLlib and Apache Solr to Build Real-Time Entity Type R...How to Integrate Spark MLlib and Apache Solr to Build Real-Time Entity Type R...
How to Integrate Spark MLlib and Apache Solr to Build Real-Time Entity Type R...
 
Sasi, cassandra on full text search ride
Sasi, cassandra on full text search rideSasi, cassandra on full text search ride
Sasi, cassandra on full text search ride
 
Using PostgreSQL with Bibliographic Data
Using PostgreSQL with Bibliographic DataUsing PostgreSQL with Bibliographic Data
Using PostgreSQL with Bibliographic Data
 
MySQL JSON Document Store - A Document Store with all the benefits of a Trans...
MySQL JSON Document Store - A Document Store with all the benefits of a Trans...MySQL JSON Document Store - A Document Store with all the benefits of a Trans...
MySQL JSON Document Store - A Document Store with all the benefits of a Trans...
 
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...
 
Data stax academy
Data stax academyData stax academy
Data stax academy
 
Apache Kite
Apache KiteApache Kite
Apache Kite
 
Apache cassandra in 2016
Apache cassandra in 2016Apache cassandra in 2016
Apache cassandra in 2016
 
Spark Cassandra Connector: Past, Present, and Future
Spark Cassandra Connector: Past, Present, and FutureSpark Cassandra Connector: Past, Present, and Future
Spark Cassandra Connector: Past, Present, and Future
 
How to integrate Splunk with any data solution
How to integrate Splunk with any data solutionHow to integrate Splunk with any data solution
How to integrate Splunk with any data solution
 
Spark ETL Techniques - Creating An Optimal Fantasy Baseball Roster
Spark ETL Techniques - Creating An Optimal Fantasy Baseball RosterSpark ETL Techniques - Creating An Optimal Fantasy Baseball Roster
Spark ETL Techniques - Creating An Optimal Fantasy Baseball Roster
 
Datastax enterprise presentation
Datastax enterprise presentationDatastax enterprise presentation
Datastax enterprise presentation
 
Scaling Self Service Analytics with Databricks and Apache Spark with Amelia C...
Scaling Self Service Analytics with Databricks and Apache Spark with Amelia C...Scaling Self Service Analytics with Databricks and Apache Spark with Amelia C...
Scaling Self Service Analytics with Databricks and Apache Spark with Amelia C...
 
Introduction to PySpark
Introduction to PySparkIntroduction to PySpark
Introduction to PySpark
 
Treasure Data Mobile SDK
Treasure Data Mobile SDKTreasure Data Mobile SDK
Treasure Data Mobile SDK
 
Kite SDK introduction for Portland Big Data
Kite SDK introduction for Portland Big DataKite SDK introduction for Portland Big Data
Kite SDK introduction for Portland Big Data
 
DataSource V2 and Cassandra – A Whole New World
DataSource V2 and Cassandra – A Whole New WorldDataSource V2 and Cassandra – A Whole New World
DataSource V2 and Cassandra – A Whole New World
 
Spark zeppelin-cassandra at synchrotron
Spark zeppelin-cassandra at synchrotronSpark zeppelin-cassandra at synchrotron
Spark zeppelin-cassandra at synchrotron
 
Building data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyBuilding data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemy
 
Teaching Apache Spark: Demonstrations on the Databricks Cloud Platform
Teaching Apache Spark: Demonstrations on the Databricks Cloud PlatformTeaching Apache Spark: Demonstrations on the Databricks Cloud Platform
Teaching Apache Spark: Demonstrations on the Databricks Cloud Platform
 

Similar to Python and the MySQL Document Store

MySQL Day Paris 2018 - MySQL JSON Document Store
MySQL Day Paris 2018 - MySQL JSON Document StoreMySQL Day Paris 2018 - MySQL JSON Document Store
MySQL Day Paris 2018 - MySQL JSON Document Store
Olivier DASINI
 

Similar to Python and the MySQL Document Store (20)

MySQL Day Paris 2018 - What’s New in MySQL 8.0 ?
MySQL Day Paris 2018 - What’s New in MySQL 8.0 ?MySQL Day Paris 2018 - What’s New in MySQL 8.0 ?
MySQL Day Paris 2018 - What’s New in MySQL 8.0 ?
 
MySQL Document Store (Oracle Code Warsaw 2018)
MySQL Document Store (Oracle Code Warsaw 2018)MySQL Document Store (Oracle Code Warsaw 2018)
MySQL Document Store (Oracle Code Warsaw 2018)
 
20171104 hk-py con-mysql-documentstore_v1
20171104 hk-py con-mysql-documentstore_v120171104 hk-py con-mysql-documentstore_v1
20171104 hk-py con-mysql-documentstore_v1
 
MySQL Document Store - A Document Store with all the benefts of a Transactona...
MySQL Document Store - A Document Store with all the benefts of a Transactona...MySQL Document Store - A Document Store with all the benefts of a Transactona...
MySQL Document Store - A Document Store with all the benefts of a Transactona...
 
20190615 hkos-mysql-troubleshootingandperformancev2
20190615 hkos-mysql-troubleshootingandperformancev220190615 hkos-mysql-troubleshootingandperformancev2
20190615 hkos-mysql-troubleshootingandperformancev2
 
Node.js and the MySQL Document Store
Node.js and the MySQL Document StoreNode.js and the MySQL Document Store
Node.js and the MySQL Document Store
 
MySQL 8.0 - What's New ?
MySQL 8.0 - What's New ?MySQL 8.0 - What's New ?
MySQL 8.0 - What's New ?
 
MySQL Day Paris 2018 - MySQL JSON Document Store
MySQL Day Paris 2018 - MySQL JSON Document StoreMySQL Day Paris 2018 - MySQL JSON Document Store
MySQL Day Paris 2018 - MySQL JSON Document Store
 
MySQL Shell: the daily tool for devs and admins. By Vittorio Cioe.
MySQL Shell: the daily tool for devs and admins. By Vittorio Cioe.MySQL Shell: the daily tool for devs and admins. By Vittorio Cioe.
MySQL Shell: the daily tool for devs and admins. By Vittorio Cioe.
 
MySQL Connector/Node.js and the X DevAPI
MySQL Connector/Node.js and the X DevAPIMySQL Connector/Node.js and the X DevAPI
MySQL Connector/Node.js and the X DevAPI
 
20190713_MySQL開発最新動向
20190713_MySQL開発最新動向20190713_MySQL開発最新動向
20190713_MySQL開発最新動向
 
MySQL NoSQL JSON JS Python "Document Store" demo
MySQL NoSQL JSON JS Python "Document Store" demoMySQL NoSQL JSON JS Python "Document Store" demo
MySQL NoSQL JSON JS Python "Document Store" demo
 
Connector/J Beyond JDBC: the X DevAPI for Java and MySQL as a Document Store
Connector/J Beyond JDBC: the X DevAPI for Java and MySQL as a Document StoreConnector/J Beyond JDBC: the X DevAPI for Java and MySQL as a Document Store
Connector/J Beyond JDBC: the X DevAPI for Java and MySQL as a Document Store
 
Mysql8for blr usercamp
Mysql8for blr usercampMysql8for blr usercamp
Mysql8for blr usercamp
 
MySQL 8 loves JavaScript
MySQL 8 loves JavaScript MySQL 8 loves JavaScript
MySQL 8 loves JavaScript
 
MySQL Document Store
MySQL Document StoreMySQL Document Store
MySQL Document Store
 
MySQL Document Store and Node.JS
MySQL Document Store and Node.JSMySQL Document Store and Node.JS
MySQL Document Store and Node.JS
 
MySQL 8.0 in a nutshell
MySQL 8.0 in a nutshellMySQL 8.0 in a nutshell
MySQL 8.0 in a nutshell
 
State ofdolphin short
State ofdolphin shortState ofdolphin short
State ofdolphin short
 
20180921_DOAG_BigDataDays_OracleSpatialandPython_kpatenge
20180921_DOAG_BigDataDays_OracleSpatialandPython_kpatenge20180921_DOAG_BigDataDays_OracleSpatialandPython_kpatenge
20180921_DOAG_BigDataDays_OracleSpatialandPython_kpatenge
 

Recently uploaded

Recently uploaded (20)

Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 

Python and the MySQL Document Store

  • 1. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Python and the MySQL Document Store Jesper Wisborg Krogh Senior Principal Technical Support Engineer Oracle MySQL Support October 2018
  • 2. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Safe Harbor Statement The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, timing, and pricing of any features or functionality described for Oracle’s products may change and remains at the sole discretion of Oracle Corporation.
  • 3. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Who Am I? • Started to use MySQL in 2006 • Been a MySQL Support engineer since 2011 • Contributed to the Oracle Certified Professional exams for MySQL: – MySQL 5.7 Database Administrator – MySQL 5.6 Database Administrator – MySQL 5.6 Developer • Contributed to the MySQL sys schema • Author of MySQL Connector/Python Revealed (Apress, 2018) • Coauthor of Pro MySQL NDB Cluster (Apress, 2017)
  • 4. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Program Agenda MySQL and JSON Documents What is the MySQL Document Store and the X DevAPI? Let’s Have Fun and Look at Some Code 1 2 3
  • 5. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | MySQL and JSON How MySQL Works with JSON 5
  • 6. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | JavaScript Object Notation (JSON) { "_id": "00005badb71c0000000000000001", "FirstName": "Jane", "Surname": "Doe", "Address": { "City": "Pacific City", "PostCode": "1234", "Street": "1 Pacific Ave" }, "Birthday": "1970-10-22", "Hobbies": [ "Hiking", "Basketball" ] }
  • 7. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | MySQL has Native JSON Support • JSON data type since MySQL 5.7 • Stored as binary object • Support for partial updates in MySQL 8 • 27 JSON functions
  • 8. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | JSON Paths • $ – the root of the document • . – path leg separator • [N] – Nth value in array (0 based) • * – wildcard: – .* – all members in the object – [*] – all values in the array – [prefix]**suffix – path beginning with prefix and ending in suffix. $.geography.States[*]
  • 9. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | MySQL JSON Functions in Action
  • 10. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | The MySQL Document Store And the X DevAPI 10
  • 11. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | The MySQL Document Store • Connector/Python: mysqlx • X DevAPI • X Protocol • Server-side: X Plugin
  • 12. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | The X DevAPI • Developed from scratch for modern development • Supports: – SQL – NoSQL – JSON documents – NoSQL – SQL tables • Uniform API across programming languages • Supported in MySQL Shell
  • 13. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | The X DevAPI • Full ACID support • Savepoints • Connection pools (as of 8.0.13) • Failover
  • 14. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Let’s Code Some Simple Examples Using MySQL Connector/Python or Shell with the MySQL Document Store 14
  • 15. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Create a Test User mysql> CREATE USER pyuser@localhost IDENTIFIED BY 'my_password'; mysql> GRANT ALL ON world_x.* TO pyuser@localhost; mysql> GRANT ALL ON py_test_db.* TO pyuser@localhost; The examples in this presentation are simplified. Please add the required checks in your programs, particularly check for warnings and errors. connect_args = { "user": "pyuser", "password": "my_password", "host": "127.0.0.1", "port": 33060, }
  • 16. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Create a Collection
  • 17. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Create an Index
  • 18. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | What Does a Collection with Index Look Like in SQL?
  • 19. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | X DevAPI with Collections Source: MySQL Connector/Python Revealed
  • 20. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | General Workflow import mysqlx import config session = mysqlx.get_session(**config.connect_args) schema = session.get_schema("py_test_db") people = schema.get_collection("people") print("Session is open …..: {0}".format(people.schema.session.is_open())) print("Schema name .......: {0}".format(people.schema.name)) print("Collection name ...: {0}".format(people.name)) # ... Use the collection ... session.close() Session is open …..: True Schema name .......: py_test_db Collection name ...: people
  • 21. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Full Transactional Support import mysqlx import config session = mysqlx.get_session(**config.connect_args) schema = session.get_schema("py_test_db") people = schema.get_collection("people") session.start_transaction() # ... session.set_savepoint("my_savepoint") # ... session.release_savepoint("my_savepoint") # ... session.set_savepoint("my_savepoint_2") # ... session.rollback_to("my_savepoint_2") # ... session.commit() session.close()
  • 22. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Adding Documents ... joe = { "FirstName": "Joe", "Surname": "Doe", "Birthday": "1970-12-21", } jane = { "FirstName": "Jane", "Surname": "Doe", "Birthday": "1972-03-12", } session.start_transaction() result = people.add(joe).add(jane).execute() if result.get_warnings_count() > 0: session.rollback() print(result.get_warnings()) else: session.commit() print("Documents added: {0}".format(result.get_affected_items_count())) print("Doc Ids:") for docid in result.get_generated_ids(): print(docid) ... Documents added: 2 Doc Ids: 00005bbac3970000000000000007 00005bbac3970000000000000008
  • 23. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Document IDs – the Primary Key of Documents • Recall the table definition: • Three parts – all hex encoded: – Prefix – Timestamp when the MySQL Server instance was started – Auto-increment counter • Globally unique IDs • Optimized for underlying storage • Examples: 00005bbac3970000000000000007 00005bbac3970000000000000008
  • 24. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | The Workflow to Find Documents dev.mysql.com/doc/x-devapi-userguide/en/crud-ebnf-collection-crud-functions.html
  • 25. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Five Most Populous Countries in North America import mysqlx import config session = mysqlx.get_session(**config.connect_args) world = session.get_schema("world_x") countryinfo = world.get_collection("CountryInfo") stmt = countryinfo.find( "geography.Continent = :continent AND demographics.Population > :min_pop") stmt.fields("Name", "demographics AS Demographics") stmt.sort("demographics.Population DESC", "Name").limit(3) result = stmt.bind("continent", "North America") .bind("min_pop", 10*1000*1000).execute() for doc in result.fetch_all(): print(doc) session.close() {"Name": "United States", "Demographics": {"Population": 278357000, "LifeExpectancy": 77.0999984741211}} {"Name": "Mexico", "Demographics": {"Population": 98881000, "LifeExpectancy": 71.5}} {"Name": "Canada", "Demographics": {"Population": 31147000, "LifeExpectancy": 79.4000015258789}}
  • 26. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | The Workflow to Modify Documents dev.mysql.com/doc/x-devapi-userguide/en/crud-ebnf-collection-crud-functions.html
  • 27. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Update the Population of the United States ... country_code = "USA" find_stmt = countryinfo.find("_id = :country_code") .fields("demographics.Population AS Population") before_result = find_stmt.bind("country_code", country_code).execute() before_doc = before_result.fetch_one() print("Before Population ...: {0}".format(before_doc["Population"])) session.start_transaction() stmt = countryinfo.modify("_id = :country_code") .set("demographics.Population", 326*1000*1000) result = stmt.bind("country_code", country_code).execute() session.commit() after_result = find_stmt.bind("country_code", country_code).execute() after_doc = after_result.fetch_one() print("After Population ....: {0}".format(after_doc["Population"])) ... Before Population ...: 278357000 After Population ....: 326000000
  • 28. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Patch: Before Document for Australia { "GNP": 351182, "IndepYear": 1901, "Name": "Australia", "_id": "AUS", "demographics": { "LifeExpectancy": 79.80000305175781, "Population": 18886000 }, "geography": { "Continent": "Oceania", "Region": "Australia and New Zealand", "SurfaceArea": 7741220 }, "government": { "GovernmentForm": "Constitutional Monarchy, Federation", "HeadOfState": "Elisabeth II" } }
  • 29. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Patch the Country Info for Australia ... # gnp = mysqlx.expr("$.GNP") patch = { "demographics": { "LifeExpectancy": None, "Population": 25*1000*1000, }, "economy": { "Currency": "Australian dollar", "GNP": "($.GNP)", }, "GNP": None, } session.start_transaction() stmt = countryinfo.modify("_id = :country_code").patch(patch) result = stmt.bind("country_code", "AUS").execute() session.commit() print("Docs updated: {0}".format(result.get_affected_items_count())) ... Docs updated: 1
  • 30. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | Patch: After Document for Australia { "IndepYear": 1901, "Name": "Australia", "_id": "AUS", "demographics": { "Population": 25000000 }, "economy": { "Currency": "Australian dollar", "GNP": 351182 }, "geography": { "Continent": "Oceania", "Region": "Australia and New Zealand", "SurfaceArea": 7741220 }, "government": { "GovernmentForm": "Constitutional Monarchy, Federation", "HeadOfState": "Elisabeth II" } }
  • 31. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | The Workflow to Removed Documents dev.mysql.com/doc/x-devapi-userguide/en/crud-ebnf-collection-crud-functions.html
  • 32. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | MySQL Shell – Great for Interactive Use
  • 33. Copyright © 2018, Oracle and/or its affiliates. All rights reserved. | 33