mysql 5.7 como document store

71
MySQL como Document Store suporte a JSON Airton Lastori [email protected] Julho-2016

Upload: mysql-brasil

Post on 15-Feb-2017

441 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: MySQL 5.7 como Document Store

MySQL como Document Store suporte a JSON

Airton Lastori [email protected] Julho-2016

Page 2: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

DBA Dev Gerencial

Quem?

Page 3: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Nunca usou NoSQL

Usa NoSQL apenas em apps não-

críticas

NoSQL em apps críticas

Quem?

Page 4: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Agenda

1. MySQL e seu legado

2. SQL vs NoSQL – quando usar

3. Funcionalidades NoSQL no MySQL

Page 5: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Agenda

1. MySQL e seu legado

2. SQL vs NoSQL – quando usar

3. Funcionalidades NoSQL no MySQL

Page 6: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Grandes usuários MySQL

6

Web, Cloud, Distribuído e Embarcado…

Page 7: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 7

Muitas foram start ups há poucos anos, começaram e cresceram com

MySQL

Page 8: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | 8

http://db-engines.com/en/ranking_trend (mar-2016)

Page 9: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

A Web

Oracle Confidential – Internal/Restricted/Highly Restricted 9

Dados massivos, problemas Big Data

Altíssima escala

Sempre online

Estratégia: hardwares commodity em nuvem + software livre

Modelo relacional: difícil escalar e implementar alta disponibilidade em nuvem de hw commodity

www.leavcom.com/pdf/NoSQL.pdf

Page 10: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 10

NoSQL = Não-relacional

Page 11: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | 11

http://db-engines.com/en/ranking_categories

183 NoSQL

12 categorias

Page 12: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 12

Web = gatilho para o surgimento das tecnologias NoSQL

Page 15: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 15

Se o software tem mais tempo de desenvolvimento e é largamente

utilizado, menor a probabilidade de falhar em funções básicas.

Page 16: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

“We had an unexpected loss of data on nearly every technology we used at one time or another, except MySQL.”

– Pinterest Engineering

Oracle Confidential – Internal/Restricted/Highly Restricted 16

Page 17: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Evolução da escalabilidade vertical do MySQL

Read-only Read-write

Page 18: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Oracle elevando o nível Um MySQL cada vez melhor

2x Engineering Staff

3x QA Staff

2x Support Staff

Page 19: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

MySQL Enterprise Edition Suporte + Base de Conhecimento + Hot Backup + Monitor + Oracle EM + Workbench + Plug-ins

Escalabilidade Autenticação

Firewall Auditoria novo TDE

Criptografia

MySQL Enterprise Monitor Oracle EM for MySQL

Plug-ins

Suporte

Hot Backup

Monitor & Workbench

Page 20: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Agenda

1. MySQL e seu legado

2. SQL vs NoSQL – quando usar

3. Funcionalidades NoSQL no MySQL

Page 21: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Vários modelos de dados

• 1960 - navigacional

– Hierárquico

– Network

• 1970 - SQL/relacional

• 1990 - Orientado a Objetos – em parte, absorvido pelos SGBDRs

• 2000 – NoSQL

– o modelo relacional não resolve bem todos os problemas

– apenas um Hype? será absorvido pelos SGBDRs?

Oracle Confidential – Internal/Restricted/Highly Restricted 21

Page 22: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 22

SQL = implementação do modelo relacional

NoSQL = tudo que não é relacional

Page 23: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

SQL

• Integridade dos dados

– Schema, Normalização, Constraints (ex. FKs)

• ACID, transações

• SQL

– Linguagem otimizável de consulta

– Diga o que quer, deixe o resto com o BD

– Agilidade nas consultas de dados estruturados, principalmente médio e longo prazo

NoSQL

• Schemaless

– agilidade no desenvolvimento inicial

– estruturas de dados flexíveis

• JSON, arrays aninhadas

• Alguns usos realmente bons

– hierarquias , campos customizados, etc

– persistir objetos sem ORMs

– proximidade com frontend (Javascript)

• Fácil de aprender e usar

Oracle Confidential – Internal/Restricted/Highly Restricted 23

Page 24: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Schemaless

• key-value

• document

• wide column

• graph

• Etc

• Muda o modelo lógico, a visão do usuário

– Outras APIs de acesso = Not Only SQL

– Em muitos casos, simplifica a vida do desenvolvedor (do DBA, nem tanto...)

Oracle Confidential – Internal/Restricted/Highly Restricted 24

Page 25: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 25

Relacional vs Documento

Page 26: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

É possível combinar os dois mundos?

• Ter ambos schema e schemaless no mesmo stack?

• Uma solução que marque todos checkboxes:

26

Developers [ x ] Schemaless [ x ] Rapid Prototyping/Simpler APIs [ x ] Document Model

Operations [ x ] Performance Management/Visibility [ x ] Robust Replication, Backup, Restore [ x ] Comprehensive Tooling Ecosystem

Business Owner [ x ] Don’t lose my data = ACID transactions [ x ] Capture all my data = Extensible/Schemaless [ x ] Products On Schedule/Time to Market = Rapid Development

Page 27: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Um database flexível

– Mão-de-obra com conhecimentos profundos

– Estável

– Custos efecientes e controlados

– Fácil mover dados entre instâncias

– Menos Drivers

– Menos Ferramentas

– SQL funciona, CRUD funciona

– Operacional e Analítico juntos

Muitos databases diferentes

– Requer repertório maior de habilidades, dificulta encontrar mão de obra com conhecimentos profundos

– Muitos Drivers

– Muitas Ferramentas

– Mais esforço para integrar, compartilhar e mover dados

– Muito mais trabalho

– Separação muitas vezes desnecessária de Operacional e Analítico

Por que combinar em um único database?

27

Page 28: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Agenda

1. MySQL e seu legado

2. SQL vs NoSQL – quando usar

3. Funcionalidades NoSQL no MySQL

Page 30: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | 30

MySQL com memcached

+1 000 000 QPS

*X86 48 cores

http://dimitrik.free.fr/blog/archives/2013/11/mysql-performance-over-1m-qps-with-innodb-memcached-plugin-in-mysql-57.html

Page 31: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Whats New? MySQL 5.7.12+

• New Server Features – Native JSON datatype and storage

– Generated Columns with Indexing

– Over 20+ Native JSON functions

– New X Protocol

• New Document APIs – SQL and NoSQL/Document CRUD APIs will cross all Connectors

• For BOTH Collections of Documents and Relational Tables

– Initial DMR M1 includes Node.js, Java and .NET

• New Interactive Shell – with Javascript, Python, SQL modes

31

Page 32: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Whats New? MySQL 5.7.12+

• New Server Features – Native JSON datatype and storage

– Generated Columns with Indexing

– Over 20+ Native JSON functions

– New X Protocol

• New Document APIs – SQL and NoSQL/Document CRUD APIs will cross all Connectors

• For BOTH Collections of Documents and Relational Tables

– Initial DMR M1 includes Node.js, Java and .NET

• New Interactive Shell – with Javascript, Python, SQL modes

32

Page 33: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 33

Exemplo CRUD MySQL 5.7.12

Page 34: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

CREATE mysql> CREATE DATABASE json_test; mysql> USE json_test;

mysql> CREATE TABLE product_info (product JSON);

mysql> INSERT INTO product_info VALUES (' { "product_id" : 9, "size" : "M", "color" : "red", "fabric" : "cotton" } ');

Query OK, 1 row affected (0.01 sec)

34

Page 35: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

CREATE mysql> INSERT INTO product_info VALUES (' { "product_id" : 14, "size" : "S", "price" : 15.0 } ');

Query OK, 1 row affected (0.01 sec)

35

Page 36: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

READ mysql> SELECT * FROM product_info;

+--------------------------------------------------------------------+

| product |

+--------------------------------------------------------------------+

| {"size": "M", "color": "red", "fabric": "cotton", "product_id": 9} |

| {"size": "S", "price": 15, "product_id": 14} |

+--------------------------------------------------------------------+

2 rows in set (0.00 sec)

36

Page 37: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

READ mysql> SELECT * FROM product_info WHERE product->"$.product_id"=14;

+----------------------------------------------+

| product |

+----------------------------------------------+

| {"size": "S", "price": 15, "product_id": 14} |

+----------------------------------------------+

1 row in set (0.00 sec)

37

Page 38: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

UPDATE mysql> UPDATE product_info SET product = '{"size": "L", "price": 15,

"product_id": 14}' WHERE product->"$.product_id"=14;

Query OK, 1 row affected (0.01 sec)

Rows matched: 1 Changed: 1 Warnings: 0

mysql> SELECT * FROM product_info WHERE product->"$.product_id"=14;

+--------------------------------------------------------------------+

| product |

+--------------------------------------------------------------------+

| {"size": "M", "color": "red", "fabric": "cotton", "product_id": 9} |

| {"size": "L", "price": 15, "product_id": 14} |

+--------------------------------------------------------------------+

2 rows in set (0.00 sec)

38

Page 39: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

DELETE mysql> DELETE FROM product_info WHERE product->"$.product_id"=14;

Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM product_info;

+--------------------------------------------------------------------+

| product |

+--------------------------------------------------------------------+

| {"size": "M", "color": "red", "fabric": "cotton", "product_id": 9} |

+--------------------------------------------------------------------+

1 row in set (0.00 sec)

39

Page 40: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Vantagens sobre tipos TEXT/VARCHAR

1. Validação

2. Eficiência no armazenamento físico Formato binário otimizado que permite um acesso mais rápido aos elementos de matrizes

41

INSERT INTO product_info VALUES ('texto que não é JSON válido');

ERROR 3140 (22032): Invalid JSON text: "Invalid value." at

position 1 in value for column 'product_info.product'.

Page 41: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Testes com dados reais

• San Francisco OpenData

• 206K objetos JSON

• Importado de https://github.com/zemirco/sf-city-lots-json + ajustes

42

CREATE TABLE features (

id INT NOT NULL auto_increment primary key,

feature JSON NOT NULL

);

Page 42: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | 43

{

"type":"Feature",

"geometry":{

"type":"Polygon",

"coordinates":[

[

[-122.42200352825247,37.80848009696725,0],

[-122.42207601332528,37.808835019815085,0],

[-122.42110217434865,37.808803534992904,0],

[-122.42106256906727,37.80860105681814,0],

[-122.42200352825247,37.80848009696725,0]

]

]

},

"properties":{

"TO_ST":"0",

"BLKLOT":"0001001",

"STREET":"UNKNOWN",

"FROM_ST":"0",

"LOT_NUM":"001",

"ST_TYPE":null,

"ODD_EVEN":"E",

"BLOCK_NUM":"0001",

"MAPBLKLOT":"0001001"

}

}

Page 43: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Comparação de Performance: JSON vs TEXT

44

# tipo JSON

SELECT DISTINCT

feature->"$.type" as json_extract

FROM features;

+--------------+

| json_extract |

+--------------+

| "Feature" |

+--------------+

1 row in set (1.25 sec)

# tipo TEXT

SELECT DISTINCT

feature->"$.type" as json_extract

FROM features;

+--------------+

| json_extract |

+--------------+

| "Feature" |

+--------------+

1 row in set (12.85 sec)

JSON 10x mais rápido que TEXT numa busca full scan (sem índice, 206K documentos)

Page 44: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Generated Columns

45

id my_integer my_integer_plus_one

1 10 11

2 20 21

3 30 31

4 40 41

UPDATE t1 SET my_integer_plus_one = 10 WHERE id = 1;

ERROR 3105 (HY000): The value specified for generated column

'my_integer_plus_one' in table 't1' is not allowed.

Coluna atualizada automaticamente com base na definição CREATE.

Somente leitura, é claro!

CREATE TABLE t1 (

id INT NOT NULL PRIMARY KEY auto_increment,

my_integer INT,

my_integer_plus_one INT AS (my_integer + 1)

);

Page 45: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Indexando via Generated Columns

46

ALTER TABLE features ADD feature_type VARCHAR(30) AS (feature->"$.type");

Query OK, 0 rows affected (0.01 sec)

Records: 0 Duplicates: 0 Warnings: 0

ALTER TABLE features ADD INDEX (feature_type);

Query OK, 0 rows affected (0.73 sec)

Records: 0 Duplicates: 0 Warnings: 0

SELECT DISTINCT feature_type FROM features;

+--------------+

| feature_type |

+--------------+

| "Feature" |

+--------------+

1 row in set (0.06 sec)

Down from 1.25 sec to 0.06 sec

Creates index only. Does not modify table rows.

Meta data change only (FAST). Does not need to touch table.

Page 46: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Virtual vs. Stored Generated Columns Performance

• Approximate worst case scenario via a table scan:

47

SELECT DISTINCT feature_type FROM

features;

+--------------+

| feature_type |

+--------------+

| "Feature" |

+--------------+

VIRTUAL-TEXT (9.89 sec)

STORED-TEXT (0.22 sec)

VIRTUAL-JSON (0.85 sec)

STORED-JSON (0.24 sec)

Clarification: Since indexes are materialized (stored) themselves, the real-life case for STORED is when generating the column is computationally expensive and you can not use indexes effectively.

Page 47: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Indexing Options Available

48

STORED VIRTUAL

Primary and Secondary

BTREE, Fulltext, GIS

Mixed with fields

Requires table rebuild

Not Online

Secondary Only

BTREE Only

Mixed with fields

No table rebuild

INSTANT Alter

Faster Insert

Bottom Line: Unless you need a PRIMARY KEY, FULLTEXT or GIS index VIRTUAL is probably better.

Page 48: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Compression Performance (16K Page)

49

May compress well - Schemaless means that the keys are repeated in each of the documents; repetition improves compression performance MySQL 5.7 also supports 32KB and 64KB pages (improved compression)

SELECT name, ((file_size-allocated_size)*100)/file_size as compressed_pct

from information_schema.INNODB_SYS_TABLESPACES WHERE name like

'test/features';

+---------------+----------------+

| name | compressed_pct |

+---------------+----------------+

| test/features | 59.2634 |

+---------------+----------------+

1 row in set (0.01 sec)

Using real-life data set from earlier (16K Page)

Page 49: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | 50

Funções JSON: além do CRUD

JSON_ARRAY_APPEND()

JSON_ARRAY_INSERT()

JSON_ARRAY()

JSON_CONTAINS_PATH()

JSON_CONTAINS()

JSON_DEPTH()

JSON_EXTRACT()

JSON_INSERT()

JSON_KEYS()

JSON_LENGTH()

JSON_MERGE()

JSON_OBJECT()

JSON_QUOTE()

JSON_REMOVE()

JSON_REPLACE()

JSON_SEARCH()

JSON_SET()

JSON_TYPE()

JSON_UNQUOTE()

JSON_VALID()

https://dev.mysql.com/doc/refman/5.7/en/json-functions.html

Page 50: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

JSON_EXTRACT()

51

mysql> SELECT DISTINCT JSON_EXTRACT(feature, '$.type') FROM features;

+---------------------------------+

| JSON_EXTRACT(feature, '$.type') |

+---------------------------------+

| "Feature" |

+---------------------------------+

1 row in set (1.22 sec)

Page 51: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Unquote JSON String

mysql> SELECT DISTINCT JSON_UNQUOTE(feature->"$.type") AS feature_type

FROM features;

+-----------------+

| feature_type |

+-----------------+

| Feature |

+-----------------+

1 row in set (1.22 sec)

52

Page 52: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

JSON Array Creation

53

SELECT JSON_ARRAY(id,

feature->"$.properties.STREET",

feature->'$.type") AS json_array

FROM features ORDER BY RAND() LIMIT 3;

+-------------------------------+

| json_array |

+-------------------------------+

| [65298, "10TH", "Feature"] |

| [122985, "08TH", "Feature"] |

| [172884, "CURTIS", "Feature"] |

+-------------------------------+

3 rows in set (2.66 sec)

Page 53: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

JSON_REPLACE

54

SELECT JSON_REPLACE(feature, '$.type', JSON_ARRAY('feature', 'bug')) as

json_object FROM features LIMIT 1;

+--------------------------------------------------------+

| json_object |

+--------------------------------------------------------+

| {"type": ["feature", "bug"], "geometry": {"type": ..}} |

+--------------------------------------------------------+

Page 54: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

JSON Object Creation

55

SELECT JSON_OBJECT('id', id,

'street', feature->"$.properties.STREET",

'type', feature->"$.type"

) AS json_object

FROM features ORDER BY RAND() LIMIT 3;

+--------------------------------------------------------+

| json_object |

+--------------------------------------------------------+

| {"id": 122976, "type": "Feature", "street": "RAUSCH"} |

| {"id": 148698, "type": "Feature", "street": "WALLACE"} |

| {"id": 45214, "type": "Feature", "street": "HAIGHT"} |

+--------------------------------------------------------+

3 rows in set (3.11 sec)

Page 55: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | 56

Funções JSON

JSON_ARRAY_APPEND()

JSON_ARRAY_INSERT()

JSON_ARRAY()

JSON_CONTAINS_PATH()

JSON_CONTAINS()

JSON_DEPTH()

JSON_EXTRACT()

JSON_INSERT()

JSON_KEYS()

JSON_LENGTH()

JSON_MERGE()

JSON_OBJECT()

JSON_QUOTE()

JSON_REMOVE()

JSON_REPLACE()

JSON_SEARCH()

JSON_SET()

JSON_TYPE()

JSON_UNQUOTE()

JSON_VALID()

https://dev.mysql.com/doc/refman/5.7/en/json-functions.html

Page 56: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Whats New? MySQL 5.7.12+

• New Server Features – Native JSON datatype and storage

– Generated Columns with Indexing

– Over 20+ Native JSON functions

– New X Protocol

• New Document APIs – SQL and NoSQL/Document CRUD APIs will cross all Connectors

• For BOTH Collections of Documents and Relational Tables

– Initial DMR M1 includes Node.js, Java and .NET

• New Interactive Shell – with Javascript, Python, SQL modes

57

Page 57: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Arquitetura

58

MySQL

Plugins

X Protocol Plugin Memcached Plugin Core

X Protocol Std Protocol

X Protocol 33060

Std Protocol 3306

SQL API CRUD API

X and Std Protocols

MySQL Shell

Page 58: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

XDev API

• Foco: facilidade de uso

• Abstração sobre SQL para operações CRUD

• Add

• Find

• Modify

• Remove

• Sort

• Create Index

• X Sessions & Node Sessions

– abstração da conexão com BD

• Atualização dos conectores

– Connector/J

– Connector/Net

– Connector/Node.js

Oracle Confidential – Internal/Restricted/Highly Restricted 59

Page 59: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 60

CRUD: Documento vs Relacional

Page 60: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 61

MySQL Shell

Page 61: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 63

Page 62: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 64

Page 63: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. | Oracle Confidential – Internal/Restricted/Highly Restricted 65

Page 64: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Coluna

• Mais integridade no schema, independente da aplicação

• Schema torna a aplicação mais fácil de manter no longo prazo, pois há maior controle nas mudanças

– Espera-se uma maior qualidade dos dados

– Permite aplicação de algumas validações automáticas sobre os dados

JSON

• Mais liberdade para representar dados (ex. Campos custom)

• Denormalização natural, registro auto-contido (ex. facilita escalabilidade horizontal via sharding)

• Protótipos rápidos, comece armazenar dados imediatamente

• Menor preocupação na definição de Tipos de Dados

• Menos dor-de-cabeça para aplicar mudanças no modelo de dados

Oracle Confidential – Internal/Restricted/Highly Restricted 66

Coluna ou JSON? Você escolhe!

Page 65: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Modelo híbrido: Schema + Schemaless

67

CREATE TABLE product_info_hybrid (

product_id INT NOT NULL PRIMARY KEY,

description VARCHAR(60) NOT NULL,

vendor VARCHAR(30) NOT NULL,

price FLOAT NOT NULL,

attributes JSON NOT NULL

);

Page 66: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Sumário

1. O movimento NoSQL é de grande relevância e tem os gigantes da Web como protagonistas

2. MySQL continua muito relevante na Web com a vantagem de ser extremamente popular e maduro

3. Novas funcionalidades Document Store do MySQL são exemplo de como bancos relacionais podem abraçar o NoSQL

Page 67: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Links úteis para seguir com os testes

MySQL as a Document Database http://dev.mysql.com/doc/refman/5.7/en/document-database.html

MySQL Shell http://dev.mysql.com/doc/refman/5.7/en/mysql-shell.html http://dev.mysql.com/doc/refman/5.7/en/mysqlx-shell-tutorial-javascript.html http://dev.mysql.com/doc/refman/5.7/en/mysqlx-shell-tutorial-python.html

X Dev API http://dev.mysql.com/doc/x-devapi-userguide/en/

X Plugin http://dev.mysql.com/doc/refman/5.7/en/x-plugin.html

MySQL JSON http://mysqlserverteam.com/tag/json/ https://dev.mysql.com/doc/refman/5.7/en/json.html https://dev.mysql.com/doc/refman/5.7/en/json-functions.html

69

Page 68: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Obrigado!

Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Page 69: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

@MySQLBR meetup.com/MySQL-BR facebook.com/MySQLBR

pt.planet.mysql.com

Page 70: MySQL 5.7 como Document Store

Copyright © 2015 Oracle and/or its affiliates. All rights reserved. |

Perguntas?

MySQL como Document Store Contato: [email protected] twitter.com/mysqlbr facebook.com/mysqlbr

Page 71: MySQL 5.7 como Document Store