More Related Content
Similar to db tech showcase2016 - MySQLドキュメントストア (20)
More from Shinya Sugiyama (18)
db tech showcase2016 - MySQLドキュメントストア
- 1. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. |
MySQLドキュメントストア
RDBMS & NoSQL, Best of the both world
日本オラクル株式会社
MySQL Global Business Unit
MySQL Principal Sales Consultant/Shinya Sugiyama
db tech showcase Tokyo 2016 Session - B12:MySQL
日付: 2016/07/13~7/15
- 2. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
Safe Harbor Statement
以下の事項は、弊社の一般的な製品の方向性に関する概要を説明するものです。
また、情報提供を唯一の目的とするものであり、いかなる契約にも組み込むことはでき
ません。以下の事項は、マテリアルやコード、機能を提供することをコミットメントするも
のではない為、購買決定を行う際の判断材料になさらないで下さい。
オラクル製品に関して記載されている機能の開発、リリースおよび時期については、
弊社の裁量により決定されます。
2
- 3. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 3
The world's most popular open source database
世界で最も普及しているオープンソース データベース
- 4. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 4
例) DB-Enginesによる調査結果
The world's most popular open source database
■ グローバルで多くの利用者
■ グローバルで多くの人材
■ 多種・多用な管理ツール
■ Oracle社が企業として対応
- バージョンリリース、パッチ
http://bugs.mysql.com/
- フルタイムの専任開発者
- 開発ロードマップ(ユーザベース)
- 組み込み利用時のIP対応
http://db-engines.com/en/
データベースソフトウェアの普及度や
人気を、インターネット上の求人情報
や職務経歴上での経験、および検索
エンジンやSNSでの情報量を元に、
毎月ランキングを作成し公開。
※登録データベース:300以上
- 5. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 5
MySQLの歴史
4.0
全文検索/GIS (MyISAM)
複数テーブルUPDATE/DELETE
組み込みライブラリ型サーバ
OracleMySQL Sun
3.23
MyISAM
InnoDB
レプリケーション
5.1
プラグガブル・
ストレージエンジン・
アーキテクチャ
パーティショニング
タスクスケジューラ
5.6
memcached API
UNDO表領域
Global Transaction ID
マルチスレッドスレーブ
オンラインALTER TABLE
トランスポータブル表領域
5.5
InnoDBがデフォルトに
準同期型レプリケーション
PERFORMANCE_SCHEMA
1.0-3.22以前
ストレージエンジン (ISAM, HEAP)
マルチスレッド
Windows対応/64bit対応
日本語文字コード (SJIS/UJIS)
5.0
ストアドプロシージャ
ストアドファンクション
カーソル/トリガ/ビュー
XAトランザクション
INFORMATION_SCHEMA
4.1
Unicode対応
サブクエリ
CSV, ARCHIVE
ndbcluster
1995 2000 2005 2010 2015
5.7
2015年10月21日 - 5.7.9 GA
新コストモデル オプティマイザ
ロスレス レプリケーション
マルチソース レプリケーション
グループ レプリケーション(Up Coming)
全文検索CJK対応/GIS (InnoDB)
セキュリティ強化 (コンプライアンス対応)
NoSQLオプション (JSON)
General Tablespace (生成列)
MySQL Router (HA) and more…
Performance: Benchmark
・ 1995年:スウェーデンにてMySQL AB設立
(2005年:オラクルがInnobase Oyを買収)
・ 2008年:Sun MicrosystemsがMySQL ABを買収
・ 2010年:オラクルがSun Microsystemsを買収
- 6. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 6
Agenda
1. ドキュメントストア概要
• リレーショナルとスキーマレス(ドキュメントデータ)
2. MySQL JSONデータ
• JSONデータ型、関数、生成列
3. ドキュメント処理拡張機能
• X Protocol , X DevAPI, MySQL Shell
4. 備考
• その他,MySQL参考情報
- 7. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 7
ドキュメントストア概要
- 8. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
ドキュメントデータ
• 形式・様式 (ex: XML, JSON)
• ツリー構造 ( [], {} )
• スキーマレス
+-----------------------------------------------------------------------------+
| body |
+-----------------------------------------------------------------------------+
| {"id": 1, "name": "自転車", "price": 10000, "Conditions": ["NEW", 2015]} |
| {“id”: 2, “name”: “テレビ", "price": 30000, "Conditions": ["USED", 2013]} |
| {"id": 3, "name": "冷蔵庫", "price": 10438, "Conditions": ["NEW", 2015]} |
| {"id": 4, "name": "冷蔵庫", "price": 50000, "Conditions": ["NEW", 2015]} |
| {"id": 5, "name": "自転車", "price": 25000, "Conditions": ["NEW", 2015]} |
+-----------------------------------------------------------------------------+
8
CREATE TABLE T_JSON_DOC (body json);
- 9. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
リレーショナルとスキーマレス?
9
両方共にそれぞれのアプローチの利点
mysql> SELECT * FROM pizza;
+------+------------------+-------+
| code | name | price |
+------+------------------+-------+
| CLA | Classic Pizza | 400 |
| MAR | Margherita Pizza | 500 |
+------+------------------+-------+
mysql> SELECT * FROM toppings;
+--------+------------+
| p_code | name |
+--------+------------+
| CLA | Pepperoni |
| CLA | Parmesan |
| MAR | Basil |
| MAR | Mozzarella |
+--------+------------+
{
"name":"Classic Pizza", "price":400,
"toppings":[
"Pepperoni", "Parmesan"
]
}
{
"name":"Margherita Pizza", "price":500,
"toppings":[
"Basil", "Mozzarella"
],
"options":[
{
"name":"Olive", "price":100
}
]
}
リレーショナル スキーマレス (ドキュメント)
属性値のペアのコレクション表, カラム, 行
- 10. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 10
□ アプリケーションに対し、スキーマの適用が容易
□スキーマにより長期的に、アプリケーションの変更管理がコントロールしやすい
- 表, カラム, 行を使用して効率よくデータを管理
- データにいくつかの制約設定を可能 (データ型、外部キー制約等)
- データ重複を削減する事が可能 (正規化)
□スキーマ内でモデル化する事が困難であるデータをより柔軟に表現可能
例) 不特定多数のお客様へ,SaaSアプリケーション提供してる場合等
- 自由なデータ構造でカスタムフィールドをサポート
- 容易な非正規化は、特定の状況において重要である最適化手法
- 労力を伴うスキーマ変更が不要 (メモ: MySQL5.6以降ではオンラインDDLが強化)
- 迅速且つ容易な設計・プロトタイピング (データ型やスキーマの強制不要)
リレーショナル
スキーマレス (ドキュメント)
- 11. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
• 単一データベース
– MySQLデータベースでより多くの
メンバーが管理可能
• 熟知したスキルで安定稼働
– 管理コストメリット
– 少ないドライバー
– 少ないツールで管理
– 容易なデータ連携
– 運用及び分析を一緒に
– SQL処理, CRUD処理
• 複数の異なったデータベース
– より多くのスキルレパートリーが必要,
より複雑な開発 …
• スキルの取得がより困難に
– 管理コスト増加
– 多くのドライバー
– 多くの管理ツール
– データ連携に工数・コストがかかる
– 運用と分析を別々のシステムで処理
単一 vs 複数データベースで管理?
11
Relational Tables
Schema less JSON Collection
Relational Tables Schema less JSON Collection
- 12. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
ドキュメントストア機能拡張 in MySQL5.7
• リレーショナル、スキーマレスを同じ技術スタックで利用可能
• MySQLに実装されている機能を活用可 (レプリケーション,InnoDB[ACID]等)
• JSONデータ型と関数,追加されたCRUD APIによる容易な開発
12
開発チーム:
[ x ] スキーマレス
[ x ] 迅速なプロトタイプ/シンプルAPI
[ x ] ドキュメントモデル
オペレーション:
[ x ] パフォーマンス管理/可視化
[ x ] 堅牢レプリケーション,バックアップ, リストア
[ x ] 包括的なツールによるエコシステム
ビジネス:
[ x ] データを確実に保護 = ACIDトランザクション
[ x ] 全てのデータをキャプチャー = 拡張性/スキーマレス
[ x ] スケージュール/製品化の時間 = 迅速なサービス開発
【ステークスホルダーのニーズを満たす為の機能追加】
- 13. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
MYSQLのドキュメントストア機能拡張
13
• JSONサポート
JSONデータ型(utf8mb4)・JSONファンクション
Generated Column(生成列)とIndexによる検索の高速化
MySQL 5.7.9(GA)
• X Protocol ☑ GA
MySQLサーバをドキュメントストアとして拡張する為に、
Xプラグイン(mysqlx)により実装
• X DevAPI ☑ Development Release
SQL処理とドキュメントに対してのCRUD処理
Connector/Node.js, Connector/J, Connector/Netに実装
• mysqlsh ☑ Development Release
コマンドラインクライアント (Javascript, Python, SQL)
MySQL 5.7.12~
参考: https://dev.mysql.com/doc/refman/5.7/en/document-store.html
- 14. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 14
MySQL JSONデータ
MySQL 5.7.9 ~
- 15. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
JSONデータ
ネイティブJSONデータ型 (バイナリ形式)
Insert時のJSON構文バリデーション機能
組み込みJSON関数 (保存、検索、更新、操作)
ドキュメントにインデックス設定可能
SQLとの統合を容易にする、新しいインライン構文
utf8mb4の文字セットとutf8mb4_binの照合 「🐬」
サイズはmax_allowed_packetの値で制限 (Default:4MB)
外部サイト
/SNS
モバイル
デバイス
コマース
/ポータル
その他
(data JSON);
REST/JSON
mysql> select feature from NEW57.features where json_extract(feature,'$.properties.STREET') = 'MARKET' limit 1¥G
************** 1. row **************
feature: {"type": "Feature", "geometry": {"type": "Polygon", "coordinates": [[[-122.39836263491878,
37.79189388899312, 0], [-122.39845248797837, 37.79233030084018, 0], [-122.39768507706792, 37.7924280850133,
0], [-122.39836263491878, 37.79189388899312, 0]]]}, "properties": {"TO_ST": "388", "BLKLOT": "0265003", "STREET":
"MARKET", "FROM_ST": "388", "LOT_NUM": "003", "ST_TYPE": "ST", "ODD_EVEN": "E", "BLOCK_NUM": "0265",
"MAPBLKLOT": "0265003"}}
15
- 16. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
連携:リレーショナルテーブルからJSON抽出
SELECT NAME,CountryCode from
world.City where CountryCode ='JPN' limit 1;
+-------+-------------+
| NAME | CountryCode |
+-------+-------------+
| Tokyo | JPN |
+-------+-------------+
16
SELECT JSON_OBJECT('CITY',NAME,'Country',CountryCode)
from world.City where CountryCode ='JPN' limit 1;
+------------------------------------------------+
| JSON_OBJECT('CITY',NAME,'Country',CountryCode) |
+------------------------------------------------+
| {"CITY": "Tokyo", "Country": "JPN"} |
+------------------------------------------------+
リレーショナルから
スキーマレスへの変換
[NEW57]> CREATE VIEW v_City_json AS
-> SELECT JSON_OBJECT('ID', ID, 'name', Name, 'CountryCode', CountryCode, 'District',
District,'Population',Population) as doc FROM City where CountryCode = 'JPN';
Query OK, 0 rows affected (0.01 sec)
[NEW57]> select * from v_City_json limit 1¥G
*************************** 1. row ***************************
doc: {"ID": 1532, "name": "Tokyo", "District": "Tokyo-to", "Population": 7980230, "CountryCode": "JPN"}
1 row in set (0.01 sec)
例) ビュー
JSON関数: JSON_OBJECT(), JSON_ARRAY()
- 17. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 17
特徴:JSONデータ処理
JSONデータ型(バイナリー)
による高速な処理
データを参照した場合の
TEXT型とJSONデータ型のパフォーマンス
JSONデータ型と生成列による
INDEXを利用した高速な参照処理
※VirtualとStoredの違いに関しては,P.18を参照下さい。
JSON関数を利用したデータ処理
例) INPLACEアップデート
※その他、JSON関数に関しては,P.19を参照下さい。
JSONドキュメントの一部のみ更新可
UPDATE T_JSON_DOC set T_JSON_DOC.body =
JSON_REPLACE(body,"$.price",FLOOR(10000 + (RAND() * 9000))) where id = 3
- 18. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
参考) 使用可能なインデックスオプション
18
Generated Column (STORED)
挿入・更新時に演算、値を格納
Generated Column (VIRTUAL)
参照時に演算、値は格納しない
Primary and Secondary
BTREE, Fulltext, GIS
Mixed with fields
Requires table rebuild
Not Online
Secondary Only
BTREE Only
Mixed with virtual column only
No table rebuild
INSTANT Alter
Faster Insert
Bottom Line: 主キー, FULLTEXTまたは仮想GISインデックスを必要とする場合を除き,デフォルトのVIRTUALで問題無い。
Advantage
Disadvantage
- 19. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 19
JSON関数
• 情報取得
– JSON_VALID()
– JSON_TYPE()
– JSON_KEYS()
– JSON_LENGTH()
– JSON_DEPTH()
– JSON_CONTAINS()
– JSON_CONTAINS_PATH()
• データ編集
– JSON_REMOVE()
– JSON_APPEND()
– JSON_SET()
– JSON_INSERT()
– JSON_REPLACE()
– JSON_ARRAY_INSERT()
• データ作成
– JSON_MERGE()
– JSON_ARRAY()
– JSON_OBJECT()
• データ取得
– JSON_EXTRACT()
– JSON_SEARCH()
– -> /* JSON_EXTRACT() */
– ->> /* JSON_UNQUOTE(JSON_EXTRACT()) */
• ヘルパー
– JSON_QUOTE()
– JSON_UNQUOTE()
– JSON_VALID()
参照: https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html
- 20. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 20
ドキュメント処理拡張機能
X Protocol , X DevAPI, MySQL Shell
MySQL 5.7.12 ~
- 21. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
MySQL 5.7.12 ~ コネクター, ドライバー, プロトコル
MySQL
Plugins
X Protocol Plugin Memcached Plugin
Core
MySQL Connectors and Drivers
X ProtocolStd Protocol
Memcached
driver
X Protocol
33060
Std Protocol
3306
SQL API CRUD and SQL APIs
Memcache
Protocol
X and Std
Protocols
MySQL
Shell
21
- 22. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
X Protocol
• 非同期APIサポート – 並列処理とバッチ処理をサポート
– パイプライン方式 – 複数リクエストを送信, ラウンドトリップを削減
– CRUD ==大量に小さなPKを処理, 独立した複数のクエリーを処理
• ミドルウエアとの親和性
– ルーティング、シャーディング、読み取り書き込みスプリッティング (XSESSION)
• オープンスタンダードの利用: TLS (Transport Layer Security),
SASL(Simple Authentication and Security Layer), Protobuf (Protocol Buffers)等
詳細: http://mysqlserverteam.com/mysql-5-7-12-part-2-improving-the-mysql-protocol/
+-------------+----------------+--------------------+
| PLUGIN_NAME | PLUGIN_VERSION | PLUGIN_DESCRIPTION |
+-------------+----------------+--------------------+
| mysqlx | 1.0 | X Plugin for MySQL |
+-------------+----------------+--------------------+
The X Protocol focuses on:
• extensibility
• performance
• security
INSTALL PLUGIN mysqlx SONAME 'mysqlx.so';
22
- 23. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
X Protocol
Query Time
Client ServerNetwork
Stage Time
network path latency 1ms
exectime 0. 1ms
クラッシックリクエスト/レスポンス
Total: 4x path + 2x exectime = 4.2ms
パイプライン処理
Total: 2x path + 2x exectime = 2.2ms
23
Pipelining messages is a core feature of the Mysqlx Protocol.
It sends messages to the server without waiting for a response to save latency. (no mandatory handshake)
参考) https://dev.mysql.com/doc/internals/en/x-protocol-messages-message-structure.html
Network Latencyが大きい
環境では特に効果的!!
例) 東京<-> 九州
日本<-> 海外
- 24. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
X Protocol
24
エラーを無視して続行: Mysqlx.Expect::Open([-no_error])
最初のエラーで失敗 : Mysqlx.Expect::Open([+no_error])
With expectations pipelined, the server will handle errors in a consistent, reliable way. In case error reporting isn't a major topic one can
combine multi-row INSERT with pipelining and reduce the per-row network overhead. This is important in case the network is saturated.
詳細: https://dev.mysql.com/doc/internals/en/x-protocol.html
Expectation
Mysqlx.Expect::Open([+no_error])
- 25. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
参考情報
Spec:
http://dev.mysql.com/doc/internals/en/x-protocol.html
Message Def:
https://github.com/mysql/mysql-server/tree/5.7/rapid/plugin/x/protocol
Protobuf:
https://developers.google.com/protocol-buffers/
$ protoc -I --python_out=... .../mysql.proto
25
Pipeline
https://dev.mysql.com/doc/internals/en/x-protocol-implementation-pipelining.html
https://github.com/mysql/mysql-server/blob/5.7/mysql-test/suite/xplugin/t/crud_pipe.test
Expectations
https://dev.mysql.com/doc/internals/en/x-protocol-expect-expectations.html
https://github.com/mysql/mysql-server/blob/5.7/mysql-test/suite/xplugin/t/expect_noerror.test
独自クライアントを作成する場合
Pipeline及びExpectationsに関して
- 26. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
X DevAPI
• X Pluginを有効にする事で、X Protocol経由で通信可能
• ドキュメントとテーブルのコレクションに対してのCRUD処理
• NoSQLライクな構文でドキュメントに対しCRUD処理可能
• Fluent API
prod = sess.getSchema("prod")
res = prod.users.
find("$.name = 'Milk'").
fields(["name", "properties"])
X Plugin (MySQL) ⇔ X Protocol ⇔ X DevAPI (Driver)
26
MySQL Connector/node.js (1.x)
MySQL Connector/J (6.x)
MySQL Connector/Net (7.x)
MySQL Shell (1.0.x)
参照: http://dev.mysql.com/downloads/connector/
- 27. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
MySQL Connectors include X Dev API
• Use SQL, CRUD APIs
スキーマレスドキュメントおよびリレーショナルテーブルに対応
- Classic APIsに加えて、これらの全てが追加されます
27
Operation Document Relational
Create Collection.add() Table.insert()
Read Collection.find() Table.select()
Update Collection.modify() Table.update()
Delete Collection.remove() Table.delete()
参照) http://dev.mysql.com/doc/x-devapi-userguide/en/crud-operations-overview.html
- 28. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 28
[root@misc01 nodejs]# cat sample_node_X_API.js
const mysqlx = require('mysqlx');
mysqlx.getSession({ host: 'localhost', port: 33060, dbUser: 'demo_user', dbPassword: 'password'
}).then(function (session) {
return session.createSchema("test_schema").then(function (schema) {
return schema.createCollection("myCollection");
}).then(function (collection) {
return Promise.all([
collection.add( {baz: { foo: "bar"}},{foo: { bar: "baz"}}).execute(),
collection.find("$.baz.foo == 'bar'").execute(function (row) {console.log("Row: %j", row);
}).then(function (res) {console.log("Collection find done!");}),
collection.remove("($.foo.bar) == 'baz'").execute().then(function () {
console.log("Document deleted");}), collection.drop() ]);
}).then(function () { return session.dropSchema("test_schema");
}).then(function () { return session.close(); });
}).catch(function (err) { console.log(err.stack); process.exit(); });
[root@misc01 nodejs]# node sample_node_X_API.js
Row: {"_id":"630f0d3b-f6fd-1d99-6d80-a8e90352","baz":{"foo":"bar"}}
Collection find done!
Document deleted Connector:mysql-connector-nodejs-1.0.2.tar.gz
- 29. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
2016-05-06T15:15:05.364983+09:00 37 Query /* xplugin authentication */ SELECT `authentication_string`,
<SNIP>
2016-05-06T15:15:05.369200+09:00 37 Query CREATE DATABASE `test_schema`
2016-05-06T15:15:05.382450+09:00 37 Query CREATE TABLE `test_schema`.`myCollection` (doc JSON,_id
VARCHAR(32) GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(doc, '$._id'))) STORED NOT NULL UNIQUE)
CHARSET utf8mb4 ENGINE=InnoDB
2016-05-06T15:15:05.464364+09:00 37 Query INSERT INTO `test_schema`.`myCollection` (doc) VALUES
('{¥"baz¥":{¥"foo¥":¥"bar¥"},¥"_id¥":¥"c5d6964d-af2a-0b87-36aa-
4f5bc18b¥"}'),('{¥"foo¥":{¥"bar¥":¥"baz¥"},¥"_id¥":¥"3f106b27-e14a-31e0-5297-51da7f1c¥"}')
2016-05-06T15:15:05.481912+09:00 37 Query SELECT doc FROM `test_schema`.`myCollection` WHERE
(JSON_EXTRACT(doc,'$.baz.foo') = 'bar')
2016-05-06T15:15:05.528923+09:00 37 Query DELETE FROM `test_schema`.`myCollection` WHERE
(JSON_EXTRACT(doc,'$.foo.bar') = 'baz')
2016-05-06T15:15:05.551710+09:00 37 Query DROP TABLE `test_schema`.`myCollection`
2016-05-06T15:15:05.565824+09:00 37 Query DROP DATABASE `test_schema`
2016-05-06T15:15:05.643891+09:00 37 Quit
General Log
29
- 30. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
MySQL Shell
• 開発および管理用のシェルの統合
• 一般的なスクリプト・インターフェースを介して
利用可能な MySQLコマンドラインクライアント。
• PythonやJavaScriptなどのスクリプト言語で
さまざまな製品と対話するための完全な開発用API
30
[root@misc01 admin]# mysqlsh --help | egrep -i "Start in"
--sql Start in SQL mode using a node session.
--sqlc Start in SQL mode using a classic session.
--js Start in JavaScript mode.
--py Start in Python mode.
[root@misc01 admin]#
バッチ処理に利用可能
shell> mysqlsh --file code.js
shell> mysqlsh < code.js
shell> echo "show databases" | mysqlsh –sql
2016年7月現在:Development Release: 1.0.3
- 31. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 31
[root@misc01 MID2016]# mysqlsh --uri demo_user@localhost/NEW57 -ppassword
Creating an X Session to demo_user@localhost:33060/NEW57
Default schema `NEW57` accessible through db.
Welcome to MySQL Shell 1.0.3 Development Preview
…….
Currently in JavaScript mode. Use ¥sql to switch to SQL mode and execute queries.
mysql-js> db.createCollection("x_posts");
<Collection:x_posts>
mysql-js> db.x_posts.add({"title":"Hello World", "text":"This is the first post via mysqlx"});
Query OK, 1 item affected (0.01 sec)
mysql-js> db.x_posts.find("title = 'Hello World'").sort(["title"]);
[
{
"_id": "baee9a744308e61168170800279cea3c",
"text": "This is the first post via mysqlx",
"title": "Hello World"
}
]
1 document in set (0.00 sec) MySQL Shell Version 1.0.3 Development Preview
session.getSchema(‘NEW57')
- 32. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
2016-05-26T23:24:45.694581+09:00 11 Query /* xplugin authentication */ SELECT `authentication_string`,
<SNIP>
2016-05-26T23:24:45.695786+09:00 11 Query show databases
2016-05-26T23:24:45.697994+09:00 11 Query select schema(), @@lower_case_table_names
2016-05-26T23:24:45.698455+09:00 11 Query select connection_id()
2016-05-26T23:24:45.698899+09:00 11 Query use `NEW57`
2016-05-26T23:24:45.699441+09:00 11 Query SELECT table_name, COUNT(table_name) c FROM
information_schema.columns WHERE ((column_name = 'doc' and data_type = 'json') OR (column_name = '_id' and
generation_expression = 'json_unquote(json_extract(`doc`,''$._id''))')) AND table_schema = 'NEW57' GROUP BY table_name
HAVING c = 2
2016-05-26T23:24:45.701333+09:00 11 Query SHOW FULL TABLES FROM `NEW57`
2016-05-26T23:24:45.703443+09:00 11 Query SELECT table_name, COUNT(table_name) c FROM
information_schema.columns WHERE ((column_name = 'doc' and data_type = 'json') OR (column_name = '_id' and
generation_expression = 'json_unquote(json_extract(`doc`,''$._id''))')) AND table_schema = 'NEW57' GROUP BY table_name
HAVING c = 2
2016-05-26T23:24:45.706091+09:00 11 Query SHOW FULL TABLES FROM `NEW57`
2016-05-26T23:25:15.862883+09:00 11 Query CREATE TABLE `NEW57`.`x_posts` (doc JSON,_id VARCHAR(32) GENERATED
ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(doc, '$._id'))) STORED NOT NULL UNIQUE) CHARSET utf8mb4 ENGINE=InnoDB
2016-05-26T23:25:38.026317+09:00 11 Query INSERT INTO `NEW57`.`x_posts` (doc) VALUES
('{¥"_id¥":¥"de3e8cb74d23e6112c1d0800279cea3c¥",¥"text¥":¥"This is the first post via mysqlx¥",¥"title¥":¥"Hello
World¥"}')
2016-05-26T23:25:57.011923+09:00 11 Query SELECT doc FROM `NEW57`.`x_posts` WHERE (JSON_EXTRACT(doc,'$.title')
= 'Hello World') ORDER BY JSON_EXTRACT(doc,'$.title')
32
General Log
- 33. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
root@localhost [NEW57]> SELECT table_name, COUNT(table_name) c FROM
information_schema.columns WHERE ((column_name = 'doc' and data_type = 'json') OR
(column_name = '_id' and generation_expression =
'json_unquote(json_extract(`doc`,''$._id''))')) AND table_schema = 'NEW57' GROUP BY
table_name HAVING c = 2;
+------------------------+---+
| table_name | c |
+------------------------+---+
| Innovation_Day | 2 |
| Innovation_Day_Confirm | 2 |
| X_JSON | 2 |
| x_posts | 2 |
| X_PYTHON | 2 |
+------------------------+---+
テーブル構造(doc json列+generated columnのPK(_id)
から、通常のテーブルとドキュメントストアを判別
mysql-js> db.getCollections()
{
"Innovation_Day":
<Collection:Innovation_Day>,
"Innovation_Day_Confirm":
<Collection:Innovation_Day_Confirm>,
"X_JSON": <Collection:X_JSON>,
"X_PYTHON": <Collection:X_PYTHON>,
"x_posts": <Collection:x_posts>
}
mysql-js> db.getTables()
{
"T_GIS": <Table:T_GIS>,
"T_JSON_DOC": <Table:T_JSON_DOC>,
"T_JSON_DOC_TXT": <Table:T_JSON_DOC_TXT>,
"T_TDE": <Table:T_TDE>,
"citylots": <Table:citylots>,
"employees": <Table:employees>,
"employees_json": <Table:employees_json>,
"employees_txt": <Table:employees_txt>,
33
- 34. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
MySQL5.7~ ドキュメント関連機能の連携デモ
JSON Data Type, MySQL Shell, X Protocol, Generated Column, FTS
Twitter API: (#dbts2016を含むJSONデータ)
https://api.twitter.com/1.1/search/tweets.json
Localhost
port:33060
Schema:NEW57
myDb = mySession.getSchema('NEW57')
<SNIP>
timeline = json.loads(res.text)
for tweet in timeline:
myDb.dbts2016.add(tweet).execute()
Shell> mysqlsh --py < demo_python_twitter.py
+-------+--------------+------+-----+---------+------------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+------------------+
| doc | json | YES | | NULL | |
| _id | varchar(32) | NO | PRI | NULL | STORED GENERATED |
| name | varchar(64) | YES | MUL | NULL | STORED GENERATED |
| text | varchar(512) | YES | MUL | NULL | STORED GENERATED |
+-------+--------------+------+-----+---------+------------------+
(1)Twitter APIに接続しJSONフォーマットのTweetを取得
(2) 取得したJSONデータを.addでテーブルに追加
(3) Generated ColumnやFTSを利用してデータ参照処理
OAuth1Session
mysqlx
34
- 35. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 35
参考) デモテーブル定義
CREATE TABLE `dbts2016` (
`doc` json DEFAULT NULL,
`_id` varchar(32) GENERATED ALWAYS AS (json_unquote(json_extract(`doc`,'$._id'))) STORED NOT NULL,
`name` varchar(64) GENERATED ALWAYS AS (json_unquote(json_extract(`doc`,'$.user.name'))) STORED,
`text` varchar(512) GENERATED ALWAYS AS (json_unquote(json_extract(`doc`,'$.text'))) STORED,
UNIQUE KEY `_id` (`_id`),
KEY `idx_name` (`name`),
FULLTEXT KEY `ft_idx_text` (`text`) /*!50100 WITH PARSER `mecab` */
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
列 概要 補足
doc TwitterからgetしてきたJSONデータを格納 JSONデータ型
_id MySQLが自動的に付与したドキュメントのUNIQUEなID 自動生成ID
name Tweetしたユーザーのユーザー名をJSON関数で動的にdocから取得して作成した列 生成列+インデックス
text TweetしたユーザーのコメントをJSON関数で動的にdocから取得して作成した列 生成列+全文検索
- 36. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 36
参考) demo_python_twitter.py抜粋
# coding: utf-8
from requests_oauthlib import OAuth1Session
import datetime
import json
import mysqlx
api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
api_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
token = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
token_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
url =
"https://api.twitter.com/1.1/search/tweets.json?"
params = {
"q": "#dbts2016",
"lang": "ja",
"result_type": "recent",
"count": "100"
}
auth = OAuth1Session(api_key, api_secret, token,
token_secret)
res = auth.get(url, params = params)
if res.status_code == 200: # 成功した場合
mySession = mysqlx.getSession({
'host': 'localhost', 'port': 33060,
'dbUser': 'demo_user', 'dbPassword': 'password'} )
myDb = mySession.getSchema('NEW57')
timeline = json.loads(res.text)
for tweet in timeline["statuses"]:
myDb.dbts2016.add(tweet).execute()
else: # 失敗した場合
print ("Error: %d" % req.status_code)
- 37. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 37
Tweet結果:デモ当日 (As of 2016/07/13)
shell> echo "select name,count(name) from dbts2016 group by name order by count(name) desc limit 10;" |
mysqlsh -u demo_user -ppassword --sql --schema=NEW57
mysqlx: [Warning] Using a password on the command line interface can be insecure.
+-----------------------------------+-------------+
| name | count(name) |
+-----------------------------------+-------------+
| yoku0825 | 29 |
| Tadashi Yamashita | 25 |
| Hiroshi Sekiguchi | 4 |
| Cassandra Japan | 3 |
| Toyofuta@7/13-15dbts | 3 |
| インサイトテクノロジー | 3 |
| Takashi Takizawa | 2 |
| Takuya Noguchi | 2 |
| Akira Shimosako | 2 |
| tetsuya_kaneko | 2 |
+-----------------------------------+-------------+
Sessionデモの段階でハッシュタグ
#dbts2016でTweetしたユーザー
とTweet数。
PS: JSONで取得した値に対して、
生成列をユーザー名で作成して
Group by
- 38. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 38
FTS結果:デモ当日 (As of 2016/07/13)
shell> mysql -u demo_user -ppassword -e "SET GLOBAL
innodb_ft_aux_table='NEW57/dbts2016';SELECT
WORD,count(WORD) FROM
INFORMATION_SCHEMA.INNODB_FT_INDEX_TABLE group by WORD
order by count(WORD) desc,WORD desc limit 20;"
+-----------------------------+-------------+
| WORD | count(WORD) |
+-----------------------------+-------------+
| 2016 | 103 |
| dbts | 91 |
<snip...>
| 技術 | 6 |
| ドキュメントストア | 6 |
| ストレージ | 6 |
| サポート | 6 |
<snip...>
| 処理 | 4 |
| メモリ | 4 |
| データベース | 4 |
| スタッフ | 4 |
| ゴリラ | 4 |
| エキスパート | 4 |
+-----------------------------+-------------+
FTSを併用し、mecab辞書と生成列
を連携し,つぶやかれている単語と
回数をGroup byして取得した値。
- 39. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 39
備考
その他、MySQL参考情報
- 40. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 40
MySQLのコミュニティ版と商用版
MySQL はデュアルライセンスソフトウェアです。ビジネスの変化や状況に応じて、
CommunityやCommercial Editionを使い分けて頂く事で,常に最適なソリューションを選択可能。
• MySQL Community Server
• MySQL Cluster
• MySQL GUI管理ツール
• MySQLコネクタ (JDBC, ODBC, etc.)
• ドキュメント
• フォーラム
Community Edition (GPL)
•Standard Edition (サポートのみ)
•Enterprise Edition (サポートとツール)
•MySQL Cluster Carrier Grade Edition
• 商用ライセンス (組み込み用)
• プロフェッショナルサービス
• トレーニング、コンサルティング、サポート
Commercial Edition
コミュニティ版ソフトウェアはGPLv2でソースコードも公開し提供
商用版は、付加価値として技術サポートや管理機能、拡張機能を有償で提供
コストを抑えた初期投資、ビジネス規模や重要性に応じた商用版によるサポート
- 41. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 41
MySQL Enterprise Edition管理ツールと拡張機能を付加
目的 MySQL Enterprise Edition 概要
TCO削減 MySQL Enterprise Monitor 複数サーバの一括管理、クエリ性能分析
TCO削減 Oracle Enterprise Manager for MySQL Oracle Enterprise ManagerからMySQLを統合管理可能
TCO削減と最適化 Oracle Premier Support 24x7, インシデント無制限、コンサルティングサポート
品質維持 MySQL Enterprise Scalability Thread Poolプラグインによる性能拡張性の向上
機会損失対策 MySQL Enterprise Backup 高速なオンラインバックアップ、ポイントインタイムリカバリ
セキュリティ
コンプライアンス
MySQL Enterprise Authentication LDAPやWindows Active Directoryとの統合認証と管理
セキュリティ
コンプライアンス
MySQL Enterprise TDE データベースオブジェクトの透過的暗号化
セキュリティ
コンプライアンス
MySQL Enterprise Audit ユーザ処理の監査、Oracle DBと同じツールで管理可能
セキュリティ
コンプライアンス
MySQL Enterprise Encryption 非対称暗号化(公開鍵暗号)の業界標準機能を提供
セキュリティ
コンプライアンス
MySQL Enterprise Firewall SQLインジェクション対策
- 42. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
MySQL Enterprise Monitor
• 複数のMySQLサーバを一括監視可能な
ダッシュボード
• システム中のMySQLサーバやレプリ
ケーション構成を自動的に検出し監視
対象に追加
• ルールに基づく監視・警告・アドバイス
• 問題が発生する前に通知
• 問題のあるSQL文の検出、統計情報の
分析が可能なQuery Analyzer
42
参照:MySQL Enterprise Monitor
"バーチャルなMySQL DBA"
- 43. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
クエリ解析機能 - MySQL Query Analyzer
• 全てのMySQLサーバの
全てのSQL文を一括監視
• vmstatなどのOSコマンドやMySQLの
SHOWコマンドの実行、
ログファイルの個別の監視は不要
• クエリの実行回数、エラー回数、
実行時間、転送データ量などを
一覧表示
• チューニングのための
解析作業を省力化
43
負荷の高い
処理を迅速
に特定可能
早期対応と改善
- 44. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
レプリケーションモニター:トポロジビュー
• レプリケーション・グループ設定の監視
• レプリケーションチャネルビュー
• 複数トポロジ対応(マスタ/スレーブ、マルチソース、円形、リング)
• レプリケーション関係にある複数データベースを一元管理
44
NEW
In 3.2
- 45. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
MySQL Enterprise Support
• 最大のMySQLのエンジニアリングおよびサポート組織
• MySQL開発チームによるサポート
• 29言語で世界クラスのサポートを提供
• メンテナンス・リリース、バグ修正、パッチ、アップデートの提供
• 24時間x365日サポート
• 無制限サポート・インシデント
• MySQL コンサルティング・サポート
45
Get immediate help for any MySQL
issue, plus expert advice
- 46. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
MySQL Supportの特徴
• 「パフォーマンス・チューニング」や「SQLチューニング」まで
通常サポートの範囲内
– コンサルティングサポートが含まれており、「クエリ・レビュー」、「パフォーマンス・
チューニング」、「レプリケーション・レビュー」、 「 スキーマレビュー」、
「パーティショニング・レビュー」, 「コードレビュー」などに対応可能
– 詳細はこちらを参照下さい
http://www-jp.mysql.com/support/consultative.html
• ソースコードレベルでサポート可能
– ほとんどのサポートエンジニアがソースを読めるため、
対応が早い開発エンジニアとサポートエンジニアも
密に連携している
46
- 47. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 47
30日間トライアル
MySQL Enterprise Edition & Cluster CGEの試使用
• Oracle Software Delivery Cloud
http://edelivery.oracle.com/
• 製品パックを選択:
"Product" にMySQLと入力し、
OSを選択し"Continue"
• 製品マニュアル
http://dev.mysql.com/doc/index-enterprise.html
- 48. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
MySQLの最新情報配信
• MySQLホームページ
http://www-jp.mysql.com/
• MySQL イベント
http://www-jp.mysql.com/news-and-events/events/
• MySQLニュースレター(月刊)※マイプロファイル内からMySQLを選択ください
http://www.oracle.com/jp/syndication/subscribe/index.html
• MySQL Twitter
@mysql_jp
• OTN セミナー オンデマンド コンテンツ
http://www-jp.mysql.com/news-and-events/generate-article.php?id=1709
48
- 49. Copyright © 2016, Oracle and/or its affiliates. All rights reserved.
お問合せ先
• [MySQL お問い合わせ窓口]
0120-065556
• 【受付時間】
平日 9:00-12:00/13:00-18:00
(祝日及び年末年始休業日を除きます)
MySQL-Sales_jp_grp@oracle.com
49
- 50. Copyright © 2016, Oracle and/or its affiliates. All rights reserved. 50
有難うございました