More Related Content Similar to NoSQL атакует: JSON функции в MySQL сервере. (20) More from Sveta Smirnova (20) NoSQL атакует: JSON функции в MySQL сервере.1. Copyright © 2013, Oracle and/or its affiliates. All rights reserved.1
Insert Picture Here
NoSQL атакует:
JSON функции
в MySQL сервере.
Света Смирнова
Ведущий инженер
https://twitter.com/#!/svetsmirnova
2. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.2
Содержание
Введение: NoSQL в мире MySQL
MySQL JSON функции
Где их взять
Взгляд в будущее
3. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.3
Insert Chart Here
Основные этапы
развития NoSQL
1997 1998 2000 2003 2004 2008 2009 2010 2012 2013
0
0.5
1
1.5
2
2.5
3
3.5
4
Databases
История NoSQL
NoSQL
database
NoSQL
term
db40 memcached
BigTable
MemcacheDB
Tarantool
CouchDB
MongoDB
Redis
WebSphere
Virtuoso
DynamoDB
JSON в
PostgreSQL
Hbase
4. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.4
Insert Chart Here
Появление NoSQL
возможностей в MySQL
2009
2010
2011
2012
2013
0
1
2
3
4
5
6
NoSQL в мире MySQL
Баги memcached
на mysql.com
HandlerSocket
InnoDB с memcached
Memcache API для
MySQL Cluster
NoSQL Connector
для JavaScript
EXPLAIN в JSON
Hadoop Applier
mysqlv8udfs
JSON UDFs
5. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.5
Insert Chart HereНакануне
2012
2013
2014
0
0.05
0.1
0.15
0.2
0.25
0.3
JSON функции в MySQL
Версия 0.1
Не была опубликована
Версия 0.2
Версия 0.3
6. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.6
JSON функции
Функции
Манипуляции текстами в формате JSON
●
Валидация
●
Поиск
●
Модификация
UDF
●
Легко инсталлировать
●
Независимы от версии MySQL сервера
Работают на всех платформах, которые поддерживает MySQL
Бинарные дистрибутивы для Linux, Mac OSX 7 и Windows
Что они делают?
7. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.9
Insert Picture Here
Что делают функции?
8. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.10
json_valid(doc)
Проверяет является ли doc допустимым документом в формате
JSON.
Возвращает 1 если проверка прошла, 0 в противном случае.
Формат как описан на http://json.org,
http://www.ietf.org/rfc/rfc4627.txt?number=4627
9. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.11
json_valid(doc)
mysql> select json_valid('{"Devconf": ["conference",
2014]}');
++
| json_valid('{"Devconf": ["conference", 2014]}') |
++
| 1 |
++
1 row in set (0.01 sec)
10. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.12
json_valid(doc)
mysql> select json_valid('{"Devconf"}');
++
| json_valid('{"Devconf"}') |
++
| 0 |
++
1 row in set (0.00 sec)
11. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.13
json_contains_key(doc, keypart1, keypart2, ...)
Проверяет есть ли в документе указанный ключ
Возвращает 1 если элемент существует, 0 если нет и NULL если
документ не в формате JSON.
12. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.14
json_contains_key(doc, keypart1, keypart2, ...)
SET optimizer_trace=1;
mysql> select user from mysql.user;
++
...
mysql> select json_contains_key(trace, 'steps', '0',
'join_optimization', 'steps', '0', 'condition_processing') as contains
from information_schema.optimizer_trace;
++
| contains |
++
| 0 |
++
1 row in set (0.01 sec)
13. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.15
json_contains_key(doc, keypart1, keypart2, ...)
mysql> select user from mysql.user where user='Sveta';
++
...
mysql> select json_contains_key(trace, 'steps', '0',
'join_optimization', 'steps', '0', 'condition_processing') as
contains from information_schema.optimizer_trace;
++
| contains |
++
| 1 |
++
1 row in set (0.01 sec)
14. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.16
json_extract(doc, keypart1, keypart2, ...)
Возвращает элемент по ключу или NULL если ключ не найден или
же документ не в формате JSON.
15. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.17
json_extract(doc, keypart1, keypart2, ...)
SET optimizer_trace=1;
mysql> select user from mysql.user;
++
...
mysql> select json_extract(trace, 'steps', '0', 'join_optimization',
'steps', '0', 'condition_processing') as value from
information_schema.optimizer_trace;
++
| value |
++
| NULL |
++
1 row in set (0.01 sec)
16. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.18
Как выполняется поиск
{“steps”:
[
{“join_optimization”:
{“steps”:
[
{“condition_processing”: .....
json_extract(trace, 'steps', '0', 'join_optimization',
'steps', '0', 'condition_processing')
17. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.19
json_extract(doc, keypart1, keypart2, ...)
mysql> select user from mysql.user where user='Sveta';
++
...
mysql> select json_extract(trace, 'steps', '0', 'join_optimization',
'steps', '0', 'condition_processing') as value from
information_schema.optimizer_traceG
*************************** 1. row ***************************
value: {
"condition": "WHERE",
"original_condition": "(`mysql`.`user`.`User` =
'sveta')",
"steps": [
....
18. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.20
json_append(doc, keypart1, keypart2, ...,
new_element)
Добавляет элемент в документ JSON.
Возвращает документ с добавленным элементом, оригинальный
документ, если некуда вставить элемент или NULL если документ,
либо подставляемое значение не в формате JSON.
19. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.21
json_append(doc, keypart1, keypart2, ...,
new_element)
mysql> select json_append('{"Devconf": ["conference", 2014]}',
'Devconf', 2, '" "') as 'Devconf';Москва
++
| Devconf |
++
| {"Devconf": ["conference", 2014, " "]} |Москва
++
1 row in set (0.00 sec)
20. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.22
json_append(doc, keypart1, keypart2, ...,
new_element)
mysql> select json_append('{"Devconf":
["conference", 2014]}', 'Devconf', 1, '" "') as Москва
'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference", 2014]} |
++
1 row in set (0.00 sec)
21. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.23
json_replace(doc, keypart1, keypart2, ...,
new_value)
Обновляет значение по ключу.
Возвращает изменённый или оригинальный документ если ключ не
был найден, NULL если документ либо подставляемое значение не
в формате JSON.
22. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.24
json_replace(doc, keypart1, keypart2, ...,
new_value)
mysql> select json_replace('{"Devconf":
["conference", 2014]}', 'Devconf', '0', '"User
conference"') as 'Devconf';
++
| Devconf |
++
| {"Devconf": ["User conference", 2014]} |
++
1 row in set (0.00 sec)
23. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.25
json_replace(doc, keypart1, keypart2, ...,
new_value)
mysql> select json_replace('{"Devconf":
["conference", 2014]}', 'Devconf', '2', '"User
conference"') as 'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference", 2014]} |
++
1 row in set (0.00 sec)
24. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.26
json_set(doc, keypart1, keypart2, ..., new_value)
Выполняет операцию наподобие INSERT ... ON DUPLICATE KEY
UPDATE.
Возвращает документ с добавленным или изменённым элементом,
NULL если документ либо подставляемое значение не в формате
JSON.
25. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.27
json_set(doc, keypart1, keypart2, ..., new_value)
mysql> select json_set('{"Devconf": ["conference",
2014]}', 'Devconf', '0', '"User conference"') as
'Devconf';
++
| Devconf |
++
| {"Devconf": ["User conference", 2014]} |
++
1 row in set (0.00 sec)
26. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.28
json_set(doc, keypart1, keypart2, ..., new_value)
mysql> select json_set('{"Devconf": ["conference",
2014]}', 'Devconf', '2', '" "') as 'Devconf';Москва
++
| Devconf |
++
| {"Devconf": ["conference", 2014, " "]} |Москва
++
1 row in set (0.00 sec)
27. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.29
json_remove(doc, keypart1, keypart2, ...)
Удаляет элемент.
Возвращает документ без элемента, оригинальный документ, если
ключ не найден или NULL если документ не в формате JSON.
28. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.30
json_remove(doc, keypart1, keypart2, ...)
mysql> select json_remove('{"Devconf":
["conference", 2014]}', 'Devconf', '1') as
'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference"]} |
++
1 row in set (0.00 sec)
29. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.31
json_remove(doc, keypart1, keypart2, ...)
mysql> select json_remove('{"Devconf":
["conference", 2014]}', 'Devconf', '2') as
'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference", 2014]} |
++
1 row in set (0.00 sec)
30. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.32
json_search(doc, value)
Осуществляет поиск по значению.
Возвращает путь к найденному элементу в обратном порядке,
NULL если элемент не найден или документ не в формате JSON.
31. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.33
json_search(doc, value)
mysql> select json_search(trace, '"trivial_condition_removal"') from
information_schema.optimizer_trace;
+
| json_search(trace, '"trivial_condition_removal"') |
++
|transformation:0:steps:condition_processing:0:steps:join_optimization:0:steps:: |
++
1 row in set (0.00 sec)
32. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.34
json_search(doc, value)
mysql> select json_search(trace, '"trivial_condition"')
from information_schema.optimizer_trace;
++
| json_search(trace, '"trivial_condition"') |
++
| NULL |
++
1 row in set (0.01 sec)
33. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.35
json_search(doc, value)
mysql> select json_search('{"Devconf": ["conference", 2014]}',
'"conf%"');
++
| json_search('{"Devconf": ["conference", 2014]}', '"conf%"') |
++
| 0:Devconf:: |
++
1 row in set (0.00 sec)
Feature preview!
0.3.2+
34. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.36
json_merge(doc1, doc2, ...)
Объединяет два или более документов в один.
Возвращает первый документ с присоединёнными последующими.
Дубликаты ключей никак не обрабатываются.
Внимание! Эта функция не проверяет документы на соответствие
формату JSON.
Тем не менее открывающие и закрывающие скобки у всех
документов должны совпадать.
Возвращает NULL если у первого документа нет открывающих-
закрывающих скобок или же они не совпадают.
35. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.37
json_safe_merge(doc1, doc2, ...)
Объединяет два или более документов в один.
Возвращает первый документ с присоединёнными последующими.
Дубликаты ключей никак не обрабатываются.
Внимание! Эта функция проверяет все документы на соответствие
формату JSON.
Возвращает NULL если первый документ не в формате JSON.
36. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.38
json_deep_merge(doc1, doc2, ...)
Объединяет два или более документов в один.
Возвращает первый документ с присоединёнными последующими.
Значения дублирующих ключей обновляются.
Внимание! Эта функция проверяет все документы на соответствие
формату JSON.
Возвращает NULL если у первый документ не в формате JSON.
Feature preview!
0.3.2+
37. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.39
json_merge(doc1, doc2, ...)
mysql> select json_merge('{"Devconf": ["conference", 2013]}',
'{"Devconf": ["conference", 2014]}') as 'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference", 2013], "Devconf": ["conference", 2014]} |
++
1 row in set (0.00 sec)
38. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.40
json_safe_merge(doc1, doc2, ...)
mysql> select json_safe_merge('{"Devconf": ["conference", 2013]}',
'{"Devconf": ["conference", 2014]}') as 'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference", 2013], "Devconf": ["conference", 2014]} |
++
1 row in set (0.00 sec)
39. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.41
json_deep_merge(doc1, doc2, ...)
mysql> select json_deep_merge('{"Devconf": ["conference",
2013]}', '{"Devconf": ["conference", 2014]}') as
'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference", 2013, "conference", 2014]} |
++
1 row in set (0.00 sec)
Feature preview!
0.3.2+
40. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.42
json_merge(doc1, doc2, ...)
mysql> select json_merge('{"Devconf": ["conference", 2013]}',
'{"Devconf": ["conference", 2014]}', '1') as 'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference", 2013], "Devconf": ["conference", 2014]} |
++
1 row in set (0.00 sec)
41. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.43
json_merge(doc1, doc2, ...)
mysql> select json_merge('{"Devconf": ["conference", 2013]}',
'{"Devconf": ["conference" 2014]}') as 'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference", 2013], "Devconf": ["conference" 2014]} |
++
1 row in set (0.00 sec)
42. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.44
json_safe_merge(doc1, doc2, ...)
mysql> select json_safe_merge('{"Devconf":
["conference", 2013]}',
> '{"Devconf": ["conference" 2014]}') as 'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference", 2013]} |
++
1 row in set (0.00 sec)
43. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.45
json_deep_merge(doc1, doc2, ...)
mysql> select json_deep_merge('{"Devconf":
["conference", 2013]}',
>'{"Devconf": ["conference" 2014]}') as 'Devconf';
++
| Devconf |
++
| {"Devconf": ["conference", 2013]} |
++
1 row in set (0.00 sec)
Feature preview!
0.3.2+
44. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.46
json_depth(doc)
Возвращает количество уровней вложения в документе или NULL
если документ не в формате JSON
45. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.47
json_depth(doc)
mysql> select json_depth('{"Devconf": ["conference",
2014]}');
++
| json_depth('{"Devconf": ["conference", 2014]}') |
++
| 3 |
++
1 row in set (0.00 sec)
46. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.48
json_count(doc[, keypart1[, keypart2[, ...]]])
Возвращает количество детей родительского элемента, указанного
при помощи пути, корневого элемента если путь опущен или NULL
если документ не в формате JSON
47. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.49
json_count(doc, keypart1, keypart2, ...)
mysql> select json_count('{"Devconf": ["conference",
2014]}');
++
| json_count('{"Devconf": ["conference", 2014]}') |
++
| 1 |
++
1 row in set (0.00 sec)
48. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.50
json_count(doc, keypart1, keypart2, ...)
mysql> select json_count('{"Devconf": ["conference", 2014]}',
'Devconf');
++
| json_count('{"Devconf": ["conference", 2014]}', 'Devconf') |
++
| 2 |
++
1 row in set (0.00 sec)
49. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.51
json_version()
Возвращает версию функций.
50. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.52
json_version()
mysql> select json_version();
++
| json_version() |
++
| MySQL JSON UDFs 0.3.2labs |
++
1 row in set (0.00 sec)
51. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.53
json_test_parser(doc)
Возвращает текстовое представление parse tree документа JSON,
частичное дерево или пустую строку если документ не в формате
JSON.
Эта функция предназначена исключительно для тестирования и не
должна использоваться в рабочем приложении.
52. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.54
json_test_parser(doc)
mysql> select json_test_parser('{"Devconf":
["conference", 2014]}') as 'Parse tree'G
********************** 1. row **********************
Parse tree: => "conference";
=> 2014;
"Devconf" => ["conference", 2014];
=> {"Devconf": ["conference", 2014]};
53. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.55
json_test_parser(doc)
mysql> select json_test_parser('{"Devconf": ["conference",
2014]') as 'Parse tree';
++
| Parse tree |
++
| => "conference"; => 2014;"Devconf" => ["conference", 2014]; |
++
1 row in set (0.00 sec)
54. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.56
Insert Picture Here
Где взять?
55. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.57
Исходный код и бинарные дистрибутивы
MySQL Labs
●
Исходный код
●
Бинарные дистрибутивы
●
x86 and x86_64
●
Generic Linux
●
Mac OSX 10.7
●
Windows 7
●
http://labs.mysql.com/
56. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.58
Как инсталлировать?
UNIX
create function json_valid returns integer
soname 'libmy_json_udf.so';
create function json_search returns string
soname 'libmy_json_udf.so';
create function json_extract returns string
soname 'libmy_json_udf.so';
create function json_replace returns string
soname 'libmy_json_udf.so';
create function json_append returns string
soname 'libmy_json_udf.so';
...
57. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.59
Как инсталлировать?
Windows
create function json_remove returns string
soname 'my_json_udf.dll';
create function json_set returns string
soname 'my_json_udf.dll';
create function json_merge returns string
soname 'my_json_udf.dll';
create function json_contains_key returns integer
soname 'my_json_udf.dll';
create function json_test_parser returns string
soname 'my_json_udf.dll';
...
58. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.60
Как инсталлировать или удалить?
Готовые скрипты
mysql db_name < install_jsonudf.sql
mysql db_name < uninstall_jsonudf.sql
Спасибо Daniel van Eeden!
59. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.61
Зависимости
Библиотека Regex
Распространяется вместе с дистрибутивом функций
UNIX
●
Можно использовать системную
Windows
●
Всегда компилируется статически
Вам не нужно устанавливать никаких библиотек, чтобы
использовать функции!
60. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.62
Как компилировать?
UNIX
Вам нужно:
●
cmake
●
Regex library (поставляется вместе с исходниками)
●
Компилятор
Как скомпилировать:
●
cmake . DMYSQL_DIR=/home/sveta/build/mysql5.6
●
make
61. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.63
Как компилировать?
Windows
Вам нужно:
●
PCRE (поставляется вместе с исходным кодом)
●
Visual Studio
●
cmake (cmake.org)
Чтобы собрать JSON UDF:
●
"C:Program Files (x86)CMake 2.8bincmake.exe" G
"Visual Studio 11 Win64" . DMYSQL_DIR="C:/MySQL/mysql
5.6.19"
●
devenv my_json_udf.sln /build Release
62. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.64
Больше информации
Документация и статьи
●
Файл README
●
Мой блог: https://blogs.oracle.com/svetasmirnova/
Анонсы
●
Мой twitter: https://twitter.com/#!/svetsmirnova
63. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.65
Insert Picture Here
Будущее
64. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.66
Зависит от вас
Открывайте баги
Шлите предложения по улучшению
Больше вы пришлёте – больше мы сделаем
Сейчас вы можете влиять на решения
65. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.67
Куда посылать баги и feature request-ы
MySQL Community bugs database
●
https://bugs.mysql.com/
●
Категория
●
“MySQL Server: JSON User-defined function (UDF)”
Internal Oracle bugs database
●
Просите инженеров технической поддержки MySQL открыть баг репорт
для вас
●
Категория “UDFJSON”
66. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.68
Полезные ссылки
https://blogs.oracle.com/svetasmirnova/
https://twitter.com/#!/svetsmirnova
http://json.org/
http://www.pcre.org/
http://dev.mysql.com/doc/refman/5.6/en/adding-functions.html
http://bugs.mysql.com/
https://support.oracle.com
67. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.69
Insert Picture Here
?
68. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.70
Insert Picture Here
СПАСИБО!
69. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.71
The preceding 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, and
timing of any features or functionality described for
Oracle’s products remains at the sole discretion of Oracle.