48

Developing with Couchbase_Document_your_world_tokyo_2014

Embed Size (px)

Citation preview

Developing with Couchbase: Document Your World

Matt IngenthronDirector, Developer Solutions

What to Expect:

• JSON Basics

• JSON Documents within Couchbase itself

• Mind-set Changes between Relational and Non-Relational Modeling

• Building an application around JSON

• Document Structuring / Modeling our data effectively

• Views and Indexes within Couchbase

• An introduction to Map / Reduce

JSONの基本について

Couchbase Serverの中の JSONドキュメント

RDBMSから Non-RDBMSへマインドセットを変える

JSONを使ったアプリケーションの構築

効果的なドキュメントの構造/モデリング

Couchbase Serverの View(ビュー)とインデックス

Couchbase ServerのMap/Reduceの紹介

JSON Basics – what is JSON?

Java Script Object Notation

• Created by Douglas Crockford

• Text Based Format

• Designed for Human-readabledata interchange

Douglas Crockford氏によって開発された

テキストベースのフォーマット

データの中身を容易に読み取ることができるように設計された

JSONの基礎

JSON Basics – Why JSON?JSON has a lot of advantages:

• It's compact

• It's easy for both computers and people to read and write

• It maps very easily onto the data structures used by most programming languages (numbers, strings, booleans, nulls, arrays and associative arrays)

• Nearly all programming languages contain functions or libraries that can read and write JSON structures

コンパクトな構造

機械と人間の双方にとって読込みと書込みが簡単

ほとんどの言語に対応し、データ構築が容易

ほとんどの全てのプログラミング言語が JSON構造の読取り/書込みライブラリまたは(ビルトインの)機能を有する

JSONには多くの利点が存在

Supported JSON Types:

String:

Numbers: – (Int. & Floating Point)

"A String"

Boolean:

{“value” : false}

Object:

{ ”name" : “Robin Johnson” “twitter" : “@rbin", ”age" : 22, "title" : ”Developer Advocate"}

22 & 55.2

JSONでサポートされるデータタイプ

Supported JSON Types - Lists:

Array:

["one", "two", "three"]foos : [ { ”bar1":"value1", ”bar2":"value2" }, { ”bar3":"value3", ”bar4":"value4" }]

List of Objects:

Complex, Nested Objects:

{ tweet, tweet… }

JSONでサポートされるデータタイプ(リスト関連)

JSON Documents within Couchbase

• Couchbase is primarily a JSON-oriented Document Data Store.

• Each document is stored with a Unique Identifier (Key) and is made up of key-value pairs.

• Couchbase uses these JSON values to build indexes, query data and perform advanced lookups.

Couchbase stores the ‘Meta’ of each Document, and the Body (Content)…

Couchbase Serverは JSONを主要格納形式としたドキュメント型データベース

各ドキュメントは Keyと呼ばれるユニークな識別子によって管理され、対となる Valueでデータが構成される

Couchbaseは格納された JSONデータを使ってインデックスとクエリを構築し、データ検索 (lookup)を高速化する

ドキュメント毎にメタデータ(とコンテンツ)を格納する

Couchbaseにおける JSONドキュメント

meta{“id”: “[email protected]”,“rev”: “1-0002bce0000000000”,“flags”: 0,“expiration”: 0,“type”: “json”}

document{“uid”: 1234,“firstname”: “Robin”,“lastname”: “Johnson”,“age”: 22,“favorite_colors”: [“green”, “red”],“email”: “[email protected]”}

Meta Information Including Key (ID)

All Keys Unique and Kept in RAM at all times.

Document Value

Most Recent In Ram And Persisted To Disk

JSON Document Structure

メタ情報 (含む Key)について

全ての Keyはユニークな値となり、全てのアイテムが RAMに保持される

ドキュメントの Valueについて

最新データはメモリに書き込まれ、後にディスクに永続化される

JSONドキュメント構造

User Object

string uid

string firstname

string lastname

int age

array favorite_colors

string email

u::[email protected]{“uid”: 1234,“firstname”: “Robin”,“lastname”: “Johnson”,“age”: 22,“favorite_colors”: [“green”, “red”],“email”: “[email protected]”}

User Objectstring uid

string firstname

string lastname

int age

array favorite_colors

string email

set()

get()

Objects Serialized to JSON and Back

u::[email protected]{“uid”: 1234,“firstname”: “Robin”,“lastname”: “Johnson”,“age”: 22,“favorite_colors”: [“green”, “red”],“email”: “[email protected]”}

オブジェクトは JSONにシリアライズされ、かつ戻される

The Mind-Set Change

•All of our data is in tables,•We split complex data across multiple

tables,•We have a very rigid, inflexible schema, and•All of our data records are forced to look the

same.•We use complex JOINS, WHERE Clauses and

ORDER BY Clauses

The Move from Relational Modeling

Our ‘Recipe’ table uses “JOINS” to aggregate info from other Tables.

リレーショナルデータベース( RDBMS)全てのデータがテーブルで格納されている

複雑なデータを分割し、複数のテーブルに配置する

堅牢なスキーマ

全てのデータが統一的に管理されなければならない

非常に複雑データ設計を必要とする

The Move to NoSQL•In Couchbase, we’re going to model our Documents in JSON.

•Contrary to Relational DBs, we can hit the database as much as we like as Gets and Sets are so quick, they’re trivial.

•We can make changes to our Data structures at any time, without having to use ALTER_TABLE statements allowing for agile model development.

•There is no implied schema, so each record in our DB could look entirely different to the last.

•Getting our heads around modeling data in JSON can be tricky. Let’s look at how we can get started in JSON Modeling:

Couchbaseでは、 JSONでドキュメントのモデリングを行う

RDBMSと異なり、データベースへのアクセスを高速かつ何度でも行うことができる

代替のテーブルなどを必要とせずにデータ構造をいつでも変更することができる

スキーマを必要とせず、各レコード(データ)は異なる構造を持つことができる

それでは実際に JSON形式のデータモデリングを行う

Modeling an Application…The JSON way

Social Application in which people can vote on other User’s Vine videos and see a Global Ranking of the Best and Worst Vine Videos!

Rate My Vine…

Top Rated Vines

Cooking w/ Hugh Fearnley-Whittingstall

I love doing Housework

What happened to Amanda Bynes

Random Access Memories

I don’t even know

Twerking gone wrong

Too cold to Dance

How To Scare Your Friends

176

143

120

112

107

98

74

37

Twitterのモバイルアプリ「 Vine」で格付け

Twitterのモバイルアプリ「 Vine 」では、他のユーザのビデオクリップに投票し、世界ランキングで“ Best”と“Worst”の順位を見ることが出来る

•This is an actual Sample App for Couchbase, fully Open Source

•Built on Ruby, Rails & Couchbase

•Using the Couchbase-Model Ruby Gem for Active-Record style (easy) data modeling

•Puma as web server for concurrent connections

Technology Used:使用技術

このアプリは Couchbase社のサンプルアプリで、オープンソースで構築されている

Ruby, Rails, Couchbaseで構成

Couchbase-Model Ruby Gemをアクティブデータのモデリングに使用

並列処理のコネクションにWebサーバの Pumaを使用

•Users must Auth with Twitter before Submitting Vines

•We simply register their Name, Twitter Username & Avatar upon T-auth

User.rbユーザはまず Twitterにログインし、ビデオクリップを共有する

Vineランキングのビデオタイトル、ユーザアカウント名などの情報を登録する

•Standard JSON structure with simple String fields

•This JSON is editable within the Couchbase Console

How that looks as JSON in Couchbase:

Key created by a hash of Twitter UID

Explicit ‘type’ of Document

Couchbase Serverでは JSONはどのように見えるか?

シンプルな文字列(一般的な JSONの構造)

Couchbaseコンソール上で編集が可能

•Vine has no public API, so we’ve written a simple script to Rip the true URI of the video, from the entered URL by the user

•Vines need a Name, A Video URL, a User and a Score

Vine.rb

ユーザはまず Twitterにログインし、ビデオクリップを共有する

Vineではビデオ名、 Vineの URL、ビデオの URL、スコアが必要

•Marketing have informed us that we need to add a new field for Facebook Sharing into our Vine Videos!

•In a relational world, we would have problems!

•In the Couchbase world, IT’S TRIVIAL!

The Joys of a Flexible Schema!

Vineのビデオに Facebook共有のフィールドを追加

RDBMSではこのような柔軟な対応はできない

Couchbaseを使えばあっという間!

•User_ID included so we know who each Vine belongs to

•Score is inside each Vine document. This brings it’s own challenges, but Couchbase solves them!

Again, the JSON within Couchbase:

Random Hash generated Key

User_ID reference

RDBMSではこのような柔軟な対応はできない

RDBMSではこのような柔軟な対応はできない

•We have chosen to have the Score inside each Vine doc.

•We need to be able to deal with concurrent score updates.

Optimistic Concurrency:

{ “score" : 174}

UPDATE UPDATE

楽観的平行性

我々は、各 Vineドキュメントに、 Scoreを持たせる選択をした

平行処理においてにスコアの更新ができる能力が必要である

•To handle the Concurrent updates, we can utilise Couchbase’ inbuilt CAS value.

•We simply write a new Update method in our application controller to use the CAS value on update.

CAS – Compare and SwapCAS – 比較と差し替え

平行処理の更新を制御するために Couchbaseのビルトインの CAS値が利用可能

CAS値を更新判定に利用することで、アプリケーションコントローラーにシンプルな更新メソッドを定義することができる

•Just as in SQL, our JSON Documents also have various types of ‘Relationship’.

•For example, a User can own many Videos as a 1 to many relationship.

Document Relationships

video:1{ type: “vine”, title: “My Epic Video”, owner: “rbin”}

user:rbin{ type: “user”, name: “Robin Johnson”, id: “rbin”}

Video:2{ type: “vine”, title: “I NEED A HORSE!”, owner: “rbin”}

ドキュメントリレーションシップ

•Marketing have informed us we need to add a Comment mechanism to our Vine Videos.

•We need to decide the best way to approach this in JSON document design.

Single vs. Multiple Documents

{

}

Single Multiple

vs.

Document

Comment

Comment

Comment

単一ドキュメント vs. 複数ドキュメント

マーケティング部門は、コメントメカニズム Vine Videoに追加する必要性を訴えた

我々は、このためのドキュメントデザインを以下のように変更する方が良いと考えた

•Comments are nested within their respective Vine documents.

•Great when we know we have a finite amount of Results.

Single vs. Multiple - Single

{

"type": "vine",

"user_id": "145237874",

"title": "I NEED A HORSE",

"vine_url": "https://vine.co/v/b2jjzY0Wqg5",

"video_url": "https://mtc.cdn.vine.co……,

"score": 247,

"comments": [

{"format": "markdown", "body": "I LOVE this video!"},

{"format": "markdown", "body": "BEST video I have ever seen!"},

]

}

7b18b847292338bc29

単一ドキュメントで設計した場合

各コメントはネストされる

コメント数の上限が設定されていることを知っているならばこの方法は問題ない

•Comments are split from the parent document.

•Comments use referential ID’s, incremented by 1

Single vs. Multiple - Multiple

{

"type": "vine",

"user_id": "145237874",

"title": "I NEED A HORSE",

"score": 247,

}

7b18b847292338bc29 { "format": "markdown", "body": "I LOVE this video!”}

7b18b847292338bc29::1

{ "format": "markdown", "body": “BEST video ever!”}

7b18b847292338bc29::2

複数ドキュメントで設計した場合

コメントを、親ドキュメントから分離する

増分数1の参照用IDを使ってコメントを格納する

•Couchbase has no inbuilt mechanism for Versioning.

•There are many ways to approach document Versioning.­Copy the versions of the document into new documents,­Copy the versions of the document into a list of nested documents,­Store the list of mutated / modified attributes:

• In nested Element,

• In separate Documents.

•In this case, we’re going to look at the simplest way…

Versioning our Documents:

•Get the current version of the document,

•Increment the version number,

•Create the version with the new key "mykey::v1”,

•Save the document in it’s current version.

Versioning our Documents:

Current Version:

Version 1:

Version 2:

mykey

mykey::v1

mykey::v2

ドキュメントのバージョン管理

ドキュメントのカレントバージョンを取得

バージョン番号を増分する

新しいキーを” mykey::v1”としてバージョンを生成する

新しいカレントバージョンのドキュメントを格納する

Questions so far?

Views & Indexing in Couchbase

•What’s a View?­A view within Couchbase takes in Unstructured / Semi-Structured data

and uses that data to build an Index…

•So what’s an Index?­An index is just an optimised way of finding data. (In list format or

other)

Terminology:技術用語

Viewとは?

Indexとは?

Couchbaseにおける Viewとは、非構造 / 半構造データを取得し、このデータを Indexを生成するために使用するものである。

Indexとは、データを見つけるための最適化された手段の1つに過ぎない(リスト形式あるいはその他の形式で)

•Ingesting Tweets from the Twitter API

•Taking in data from the LinkedIn API

•Taking Git Commit data etc.

There is little point in trying to sort the data before we store it.

We can simply store the unstructured data, and structure it at query time.

Unstructured Data…構造化データ

• Storing Data and Indexing Data are separate processes in all database systems.

•With explicit schema like RDBMS systems, Indexes are general optimized based on the data type(s), every row has an entry, everything is known.

• In flexible schema scenarios Map-Reduce is a technique for gathering common components of data into a collection and in Couchbase, that collection is an Index.

Couchbase Server: Views

全てのデータベースシステムにおいて、データ格納とデータ Index化は、分離されたプロセスである

RDBMSシステムのような厳密な、スキーマを使用することで、 Indexは、一般に、データタイプをベースに最適化され、各 rowはエントリを持ち、全情報を知っている

柔軟なスキーマシナリオにおける Map-Reduceとは、データの主要な要素を収集し、収集結果を得るための技術であるが、Couchbaseにおいては、この収集結果とは、すなわち Indexのことである。

Map-Reduce in General

A Map function locates data items within datasets and outputs an optimized data structure that can be searched and traversed rapidly.

A Reduce function takes the output of a Map function and can calculate various aggregates from it, generally focused on numeric data.

Together they make up a technique for working with data that is semi-structured or unstructured.

一般的なMap-Reduce

Map関数は、データセット中のデータアイテムを取り出し、最適化されたデータ構造を出力する、このデータ構造は、迅速に検索され横断される

Reduce関数は、Map関数の出力を取得し、この出力をもとに、複数種類の集計を行う。一般的には数値データにフォーカスされる

これらの関数は、構造化/半構造化データについての処理技術のために作り上げられた

Couchbase Server 2.0: Map-Reduce

In Couchbase, Map-Reduce is specifically used to create an Index.

Map functions are applied to JSON Documents and they output or “emit” a data structure designed to be rapidly queried and traversed.

Couchbase Server2.0で構築された Map-Reduceについて

Couchbase では、Map-Reduceは、 Indexを生成するために使用される

Map関数は、 JSONドキュメントに適用され、データを出力または” emit”する出力データ構造は、高速に検索や横断をするためにデザインされている

function(doc, meta) {emit(doc.username, doc.email)}

indexed key output value(s)create row

json doc doc metadata

Every­Document­passes­through­View­Map()­functions

Map

Map() Function => Index

function(doc, meta) {emit(doc.email, null)}

text key

Map

doc.email meta.id

[email protected] u::1

[email protected] u::2

[email protected] u::3

Single Element Keys (Text Key)

Indexing Architecture

33 2Managed Cache Disk Q

ueue

Disk

Replication Queue

App Server

Couchbase Server Node

Doc­1Doc­1

Doc­1

To other node

View Engine

Doc­1

Doc Updated in RAM Cache First

Indexer Updates Indexes After On Disk, in Batches

All Documents & Updates Pass Through View Engine

Buckets >> Design Documents >> Views

Couchbase Bucket

Design Document 1 Design Document 2

View ViewViewViewView

Indexers Are Allocated Per Design Doc

All Updated at Same TimeAll Updated at Same TimeAll Updated at Same Time

Can Only Access Data in the Bucket NamespaceCan Only Access Data in the Bucket Namespace

Querying Views

Parameters used in View Querying

• key = “”­ used­for­exact­match­of­index-key

• keys = []­ used­for­matching­set­of­index-keys

• startkey/endkey = “”­ used for range queries on index-keys

• startkey_docID/endkey_docID = “”­ used for range queries on meta.id

• stale=[false, update_after, true]­ used­to­decide­indexer­behavior­from­client

• group/group_by­ used­with­reduces­to­aggregate­with­grouping

Viewクエリにて使用されるパラメータの種類

doc.email meta.id

[email protected] u::1

[email protected] u::7

[email protected] u::2

[email protected] u::5

[email protected] u::6

[email protected] u::4

[email protected] u::3

?startkey=”b1”­&­endkey=”zz”

Pulls the Index-Keys between UTF-8 Range specified by the startkey and endkey.

?startkey=”bz”­&­endkey=”zn”

Pulls the Index-Keys between UTF-8 Range specified by the startkey and endkey.

?startkey=”[email protected]”­&endkey=”[email protected]

Range of a single item (can also be done with key= parameter).

Most Common Query’s Are Ranges最もよく使われるクエリは範囲検索である

doc.email meta.id

[email protected] u::1

[email protected] u::7

[email protected] u::2

[email protected] u::5

[email protected] u::6

[email protected] u::4

[email protected] u::3

?key=”[email protected]”­

Match a Single Index-Key

Index-Key MatchingIndex-Keyのマッチング

doc.email meta.id

[email protected] u::1

[email protected] u::7

[email protected] u::2

[email protected] u::5

[email protected] u::6

[email protected] u::4

[email protected] u::3

?keys=[“[email protected]”,“[email protected]”]

Query Multiple in the Set (Array Notation)

Index-Key Set MatchesIndex-Keyのマッチング

Beer Sample Views Demo

Questions?