#garagekidztweetz

id:garage-kid@76whizkidz のライフログ・ブログ!

Mongo Tokyo でとってきたメモ #mongotokyo

スポンサーリンク

昨日、Mongo Tokyo に参加してまいりましたので、私のとっていたメモを share したいと思います。
# のちほど、所感の追記等もします。

About MongoDB from 10gen members.

  • 13:00-13:45 Welcome to Mongo Tokyo and Introduction to MongoDB : Roger Bodamer (@rogerb) SVP, Products & Engineering, 10gen
  • 13:45-14:30 Replication and Sharding : Alvin RichardsSenior Director of Service & Enterprise Engineering, 10gen
  • 14:30-15:15 Schema Design : Roger Bodamer SVP, Products & Engineering 10gen

Introduction of MongoDB

Roger Bodame
  • roger@10Gen.com
  • twitter: @rogerb
  • 元Oracle
What is MongoDB?
  • MongoDB adoptions is very strong.
  • 120,000 database downloads per month.
  • Europe, Japan, China.
  • Growing very very fast.
  • Ruby support.
Over 1,000 production deployments
  • new york times
  • foursquare
  • net price search engine
  • bitly
Its Birth Background
  • RDBMS
    • MySQL, Oracle
  • New Gen.
    • OLAP
      • vertica, aster. greenplum, infobright
  • Non-relational Operational Stores
    • NoSQL
      • Hadoop, CouchDB, MongoDB
The database world is changing.
  • Suit to RDBMS
    • Transaction model
    • More transaction
    • Online processing
    • SQL
  • Suit to NoSQL
    • Less transaction
    • Horizontally scalable
    • Ease of development
    • Predominantly Open-source
  • y軸、scalability performance, x軸、depth of functionality
    • KVS と rdbms の中間に位置する
    • performance では memcached を押している
MongoDB
  • Ver1.6, 1.8
  • Platform and language support
  • C++
  • platform 32/64 bit
  • windows linux mac freeBSD solaris
  • language Drivers
  • Ruby / Ruby on Rails
  • Java
  • C#
  • Javascript
  • C/C++
  • Erlang
  • Python
  • Perl
  • others
NoSQL really means
  • non-relational, next-generation
  • no joins + no complex transaction = Horizontally Scalable Architecture
  • no joins + no complex transaction = Free schema
News data models
  • Improved ways to develop
Teminology
RDBMS MongoDB
table collectin
Rows Json document
index index
Join embedding & linking
partition shard
partitioning key shard key
mongoDB design session
  • サンプルスキーマを用いた実装概要の説明
  • ドキュメントをみながら確認するといいだろう。
  • example of Blog post document
    • _id is unique, but can be anything you'd like.
  • Secondary index
    • create index on any field in document.
    • // 1 means ascending, -1 means descending.
    • internally mongodb contains index in B-tree.
  • query operators
    • // find posts with any tags.
    • >db.posts.find({tags;}$exists;true}})
    • //posts where auther starts with r
    • >db.posts.find({author:^r/})
  • Extending the Schema.
    • example of Adding Comments to Blog schema.
    • document can change dynamically.
  • Secondary Index
    • // you also can create index on nested documents.
Deploying MongoDB
  • Image of MongoDB Replica set.
 
 read/write <-----------> Primary
                          | Replication (similar to mysql)
                          Secondary
       read <------------ | Replication
                          Secondary for backup
 
    • Replicaset.
      • very useful
      • Enable HA, automatically failover.
  • Read scalability ; Replication
    • x 軸 read, y 軸 write
    • ワンセットだと read だけスケールするが sharding することで write もスケールする
  • MongoDB monitoring
    • Zabbix , Nagios
    • Munin they recommended

Schema Design

  • overview for introduction
  • how to extended
  • how to deploy
  • Dynamic schema, free schema
  • need to forget RDBMS schema designing.
  • there are also pros. and cons. exist.
A brief of history of datamodeling
  • ISAM, COBOL
  • Network
  • hierarchical
  • Relational
  • Object
so why model data
  • modeling goal
  • avoid anomalies when inserting , updating or deleting
  • mininize redesign when extending the schema
  • make the model informative to users
  • avoid bias towards a particular style of query
  • source wikipedia
MySQL から移行を考えた理由
  • rewrite the data is one of the problem of RDBMS.
RDBMS detamodeling sample
  • sample of document databases make normalized data look like this.
Recap
  • Query operators
  • references you can see.
  • extending schema
Advanced schema design
  • common patterns
    • single table inheritance
    • one-to-many & many-to-many
    • trees
    • queues
One - Many
  • embedded array / array keys
    • slice operator to return subset of array
    • some queries harder
    • e.g. find latest comments accross all documents
  • embedded tree
    • single document
    • natural
    • hard to query
  • Normalized (2 collections)
    • most flexible
    • more queries
Many - Many
  • Example:
    • product can be in many categories
    • category can have many products
Trees
  • Full trees in documents
    • Pros: single document, performance, intuitive
    • Cons: Hard to search , Partial results, 4MB limit (16MB in 1.8)
Parent Links
  • Each nodes is stored as a document
  • Contains the id of the parent
    • Child Links
  • xxxxxxxxxx // 書き取れず
Array of Ancestors
  • Store all Ancestors of a node
Trees as Paths
  • Store hierarchy as a path expression
    • Separate each node by a delimimter, e.g. "/"
Queues
  • Needs to maintain order and state
  • Ensure that updates to the queue are atomic
    • // find highest priority job and mark as in-progress
Summary
  • Schema design is dirrent in MongoDB
  • Basic data design principals stay the same
  • Focus on how the apps manupulates data
  • Rapidly evolve schema to meet your requirement
  • Enjoy your new freedom, use it wisely :-)
  • MongoDB makes building application easy and some attractive features like....
    • Map/Reduce
    • Capped Collections
    • Tail-able Cursors
    • Geo Indexing, and much more!

Scaling

What Scaling?
  • Vertical Scaling
  • horizontal Scaling
  • operations/sec go up
  • storage needs go up
    • capacity
    • IOPs
  • complexity goes up
    • caching
How do you scale
  • Optimizaon & tuning
    • Schema and index design
    • OS tuning
    • HW configuration
  • Vertical scaling
    • HW is expensive
    • Hard to scale in cloud
MongoDB Scaling
  • single node
  • adding replica
  • sharding
    • add shards
Scaling with MongoDB
  • Schema
    • Data model effects performance
      • Embedding versus linking
      • Roundrips to database
      • Disk seek time
      • size if data to read and write
      • Partial versus full document write
  • Performance problems can be solved by changing schema.
Indexes
  • index common queries
  • Do not over index
    • (A) and (A,B) are equivalent , choose one.
  • Right-balanced indexes keep working set small.
Random Index Access
  • Entire index in ram
  • Right-balanced index Access
  • Small portion in ram
  • // image
What is scaling
  • Ad-hoc partitioning
  • Consistent hashing
    • Amazon Dynamo
  • Range based partitioning
    • you choose the key.
  • Google BigTable
  • Y! PNUTS
  • MongoDB
MongoDB Sharding
  • Automatic partitioning and management
  • Range based
  • Convert to sharded system with no downtime
  • Almost no functionality lost over single master
  • Fully consistent
How MongoDB Sharding works

db.runCommand ( { addshard : "shard1" } )
db.runCommand ( { addshard : "shard2" } )
db.runCommand ( { addshard : "shard3" } )

  • Data in inserted
  • Ranges are splits int more "chanks"
    • Adding a shard, data migrated to another suitable shard automatically.
Sharding Key Esamples
  • Good : {server:1}
    • All data for one server is in a single chunk
    • Chunk cannot split any smaller
  • Better : {server:1,time:1}
    • Chunk canbe split by millisecond
  • Good {time:1}
    • TIme is an increasing number
    • All data will be first written to a single shard
    • Data balanced to other shards later
  • Better: {server:1, application:1}
    • xxxxx
Sharding Feature
  • Shard data without no downtime
  • Automatic balancing as data is written
  • Commands routed (switched) to correct node
    • Inserts - must have the shard key
    • Updates - must have the shard key
  • Queries
    • with shard key - routed to nodes
    • without shard key - scatter gather
  • Indexed Queries
    • with shard key - routed in order
    • without shard key - distributed sort merge
MongoDB Replication
  • MongoDB replication like MySQL replication
    • Asynchronous master/slave
  • Variations:
    • Master/Slave
    • Replica Sets
Replica set features
  • A cluster of N servers
  • Any (one) node can be primary
  • Consensus election of primary
  • Automatic FO
  • Automatic recovery
  • All writes to primary
  • Reads can be to primary (default) or xxxx
How MongoDB Replication works
  • Basical Replica set.
    • Election establishes the PRIMARY
    • Data replication from PRIMARY to SECONDARY.
 
 member1                            member3
 |                                  |
 +------- member2 (PRIMARY) --------+
 
    • When PRIMARY down,
 
 member1 <- negotiate each other -> member3
 x                                  x
 +------- member2 (DOWN)   ---------+
 
  • Then, New primary elected,
    • Replication set re-established
 
 member1 <------------------------- member3 (PRIMARY)
                                    x
          member2 (DOWN)   ---------+
 
  • After member2 recovered
    • Replication automatically recover
    • Replication Set re established
 
 member1 <------------------------- member3 (PRIMARY)
                                    |
          member2          ---------+
 
Using Replicas
  • salaveok()
    • driver will send read requests to Secondaries
    • driver will always send writtes to Primary
Create a Replica Set
  • Replica set member type
    • Normal {priority:1}
    • Passive {priority:0}
      • Cannot be elected as PRIMARY
    • Arbiters
      • Can vote in an election
      • Dont hold any data
Replication features
  • Reads from Primary are always consistent
  • Reads from Secondaries are eventually consistent
  • Automatic FO if a Primary fails
  • Automatic recovery when a node joins the set
Summary
  • Schema & Index design
    • Simplest way to scale
  • Sharding
    • Automatically scale write
Q&A
1. free document は検索しづらい xpath のサポートは?
2. if need complex transaction, if it needs, is it need to self implement?
  • single document transaction is supported,
3. binary data, 4MB, 16MB limitation.
4. 現状最大の利用事例、構成
  • TB of data customer
  • 10s of nodes
  • using sharding
  • 4 or 3 of nodes of dataset
  • 8 of shard in product
  • not need high spec machine, normal machine.
5. lock issue
  • mongostat?
  • write 競合
6. secondary index performance compared with primary index
  • no diference between the performance primarykey and secondary index.
7. Driver に関する質問?
8. question for Create index timing. what situation prefer.
  • during the development.
  • if the product enviroment in high load,
  • but it going background
  • Ill take longer but it can conduct
9. index performance
10. sharding するときの注意事項を質問
11. collection based sharding don't supported automatically defaults
  • sharding key is now needed.
  • easy script can prepare but now don't.
12. if using sharding authorization feature cannot be used.
  • it will be supported in future release
  • in ver 2.0
  • when it will release?
  • you can see road map in the MongoDB site.

15:30-16:15 You're Happy When You Choose Ruby and MongoDB : Yunna Kurita(@yuunyan_m)

Slide.
  • Not uploaded yet.
Overview.
  • MongoDBとRubyの幸せな関係:
  • RubyからMongoDBを扱う時には、目的に応じて適切なアーティテクチャーの選択をしないといけません。
  • ドライバーの比較からはじめ、
  • RailsとMongoDBの関係、Geo情報の扱い、Hadoop Streamingの利用時などのTipsと、
  • Rubyっぽい「黒魔術」なMongoDBの利用法のお話をします。
自己紹介
Ruby MongoDB Driver
  • Ruby Driver
  • Many OR mapper
Too many OR mapper
  • Need to choose
Mongo Mapper
  • most famous driver for Rails
  • Plugin system
Mongoid
  • もっとも選ばれているのではないか?
  • 日本語エラーがでない
    • つくったとのこと
mongomatic
  • 速い
    • 依存関係が少なくて済む
    • 日本語のドキュメント少ない
MongoODM
  • Ruby mongo Driver is much more proper and richher than the popular AR ORM for Ruby
選ぶためのフローチャートをつくってみた
Benchmark
  • #1 compare with MySQL
    • InnoDB が一番遅い
    • サクラのVPS
    • とにかくデータをつっこむだけならMySQL alternative になりうる
  • #2 compare with driver
    • 圧倒的にPHP が速い
    • Ruby
    • Cネイティブのドライバーは速い
Usecase
Rezept Analyze
  • 診療明細
    • Not good optimized data format.
    • there is no guarantee for its values.
    • occur to think this is suitable for MongoDB, so use MongoDB.
4 step developing
  • Dev#1 approach
    • using mongoid
    • OR mapper を書くのが終わらない
    • Dev#2
    • Dev#3 using with Classid()
      • 自動クラス生成
    • Dev#4 only use Mongo-ruby
      • with using Json nesting
      • ORmapper を使わないほうが扱いやすい
      • Re-constable original data from Json
5. system image.
 
 mongoDB -----------------------------> Map
                                        |
                                        Ruby
                                        |
                                        Hadoop
                                        |
                                        Ruby
                                        |
 Browze <------------ R <------------- Reduce
 
Ruby + Hadoop = patraqushie
  • daambo ruby migration
Future works
  • Geohex Support on Ruby + MongoDB
  • An appreciate architecture brings happy MongoDB life!
Others.
  • セキュリティを高めるためにはデータを残さない
  • ORmapper を使わないといけないこと
    • Agile開発、スキーマを定義しないといけない
    • ジレンマ
    • ORmapper はスキーマごとにクラスをかかないといけない

AR は使わない
native を使用するとRuby のhash になるので同じ所に違うデータがはいってもよいので楽

16:15-17:00 Social Data and Log Analysis Using MongoDB : Takahiro Inoue (@doryokujin)

Overview.
  • 芸者東京エンターテインメント株式会社(GTE)・MongoDB JP主催者
  • ソーシャルデータの解析データサーバーとしてのMongoDBの活用方法をお話しします。
  • アクセスログ・行動ログ・ユーザー属性情報などの各種ログをMognoDBへ集約させる方法、
  • またHadoop,R,JQueryなどの他のツールとの連携のさせ方を具体的にお話しします。
My Job
  • Fledgling Data scientist
  • Big data analysis
    • How to generate logs scattered many servers
Analytic Architecture
Social Game , Omiseyasan
  • Data flow

Accesslog解析

System overview
 
 access log -> apache tomcat -> MySQL user registration
                             -> Cassandra user save data
                             -> Flash compse server
 
  • Back-end Architecture
    • Hadoop 連携
    • Pymongo
    • Dumbo
  • Front-end Architecture
    • MongoDB
    • jquery
    • Neo4j, Gremlin
    • R
  • Environment
    • MongoDB 1.6.4
    • Pymongo 1.9
    • Hadoop, CDH2 soon update to CDH3
    • Cassandra 0.6.11
    • R, Neo4j, jQuery, Munin
    • Data size
      • access log 15GB/day gzip 2000 M PV
      • User Trage log 50 GB/day
How to handle accesslogs
  • MongoDB による 2段階のMR
  • Mongo 1.7.4 or later needed
  • Hadoop を前処理に利用
    • 不要なデータをフィルタリングするようにしている
  • userid ごとで分解
  • MongoDB の MR
    • 1段階目のMR with Pymongo
  • Map reduce operation runs in parralel in each shards
  • 4type of MR output collection (MongoDB>=1.7.4)
    • out
    • marge_output
    • reduce_output
    • full_response
  • 2段階目のMR with Pymongo
  • MongoDB のコマンドを使用してのMR
    • 現状の ver 1.6 の MR は不完全
    • 1 thread でしか動作できない
    • MongoDB MR の使えるリンク集
How to Collaborate with from analytic tools
  • MongoDBに蓄えたデータを以下に効率よく解析するか
    • jQuery.DataTables
      • JSON データを渡すとテーブルデータに変換してくれる
    • Graph: jQuery.Data.HighCharts
      • JSON データを渡すと、チャートを自動生成してくる
    • sleepy.mongoose
      • 10gen engineer developed.
  • MongoDB、簡単なコマンドで統計情報をがとれるのも魅力
Future plans
  • Realtiime Analysis with MongoDB.
  • データの転送がネックになっている
Summary
  • MongoDB is almighty as a analytic data server
  • schema free, social game data are changeable
  • rich queries, important for analyze many point of view
  • powerful aggregation, Map Reduce
  • mongo shell, analyze from mongo shell are speedy and handy
  • Scalability
    • Using replication , Sharding are very easy
    • Node.js
    • Enable us server side scripting with MongoDB

17:00-17:45 MongoDB as a Search Engine Document Repository : Kazuki Ota (@kzk_mover)

Overview
  • 株式会社 Preferred Infrastructure CTO
  • 分散検索エンジン Sedue ではMongoDBをドキュメント保存用のリポジトリに使用しています。
  • MongoDBを選択した背景や理由、採用するに当たって苦労した点、そして大規模化にむけたSharding性能実験等を紹介したいと思います。
製品に MongoDBを組み込んでどううまくいったか?の話。
Introduction of Sedue
  • search engine
  • Enterprise Distributed search engine.
  • Multi-threaded C++ server
Sedue data model
  • need to define schema like RDBMS
  • field definition + index definition
  • index 生成することで検索を高速化→search engine
  • Sedue schema sample
    • XML
    • 転置 index
  • Sedue Query sample
  • Data is mapped to Distributed File System.
Sedue Architecture
  • Crawler <-> Distributed Repository <-> Document Repository Proxy <-> Indexer <-> Distributed File System <-> Searcher <-> Query Server <-> User
    • archive process が全体をマネージする
    • 解析に、DFSは向いている
Problems what we had
  • 現実はあまりにもひどかった
  • schema がしょっちゅう変わってしまう
  • 足してみたカラムに実はデータがはいってこない
  • いろんなメディアからデータをあつめているとあるメディアにはあるがあるメディアにはないカラムなどがある
  • 日経BP社、16メディアほどデータをいれてもらっているが、全然内容が異なる
    • →だが、横断的にデータを検索したいというニーズはある
    • → Sparse になる
  • 一個だけラッキーなことがあった
    • Pluggable Storage Storategy をとっていた
      • →データを格納するストレージを選べるようにしていた。
      • → 当初は、tokyo cabinet と MySQL をサポートはしていた
      • →また当初は、DFS、NFSとHDFSをサポートしていた
      • →ここでMongoDBが選択肢としてでてきた
MongoDB is matched to Sedue
  • API, Replication, Online Schema Change, Sharding
    • As DFS, API=C++ .....
  • MongoDB support GridFS
    • MongoDB as a Blob-storage
      • the contents is splitter int 256kb.
      • performance is not as high as HDFS, but still useful.
Now Sedue loves MongoDB
  • Repository + DFS
  • Easy setup
    • 330 million documents
  • no schema change is required
  • master-master replication
  • backup once a week
  • 4 production deployment
We had issues, but MongoDB is OSS
  • 自分で直せると
    • Patchも採用を迅速に行ってくれる
    • Patchを送るとマグカップが送られてくる
  • SERVER-1408(Fixed)
    • C++ Driver GridFS cannot store over 4GB objects
      • などなど
How MongoDB solve this problem
How we store documents?
  • docid をふる
  • acrid, sharding に使用
  • それ以外は、ドキュメントをそのまま格納している
  • 困っているのは、データの容量が4MBの制限があること
    • pdfなどは4MBを軽く超える
Queryサンプル
  • KV lookup, not complicated queries.
MongoDB Problems
  • Disk usage
    • MongoDB spent much disk.
    • Allocate some GBs , for the replication logs.
    • Mostly append architecture
      • In place modification is supported , if smaller than the original size
    • No compression option
  • Consistency
    • Fire-and-Forget Write Behaivior
      • Normally mongodb insert doesn't ensure the success at the server side.
      • need to call getLastError() to confirm the writes succeed, but it loss performance.
      • in replicated environment you can specify minimum number of servers which succeed xxxxx
  • Sharding
    • Scaling without no application modification.
    • Benchmark
      • last summer
      • Testing with 2 nodes
      • they think it is trust worthy.
      • 150 doc register/sec
Conclusion
  • Sedue is distributed index query Engine
    • headache about frequent changing schema
  • Sedue loves mongodb
    • as documentrepository + blob storage
    • mongodb handles read data well
Other Sentiments.
  • 人的ミスはこわい
  • レプリケーション時に原因不明の高負荷
  • このスピード感で開発しているのに、高いクオリティ。
    • 期待は大きい。
  • MySQL との benchmark 比較
  • safe mode はdefault はOff
    • その状態でMySQLと比較するのは Fair じゃないと。
  • Backup上の注意
    • mongodump を使ってる
    • slave backup を使うのも一手
    • replication のためのlogを格納する領域に十分のサイズが必要。→MySQLも同様。

18:00-18:45 Kiosk: The Schema Layer for MongoDB and PHP - Schema is Not Your Enemy : Basuke (@basuke)

Slide

Not uploaded yet.

Overview
  • 関心空間CTO MongoDBの手軽さにRDBの確実性をプラス!
  • スキーマがないことが魅力のMongoDBですが、実際のコーディングでは、これまでRDBがテーブルとして 提供していた枠組みがなくなるデメリットも出てきます。
  • PHPのような型の概念の薄い言語ではなおさらです。
  • PHP用のKioskライブラリは、オブジェクトと Mongoの間のゆるいスキーマレイヤーを作ることを目的としています。
  • Front からの MongoDB の使い方の一例
Schema is not your enemy.
  • それ(スキーマ)をどうスキーマレスのMongoDBに適用できるか?
自己紹介
Kioskとは
  • php用のデータアクセスライブラリ
  • Active Record型のデータレイヤー
  • Mongodb にスキーマを提供
  • OSS、Gethabで公開
MongoDBの実績
  • #1 ランブリン
    • 当初、TokyoTylant
    • データの保守性改善のために移行先を検討
    • そんなにうまくMongoDBを活用できてない
  • #2
    • AsssistOn
    • 原宿のセレクトショップの通販サイト
    • PostgreSQLからの移行を計画
    • 量より柔軟性のために
    • ただ、頓挫
MongoDBのよいところ悪いところ
  • スキーマレスは利点であり、欠点でもある
    • ドキュメント以外では、コードがすべて
    • ゆるいPHPと自由なMongoDBの相性
    • よくもあり適当でもあり。自由x自由で収集がつかなくなることがある。
    • ドキュメント=辞書型
    • アプリによってはオブジェクトのほうが使いやすい
  • スキーマの構造の把握が難しいのが欠点
    • Running Code is the only clue
PHP は型にルーズすぎる
  • MongoDBは多少、型にうるさい
  • 型が違うと探してくれない
  • 文字列と数字
  • $doc = $_POST
    • →すべてのコードは文字列になってしまう
ドキュメントベースゆえのつらさ
  • 属性名を短くする工夫
  • 空間効率はあがるが、プログラマは大変
Kioskの特徴
  • ドキュメントをPHPのオブジェクトにマッピング
  • コレクションとエンティティ
  • MongoDBにスキーマを提供
  • コード中に構造のヒントを記載することができる
  • 型の強制
  • 名前の変換
  • CakePHP的なConditionの記述
  • →括弧が減る
  • コモン・パターンのサポート
  • テスト駆動での開発
  • OSS、GitHubで公開
ActiveRecordの定義
  • 得られた値をオブジェクトとして使いたい
  • 集合体に対して検索、生成が行える
  • オブジェクト=レコードが自立的に保存、削除などできないといけない
  • 単なるデータ構造だとMVCのVとCに負担をかけすぎる
コレクションとエンティティ
  • Mongoではエンティティをドキュメントとよぶ
  • エンティティの集合体をコレクションとよぶ
  • 設定
    • コレクションとクラスをbind する必要がある
    • PHP は他の言語に比べてクラス定義に自由度がない
      • →Rubyのようなマクロは書けない
      • 一つのクラスに一つのデータレイヤーとは限らない
      • →管理アプリではフル完備のUserクラス、
  • 公開アプリでは簡易Userクラス
PHPでは超えられない壁の話
CRUD
  • User::create()
  • User::import()
  • ...
実例、Sourceコード
  • オブジェクトに対するUpdateができるようにする
    • →アトミックな処理
  • スキーマ定義にないカラムの扱いやすい
  • Many to Many
Migration
  • 新規案件はいいが、既存のRDBからの移行をどうするか
  • Kioskは実はRDB用のORM
    • データベースソースの定義以外は比較的同じ記述で制限が操作
    • マルチデータソース、RDB+Mongo
    • レガシーな環境をサポートしつつ、MongoDBまでもっていける柔軟性をめざす
PHP4でもうごくが、PHP4ははやくやめたい。

18:45-19:30 Node.js and MongoDB / Suguru Namura (@snamura)

Overview.
  • 株式会社 サイバーエージェント アメーバピグで作っているPC向けソーシャルゲームを
  • node.js + mongoDB で作っているので、
  • node.js + mongoDB のメリットと開発経験談、
  • 工夫したポイントなどをお話しします。
  • アメーバピコ、米アメーバでの実例
  • アプリケーションよりの具体的な話
自己紹介
  • サイバーエージェント、7年生
  • ゲームよりのコンテンツ
つくろうとしているもの
  • pc向けのソーシャルゲーム
  • アメーバピグのプラットフォーム上で動作
  • 農園っぽいもの
使おうとしている技術
  • MongoDB 1.8.x
  • node.js 0.4.x
  • WebSocket Draft76
  • Flash Player 10.x -> client
  • 独自のバイナリプロトコルを使っている
なぜMongoDBか
  • スキーマレス
    • 柔軟なIndex
    • Sharding & replica set
  • node.js
    • Java + mongo に絶望した
    • DBOject 接続プール、静的な形付
    • →MongoDBのよさを殺している
    • Python+twistedを拒否された
    • 流行
    • 言語仕様が既にシングルスレッド
システム構成
  • ※レプリカセットの最低構成台数は3というマニュアルに従った
  • →3つ並べたのはなんとなく。
 
 client FLASH
 |
 LB // HTTP Websocket
 |
 node.js x 3 <- SVN or git
 |
 3x3 shaded MongoDB
 
MongoDB+node.js
  • 相性がいい
  • シームレス
  • JSONがそのまま使える
  • 検索クエリ・保存データ、すべてJSON
  • プログラムにデータがシームレスに統合される
  • ORMapperが必要ない
  • MongoDBのコンソールと近いコードで書ける
node.js Driver
  • node-mongodb
    • 公式のCドライバーのラッパーだが、bulk insert not supported
  • node-mongodb-native
    • javascript で書かれたドライバ
    • BSON部分だけネイティブにも対応
    • npm install mongodb でインストールされるのはこちら
node.js の特徴
  • 原則すべて非同期処理
  • なにをするにもコールバックでうけとる
  • dbアクセスも全部コールバック
  • コールバックすべてにエラーハンドリングが必要
  • ネストが大変深くなる
    • →コールバックの例のコードがすごいことになっていた
    • →工夫
    • →DBアクセスのシリアルな処理を記述するためのライブラリ、メソッドチェーン
    • →さらに、コード例
その他の解決
  • Mongoose
    • node-mongo-native と併用
    • シリアルな実行をサポート
    • スキーマ定義をサポート
    • →使わなかったのは、自分が作りたかったから
運用管理ツール
  • アメーバピグのリアルタイムレポート、リアルタイム販売データを表示
    • node.js を使ったことによるメリット。
    • 最先端技術は管理ツールのほうが導入しやすい。
    • よいツールは運用チームのテンションをあげる
管理ツールにおけるMongoDBの利点
  • スキーマがなく階層構造をとれるため、汎用的なデータをそのまま使用できる
  • データ定義をそのままフォーム仕様に。
    • →ピグライフ管理コンソール
結論
  • 仕様やデータの構造が複雑なソーシャルゲームとMongoDBの相性はよい
  • node.js とMongoDBは良い組み合わせ
    • →どちらも新しいプロダクトなので、どちらも問題が起こる懸念はある。
  • テストコードが超大事 nodeunit
    • →非同期処理のテストユーティリティ
  • 厳格なシステムには、この組み合わせは向かない
  • node.js , MongoDB に対する proxy および validation 用途でも使っている
MySQL との比較

以下の 3 点でメリットを感じるとのこと。

  • 非同期
  • scalability, replica set and Sharding
  • bulk insert
Shard の偏りを手で直す
  • マニュアルに記載ありとのこと
  • Collectionの偏り
  • move chunk

References.

Books.

MongoDB: The Definitive Guide

MongoDB: The Definitive Guide

Scaling MongoDB

Scaling MongoDB

Document Design for Mongodb

Document Design for Mongodb