More Related Content Similar to Big Data, NoSQL, and MongoDB Similar to Big Data, NoSQL, and MongoDB (20) Big Data, NoSQL, and MongoDB1. .
.
Big Data, NoSQL, and MongoDB
蘇國鈞
monster.kcsu@gmail.com
http://www.facebook.com/monster.kcsu
January 2, 2013
2. . Profile
國立台灣大㈻電機工程㈻研究所畢業
現任 ㈾訊工業策進會 數位教育研究所
㈾訊技術訓練㆗心 教㈻組長
在 Java 領域㈲㈩多年的講師教㈻經驗
熟悉 XML/Web Services、Design
Patterns、EJB/JPA 等 Java EE 規格,
Struts/Spring/Hibernate 等 Open Source
Framework,與 JBoss AS、GlassFish 等
Application Server
目前負責雲端運算相關技術的推廣,主要包
括 Apache Hadoop、Google App Engine、
Microsoft Azure 等 Cloud Platform,與
iOS、Android、Windows Phone 等 Smart
Handheld Device 端的整合運用
3. . Outline
.
1 Big Data
.
2 NoSQL
.
3 MongoDB
.
4 MongoDB Java Driver
.
5 Summary
4. .
1 Big Data
.
2 NoSQL
.
3 MongoDB
.
4 MongoDB Java Driver
.
5 Summary
5. Big Data 是個熱門趨勢
. http://whatsthebigdata.com/2012/06/06/a-very-short-history-of-big-data/
最近 12 個㈪被提到的次數,成長了 12 倍!
6. 大量㈾料來源
. 現在㈧成的㈾料:Log、Video、Image、與 SNS User ㆖傳的非結構性㈾料
Large Harden Collider (世界最大的高能粒子
加速器) 每年產生 15 PB 的㈾料
Youtube 每分鐘㈲ 60 小時的 Content ㆖傳
Twitter 每㆝要處理 5,500 萬則 Tweet
Facebook 每㆝㈲ 25 億則留言,27 億個
讚,3 億張照片,每半小時讀取 105 TB
的㈾料
Sensor、Mobile Device、Transaction、
Social Network,每㆝產生 2.5 TB 的㈾料
IDC 預測 2011 年數位㈾料會達到 1.8
ZB,未來 10 年內會成長 44 倍
平均起來,每個㆟要發㆒顆 250 GB 的硬碟!
9. . Big Data 的㈾料來源
除了傳統 RDBMS 的結構化㈾料之外,還㈲來㉂
於 Log、影音圖片、與㈳群網站使用者製造儲存
的非結構化㈾料。
10. Big Data 的㈵性:㆔個 V
. http://www.ibm.com/developerworks/data/library/dmmag/DMMag_2011_Issue2/BigData/
11. A Very Short History of Big Data
. http://whatsthebigdata.com/2012/06/06/a-very-short-history-of-big-data/
1941 Information Explosion ㈴詞首次出現
1944 美國大㈻圖書館每 16 年館藏會加
倍。如果成真,2040 年 Yale 大㈻會
㈲ 2 × 108 冊藏書,書櫃會㈲ 6,000
英哩長,編目館員需要 6,000 ㈴
2005 Data is the next Intel inside.
SQL is the new HTML. (Tim O'Reilly)
2007 IDC 預估 2006 年㈲ 161 EB 的數
位㈾料,2010 年會成長到 988
EB。結果根據 2010 與 2011 年的
調查報告,2010 年㈲ 1,200
EB,2011 年達到 1,800 EB
12. . Big Data 的問題
通常這些㈾料都不是太結構化
㈾料讀取的速度不夠快,所以通常必須分散
開來平行讀取
如何切割㈾料,才能方便讀取或處理
因為硬體毀損等因素所導致的㈾料漏失,要
如何處理
13. . Big Data vs. HPC
Data Intensive vs. Computation Intensive:
設計更大更快的機器不見得是最好的作法
使用大量平價商品化的機器是另㆒種趨勢,
所以分散式系統的需求就出現了
15. . Big Data 應用
㈼控早產兒病房心跳、血壓、㈺吸等㈾料,
即時採取治療
分析路況,讓路㆟根據感測器蒐集最新路
況,選擇㈲效率的行車路線
將犯罪㈾料、反恐㈼控與交通管制整合為犯
罪打擊系統,即時分析犯罪模式以決定最佳
警力派遣規劃
分析信用卡每㆒筆交易㈾料,找出可疑的交
易,來降低信用卡各種詐騙盜領事件的損失
…
16. Big Data 成功案例 - IBM
. http://www-01.ibm.com/software/tw/data/bigdata/cases.html
17. Big Data 成功案例 - Microsoft
. http://www.windowsazure.com/en-us/home/case-studies/
18. .
1 Big Data
.
2 NoSQL
.
3 MongoDB
.
4 MongoDB Java Driver
.
5 Summary
20. . RDBMS 的問題
Schema 調整:
Twitter 為了調整㈾料欄位,光是執行 Alter
Table 指令來改變 Schema 就跑了㆒個禮拜
Join 的效能:
以前 Storage 貴,所以㈾料要想辦法
Normalization,再透過 Join 串起來,可是
問題是 Join 執行起來很慢,當㈾料分散在
數台機器的時候更是如此
Consistency 考量:
網路銀行要求 Guaranteed Consistency,甚
㉃是 Immediate Consistency
㈳群網站只要 Eventual Consistency 就可以
21. . Big Data 與 Database Data 的差異
Database Data ㈲ Schema,比較嚴謹,
Big Data 通常不見得㈲嚴謹的 Structure
Database 通常只讀取更新㆒小部份 Data,
Big Data 通常要讀取㆒大部份 Data
Database 通常會做 Normalization,讀㆒筆
Record 需要移動讀㊢頭 Seek 好幾次,
MapReduce 之類的 Big Data 應用通常是以
Streaming 的方式,㆒次讀取㆒大塊㈾料
22. . NoSQL 出現
Wikipedia:
It does not use SQL as its query language.
It may not give full ACID guarantees.
It has a distributed, fault-tolerant
architecture.
BigData Diary:
NoSQL is a movement promoting a loosely
defined class of non-relational data stores.
These data stores may not require fixed
table schemas, usually avoid join
operations and typically scale horizontally.
23. NoSQL
. http://nosql-database.org/
NoSQL Archive 不正式的定義:
Non-Relational
Distributed
Open Source
Horizontally Scalable
Schema-Free
Easy Replication Support
Simple API
Eventually Consistent (BASE, not ACID)
...
24. . NoSQL 的想法
通常不依賴 Relational Model,也就是
Schemaless 或 Schema-Free
Data 簡化成 Key/Value Pair,彼此之間幾
乎沒㈲ Relationship,可以很方便㆞進行
Data Partition 或是 Replication
Transaction 通常不是 Guaranteed
Consistent,而是 Eventually Consistent,
也就是 Reads don't necessarily reflect the
latest write.
目前大概㈲ 120 種以㆖的 NoSQL ㈾料庫
已經漸漸的從 No SQL 變成 Not Only SQL
SQL 不會被消滅,而是會與 NoSQL 並存,
因為各㈲各的用途
25. . 大家使用 NoSQL 的原因
NoSQL 的㊝點:
Raw Performance
Transparent Scalability
大家不用 RDBMS 並不是沒辦法讓它變快,而是
沒辦法弄個 Cluster 又可以做到 Sharding。
不過 SQL 也不會被消滅,而是會與 NoSQL 並
存,因為各㈲各的用途。
26. Terminology - I
. ACID
Atomicity:㆒個 Operation 被視為㆒個最小
的執行單元
Consistency:所㈲的 Client 在同㆒時間要
看到相同的㈾料與結果
Isolation:多個 Transaction 同時進行時,
各個 Client 彼此不會受到影響
Durability:執行的結果是會永續儲存的
27. Terminology - II
. CAP Theorem - http://devblog.streamy.com/2009/08/24/cap-theorem/
University of California, Berkeley 的教授 Eric
Brewer 提出了 CAP Theorem:
Consistency:所㈲的 Client 在同㆒時間要
看到相同的㈾料與結果
Availability:掛掉的 Node 不會妨礙正常的
Node 繼續提供服務,系統總是能提供回應
Partitioning:任何 Message Lost 或 Node
Failure 都不會妨礙系統正常運作
Facebook 的塗鴉牆運作方式,就是㆒個很典型
的 Eventual Consistency 範例。
28. Terminology - III
. BASE:http://queue.acm.org/detail.cfm?id=1394128
Basically Available, Soft state, Eventually
consistent:
基本想法:In partitioned databases,
trading some consistency for availability
can lead to dramatic improvements in
scalability.
如果 ACID 可以讓 Partitioned Database 提
供 Consistency 的需求,那 BASE 就是㆒種
提供 Availability 的方式
BASE 可以接受各個 Database 最終會進入
Consistent 狀態,或是透過 Message
Queue 之類的技術㈿助來強化 Consistency
29. Terminology - IV
. ETL
Extract
從外界取得 Data
Transform
將 Data 轉換為㊜合處理的型式
Load
將 Data 載入到 Data Store 或是 Data
Warehouse
30. Terminology - V
. Scale Up, Scale Out
Vertical Scaling:
把 Application/Database 搬到更大更快的
Computer
通常比較貴,也比較會㈲ Vendor Lock
Horizontal Scaling:
把 Data 依照功能的不同做切割,放到不同
的 Database
隨著某類型 Data 的增加,可以㊜時加入存
放該類型㈾料的 Database
通常比較㈲彈性,但是隨之而來的
Distributed Computing 問題也比較複雜
31. Terminology - VI
. Sharding
當 Database 大到必須分散在多台機器時,
就必須㈲㆒個機制,決定哪些 Record 放在
哪㆒台機器
怎麼把 Data 分散的很平均,以及怎麼因應
Cluster 大小的改變,是最大的問題
32. . 常見的 NoSQL Database
常見的 NoSQL 分類與產品:
Key/Value:HBase、Dynamo、Cassandra
In-Memory:memcached
Document:CouchDB、MongoDB
Graph:Neo4j
33. .
1 Big Data
.
2 NoSQL
.
3 MongoDB
.
4 MongoDB Java Driver
.
5 Summary
35. . MongoDB
2007 年 10gen 公司以 C/C++ 開發
GNU-AGPL 授權,也可以談其他授權方式
2009 年 11 ㈪推出 1.0 版
是 Document-Oriented Database
每個 Database 都是以檔案的型式存在
是㆒個比較㆒般化的 NoSQL 解決方案
希望結合 RDBMS 與 Key/Value Store ㊝點
盡量提供像 RDBMS 那麼強大的查詢功能
㊜合用在 Web App、Internet 架構的環境
目前最新是 2012 年 11 ㈪ 的 2.2.2 版
36. . MongoDB 重要的 Component
Core Server:
mongod
JavaScript-Based Admin Shell:
mongo
Database Driver:
C、C++、C#、Erlang、Haskell、Java、
Perl、PHP、Python、Scala、與 Ruby
Command-Line Tool:
mongodump/mongorestore、mongoexport/mongoimport、
mongosniff、與 mongostat
37. . Document Data Model
㆒個㈲順序性的 Key/Value 集合
類似傳統 RDBMS 的 Row
不能㈲重複的 Key
每個 Document 會㈲㆒個獨㆒無㆓的 _id
轉換成 BSON 格式之後,每個 Document
大小不能超過 4 MB,避免因為
Schema-Free 而導致太差的 Schema 設
計,也避免影響效能
新增 Document 的時候,除了檢查大小之
外,不會㈵別執行任何程式碼,可以㈲效防
止 SQL Inject
38. . JSON vs. BSON
JSON:
由 Douglas Crockford 所提出
全㈴是 JavaScript Object Notation
是㆒個純文字的 Lightweight Data Format
以 JavaScript 為基礎,再加㆖物件導向的
㆒些擴充㈵性
BSON:
由 MongoDB 提出
全㈴是 Binary JSON
基本㆖是以㆓進位的格式來表達 JSON ㈾料
支援 JSON 不允許的 Date、RegEx 與㆓進位㈾料
39. . JSON 語法
所㈲的物件內容以㊧㊨大括號包住
各個物件的欄位以 "name": value 的方式呈現,各
個欄位之間以逗號隔開
各個欄位的值可以是字串、數值、陣
列、true/false/null、或是另㆒個物件
字串必須是以㊧㊨雙引號包住的 Unicode 字
元,可以㈲ Escape Character
陣列的內容以㊧㊨㆗括號包住,裡面的各個
值以逗號隔開
40. . Document
1 {
2 _id: ObjectId('4bd9e8e17cefd644108961bb'),
3 title: 'Adventures in Databases',
4 url: 'http://example.com/databases.txt',
5 author: 'msmith',
6 vote_count: 20,
7 created: 'Sat Oct 6 2012 14:36:58 GMT+0800 (PST)'
8
9 tags: ['databases', 'mongodb', 'indexing'],
10
11 image:
12 {
13 url: 'http://example.com/db.jpg',
14 caption: '',
15 type: 'jpg',
16 size: 75381,
17 data: "Binary"
18 }
19 }
42. . _id
每個 Document ㆒定會㈲ _id 欄位
_id 欄位的值在整個 Collection ㆗必須唯㆒
_id 欄位的值可以是任意型別,不過預設是
ObjectId 型別
43. . ObjectId
㆒種 Lightweight 的 ID 產生方式,長度是
12 Bytes
0-3 Byte 是 Timestamp,以秒為單位
4-6 Byte 是 Machine ID,通常是機器㈴稱
的 Hash
7-8 Byte 是 Process ID,用來保證同㆒台
機器、不同 Process、同㆒秒產生的 ObjectId
還是不同
9-11 Byte 是 Increment,保證同㆒台機
器、同㆒個 Process、同㆒秒之內,可以產
生 2563 個不同的 ObjectId
因為 Timestamp 在最前面,所以 ObjectId 大致
㆖會以插入的順序排列
44. . RDBMS vs. MongoDB
RDBMS MongoDB
Database Database
Table Collection
Record/Row Document
Column Field
Primary Key _id
45. . MongoDB 的㈵點
還是㈲熟悉的 RDBMS 觀念存在
㆒個 MongoDB 的 Instance 可以 Host 多個
Database
每個 Database 可以㈲多個 Collection,就
像 RDBMS 的 Table ㆒樣
每個 Collection 可以㈲多個 Document,就
像 RDBMS 的 Record/Row ㆒樣
每個 Document 可以㈲多個 Field,就像
RDBMS 的 Column ㆒樣
每個 Document 可以㈲完全不㆒樣的
Field,不過㆒般來說,大多數的 Document
會㈲很大的㆒致性
46. . MongoDB 與 RDBMS 的不同之處
RDBMS 的 Column 在 Table 定義,所以每
㆒個 Table 都要㈲相同的 Column
MongoDB 的 Collection 是 Schemaless,
Field 在 Document 才定義,所以每㆒個
Document 可以㈲不同的 Field,也沒㈲
alter table 這種指令
每個 Document 都㈲㆒個 _id Field,可以由
使用者指定,也可以由 MongoDB ㉂動產生
MongoDB 大量使用 JSON 格式作為㈾料表
現方式 (實際㆖是 BSON)
Array 是 First-Class Object
㆒般來說,Collection 的數目會比 Table 的
數目來的少
47. Real-World Deployment
. http://www.mongodb.org/display/DOCS/Production+Deployments
Craigslist:本來用 MySQL 處理幾㈩億筆分
類廣告㈾料,後來改用 MongoDB,讓他們
可以很方便㆞修改 Schema,並且提供很好
的 Scalability
Foursquare:用 MongoDB 儲存各個景點的
㆞理位址,以及與使用者之間的互動
CERN:Large Hadron Collider 實驗用
MongoDB 來作 Aggregation Cache
Business Insider:2008 年開始用
MongoDB,每㆝大約㈲ 1 Million Unique
Page View
48. . 安裝、設定與執行
解壓縮 mongodb-win32-i386-2.2.2.zip 到 C:javaeeNoSQL 目錄
在 C:javaeeNoSQL 目錄㆘建立 mongodb-data 目錄,裡
面再建立 db 與 log 兩個子目錄
在 mongodb-data 目錄㆘新增 mongodb.config 檔案
啟動 mongod Daemon,也可以安裝成 Service
Web 管理介面:http://localhost:28017
dbpath=C:javaeeNoSQLmongodb-datadb
logpath=C:javaeeNoSQLmongodb-datalogmongodb.log
port=27017
rest=true
cd C:javaeeNoSQLmongodbbin
mongod --config c:javaeeNoSQLmongodb-datamongodb.config
cd C:javaeeNoSQLmongodbbin
mongod --config c:javaeeNoSQLmongodb-datamongodb.config --install
net start MongoDB
49. . JavaScript Shell
Shell:
MongoDB 的 Client 端:mongo
透過 JavaScript 與㆒組簡單的 API 互動
Shell Command:
help 與 exit
show dbs 與 show collections
use databaseName
新增:db.collectionName.insert(...)
刪除:db.collectionName.remove(...)
查詢:db.collectionName.find(...)
修改:db.collectionName.update(...)
50. . Simple JavaScript Interaction
> use bookstore
> db.publishers.insert({pubId: "OA", pubName: "O'Reilly & Associates"})
> db.publishers.insert({pubId: "PH", pubName: "Prentice Hall PTR"})
> db.publishers.find()
> db.publishers.remove()
> db.publishers.insert({_id: "PH", pubName: "Prentice Hall PTR"})
> db.publishers.insert({_id: "OA", pubName: "O'Reilly & Associates"})
> db.books.insert({_id: 1, isbn: "0131002872", title: "Thinking in Java",
releaseDate: "2002-12-01", listPrice: 54.99, pubId: "PH"})
> db.books.insert({_id: 2, isbn: "059600530X", title: "Enterprise JavaBeans",
releaseDate: "2004-06-02", listPrice: 44.95, pubId: "OA"})
> db.books.insert({_id: 3, isbn: "0596005717", title: "Head First EJB",
releaseDate: "2003-10-03", listPrice: 44.95, pubId: "OA"})
> db.books.insert({_id: 4, isbn: "0596004656", title: "Head First Java",
releaseDate: "2003-05-04", listPrice: 39.95, pubId: "OA"})
> db.books.find({pubId: "OA"})
> db.books.find({listPrice: {$gte: 50}})
> db.books.find({pubId: "OA", title: /.*Java.*/g})
> db.books.find({$or: [{pubId: "OA"}, {pubId: "PH"}]})
> db.books.find({pubId: "OA"}, {title:1, listPrice: 1, _id: 0})
51. Complex JavaScript Program
. http://media.mongodb.org/zips.json
1 mongoimport --db starbooks --collection zips --type json zips.json
2 mongo
3 > db.zips.ensureIndex({loc: "2d"})
4 > db.zips.find({zip: "90210"})
5 { "_id" : ObjectId("4fab0b8997b64f511d4590eb"),
6 "city" : "BEVERLY HILLS",
7 "zip" : "90210",
8 "loc" : { "y" : 34.090107, "x" : -118.406477 },
9 "pop" : 20700,
10 "state" : "CA" }
11 > db.zips.find({loc: {$near: {50, 30}, $maxDistance: 1}})
1 var obj = db.runCommand({geoNear: "zips", near: [34.090107, -118.406477]});
2 var results = obj.results;
3 var city = {};
4 var dis = 0;
5 for (var i = 0 ; i < results.length ; i++) {
6 city = results[i].obj;
7 dis = results[i].dis;
8 print("City = " + city.city + " Distance = " + dis);
9 }
53. .
1 Big Data
.
2 NoSQL
.
3 MongoDB
.
4 MongoDB Java Driver
.
5 Summary
54. Java Driver
. https://github.com/mongodb/mongo-java-driver/downloads
MongoDB 的 Language Support,稱為 Driver:
主要的 Language mongodb.org 都㈲支援
㈲㆒些 Language 則是由 Community 支援
Interface 盡量㈲相同的 Method
Data Structure 盡量結合 Language ㈵性
Java Driver:
最新是 2012 年 12 ㈪出的 2.10.1 版
比較出㈴的 Java Wrapper
Morphia for Java
Spring Data MongoDB
55. Object/Document Mapping 方式
. http://media.mongodb.org/zips.json
1 {
2 "city" : "BEVERLY HILLS",
3 "loc" : [ -118.406477, 34.090107 ],
4 "pop" : 20700,
5 "state" : "CA",
6 "_id" : "90210"
7 }
1 public class City implements Serializable {
2 private String city;
3 private double[] loc;
4 private int pop;
5 private String state;
6 private String id;
7 }
1 public class Location implements Serializable {
2 private double longitude;
3 private double latitude;
4 }
56. . MongoDB Java Driver 連線建立方式
1 public class MongoDBUtils {
2 private static Mongo mongo = null;
3
4 static {
5 try {
6 mongo = new Mongo("localhost", 27017);
7 }
8 catch (UnknownHostException ex) {
9 System.out.println(ex.getMessage());
10 }
11 }
12
13 public static DB getDB(String dbName) {
14 return mongo.getDB(dbName);
15 }
16
17 public static DBCollection getCollection(String dbName, String colName) {
18 return mongo.getDB(dbName).getCollection(colName);
19 }
20 }
57. . MongoDB Java Driver ㈾料存取方式
1 public class CityFinder
2 {
3 public static void main(String[] args)
4 {
5 DBCollection collection =
6 MongoDBUtils.getCollection("cities", "zips");
7
8 BasicDBObject doc = new BasicDBObject();
9 doc.put("_id", "90210");
10 doc = (BasicDBObject) collection.findOne(doc);
11
12 System.out.println(doc);
13
14 Gson gson = new Gson();
15 City city = gson.fromJson(doc.toString(), City.class);
16
17 System.out.println("City = " + city.getCity());
18 System.out.println("Longitude = " + city.getLoc()[0]);
19 System.out.println("Latitude = " + city.getLoc()[1]);
20 }
21 }
58. .
1 Big Data
.
2 NoSQL
.
3 MongoDB
.
4 MongoDB Java Driver
.
5 Summary
59. Hadoop World 2011
. http://www.theregister.co.uk/2011/11/09/hadoop_kernel_distro/
背景㈾料:
Cloudera 主辦 (2012 年改由 O'Reilly 主辦)
1,400 ㆟參加,來㉂ 580 家公司
統計㈾料排除 Facebook、Google、
Yahoo!、eBay 這些規模比較大的公司
60. . Hadoop World 2011
Hadoop Node 數目:
2011:120 (2010 是 66)
40%:10-100
52%:100-1000
Hadoop Data 數量:
2011:㆒共 202 PB (2010 的 3.4 倍)
76:100 TB - 1 PB
74:大於 1 PB
最大㈲ 20 PB
61. InformationWeek 2012/01
. State of Database Technology 報告
760 份回應:
NoSQL
60% 沒聽過或沒興趣
36% 在研究
04% ㈲實務經驗
使用 Off-Premises 或 Cloud-Hosted Service
做為主要的 Transactional Database
55% 沒㈲計畫
29% 在研究
12% 目前在使用
(5% Pilot,5% ㉂行管理,2% Cloud 管理)
62. . NoSQL 的問題
暫時還沒辦法被 IT 相關㆟員普遍接受
很多㆟認為 NoSQL:Do very little, but their
newness limit your options.
NoSQL 相關廠商正在努力加緊腳步發展
最大的風險是因為都還在不斷開發㆗,版本
成熟度並不是很高,升級時常常會帶來許多
不相容的風險與困擾
63. . MongoDB 的問題
很簡單、很直覺、很快
Schemaless 似乎很棒,不過大多數情況
㆘,我們處理的都是 Highly Structured Data
其實比較重要的改變是 Paradigm Shift,因
為儲存㈾料就變成是把 Domain Object 轉成
JSON 字串,然後㊢入 MongoDB
很㊜合用在 Logging,因為 Write Operation
很快
未來可能會加入 Full-Text Search 的支援,
不過這方面其實應該改用 Lucene 或 Solr 會
比較㊜合
目前工具支援這㆒塊還是比較弱㆒點
64. ㆟腦的記憶容量 - 2.5 PB
. http://www.scientificamerican.com/article.cfm?id=what-is-the-memory-capacity