mongodb tutorial

Preview:

DESCRIPTION

mongodb 소개 및 basic tutorial 자료입니다. - 데이터베이스의 진화 - nosql의 등장배경 및 역할 - mycq 개발 경험 - mongodb 기능 및 구조

Citation preview

MongoDB 튜토리얼

박 재 홍

jaehong@mycq.co.kr

Big Data 처리 기술

NoSQL

MongoDB

사례시스템

로그 인프라

3G망 패킷분석

모바일 리서치

Flurry.com

항공기 블랙박스

CCTV

Person of Interest

전파 분석

Glory FS 관리도구

오픈스택 관리도구

실시간 이벤트 처리

SLA, 자판기

빅데이터 처리 기술 개요

데이터 처리 기술의 진화

SQL에 의존하지 않는 기술의 발전 및 성공사례 증가

빅서비스 >다양한 데이터 처리 요구(데이터 구조, 량, 속도) 증가 > 상용DB는 고비용 >입맛에 맞는 기술이 없음 >직접 만들어 사용

데이터 처리 기술 진화 가속화

Google MapReduce (2004)

Scale Up vs. Scale Out

128cores(4core*32)4 TB Memory

분산처리

20억원 1억원vs.

HP Superdome 2 (2010)

(4core, 128G) * 32

NoSQL(No Join, No Transaction)

2PC?OK

네트워크로 컴퓨터 연결//복잡함컴퓨터 대수가 많다보니, 고장 확율 높아짐.

이런상황에서 TX보장 및 JOIN기능 제공 하면서 성능내기쉽지않음.TRANSACTION (X) // Atomic OperationJOIN (X) // Embedded Document로 해소

분산처리

NoSQL 기술의 시장은?

상용(오픈)RDBMS

상용(오픈)RDBMS

NoSQL

SQL (ex, Oracle): 현재가치가 큰 데이터NoSQL: 미래가치가 큰 데이터

• 대용량 데이터 처리 비용 감소• 전체 데이터 처리 시장 확대

RDBMS > NoSQL로 전환

시장

2014.2

2013

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

빅데이터 처리 기술

빅데이터 처리 플랫폼 구조

빅데이터 처리 플랫폼

수집

플랫폼 관리분석 서비스

(GUI)연동 서비스(Open API)

저장 분석

빅데이터 처리 플랫폼 구조

데이터 수집

• 다양한 데이터타입 수집방법 제공• 정형, 반정형, 비정형

• 다양한 데이터소스 수집방법 제공• 파일, DB, 스트림

데이터 저장소

• 대용량 분산파일시스템• HDFS, GloryFS, GridFS

• 대용량 분산DB (NoSQL)• MongoDB 등

• 대용량 텍스트 검색 엔진• Elastic Search 등

데이터 분석 프레임워크

• 배치분석 방법 제공: 파일 기반 배치분석:Hadoop M/R, DB 기반 배치분석:MongoDB M/R

• 대화형분석 방법 제공: Hbase, Mongo 등

• 머신러닝 분석 방법 제공: Mahout 등• Complex Event Processing 분석방법

제공: Esper, MyCQL 등

플랫폼 관리 서비스

• 클라우드 가상머신 기반 자원할당• 인프라 상태 모니터링 (노드,

프로세스, 로그 등)• 사용자 인증 및 관리• 인프라 설정관리• 빌링

분석 서비스 (GUI)

• 배치분석 알고리즘 관리 및 수행• 대화형 분석 방법 제공• 워크플로우 관리• 데이터 업/다운로드 방법 제공• 분석 결과 시각화 제공

연동 서비스 (Open API, 3rd Party 연동)

• 인증• 서비스 검색• 서비스 연동, 기능조회 등• 데이터 업/다운로드• 외부 API 연동

데이터 소스

• 파일• (스트림)데이터• DB• 연동 API• …

수집기

• 데이터 변환• 데이터 변환 규칙 (XML, JSON, DB 등)• 데이터 필터링, Smoothing, Shedding, Sampling

• 데이터 라우팅 & 적재• 파일시스템 또는 데이터베이스에 데이터 적재• 데이터 압축 적재• 분산 병렬 적재 기법• 적재 신뢰성 보장 유무

• 데이터 보관주기• 용량기준 데이터 삭제 후 적재• 보관주기 기준 과거 데이터 삭제

• 이벤트 처리• 데이터 적재전 특정 상황 발생 감지 및 전달

• 방식: 에이젼트, API제공 or 호출

• 실행위치• 데이터가 생산되는 장비• 수집 전용 장비

저장소

데이터수집

• 분산 파일 시스템

• 분산 DB(NoSQL) 시스템

• 분산 텍스트 검색엔진 시스템

• 파티셔닝(샤딩)

• 복제

• 로드밸런싱

• 데이터 마이그레이션

• 유연성

• 신뢰성

• 가용성

• 확장성

• 안정성

• 성능

• 보안

저장 기술데이터저장

분산파일 시스템

ex) Hadoop FS메모리: 64M (2억5천개파일)Single Node

데이터저장

Key/Value DB

MapMap.Put(key,value);

Value = Map.Get(key);

Key: User1Value: Name1, Point1, X1

Key: User2Value: Name2, Point2, X2

Key: X1Value: ****

Key: X2Value: ****

데이터저장

Graph DB데이터저장

MongoDB데이터저장

데이터저장

데이터저장

배치 분석: Map/Reduce데이터분석

MongoDB Map/Reduce

// function finalize(key, value)-> final_value

데이터분석

MongoDB Map/Reduce데이터분석

Continuous Map/Reduce

T(n) T(n-1) T(n-2) … … T(0)

New Data

Area 1 Area 2

데이터분석

Hot Cold

실시간 데이터 스트림 분석

windowqueue1 as win1[size=5sec, slide=5sec]select * from win1where string like 'hello%' and (col2=1000 or col3=5000)

• MyCQ Server• Esper

MyCQL

데이터분석

데이터분석

full text 검색

데이터분석

서비스 운영&품질관리

• 운영

– 관리

• 처리용량 설계&계획

• H/W(서버,네트워크장비) 설계 및 구축

• 클러스터&노드 추가,삭제,변경

• 데이터 삭제,백업,복구

• 가상머신 기반의 클라우드 환경에서 관리

– 모니터링

• GUI 제공 (PC용, Mobile App, Web App(RIA 기반, W3C 표준준수)

• H/W (CPU, Memory, Disk, Network 등)

• 데이터 사이즈, 레코드수, OP(read,write,delete)성능 등

• 품질관리

– 기능 시험

• 개발된 수집,저장,분석 기능에 대한 시험

– 비기능 시험

• 성능, 안정성, 확장성 등

– 수집성능(처리량, 처리건수 등), 분석성능(분석량, 건수 등)

– 노드 장애시 안정성 시험.

– 처리량에 대한 확장성 시험 등.

플랫폼관리

Data Source

Real-Time Data Stream Processor

DatabaseDatabase

Application

Real-TimeApplication

Batch Analysis

pattern

EventArchiving

saveevents

history datajoin

events (tx)

updaterule

Architecture

MONGO DB

MongoDB

MongoDB (from "humongous")

Scalable

high-performanceopen source

NoSQL database

Written in C++

from 2007

User Application

Client LibraryApache, BSD, ...

MongoDB Software License

MongoDB

GNU AGPL v3.0

MONGO DBBasic

www.mongodb.org

MongoDB 매뉴얼

MongoDB Shell (연습용)

MongoDB 다운로드

MongoDB University

MongoDB University

MongoDB MMS & Backup

MongoDB 특징

Document-Oriented StorageFull Index Support

Replication & High Availability Auto-Sharding

Querying Fast In-Place Updates

Map/ReduceGridFS

MongoDB 저장 구조 (Logical)

MongoDBDatabase

CollectionDocument...

......

JSON• JSON (JavaScript Object Notation)

– Standard ECMA-262 3rd Edition - December 1999object{}{ members }

memberspairpair , members

pairstring : value

array[][ elements ]

elementsvaluevalue , elements

valuestringnumberobjectarraytrue,falsenull

Grammar

Example

Document

BSONhttp://bsonspec.org

Grammar

Example

JSON에 비해 사이즈 줄이고컴퓨터가 처리하기에 성능이 더 좋음.

CRUD Demo• Shell• Java Application

insert

update

find

find

remove find

SQL to MongoDB Mapping

실행파일

SQL to MongoDB Mapping

CREATE, ALTER, INDEX, DROP

INSERT, SELECT

Indexing

indexing compound indexing

People Collection Products Collection

db.addresses.ensureIndex( { "user_id": 1 }, { unique: true } ) // 중복허용안함db.accounts.ensureIndex( { username: 1 }, { unique: true, dropDups: true } )db.people.ensureIndex( { zipcode: 1}, {background: true} ) //인덱싱하는동안에도 CRUD 가능.

db.addresses.ensureIndex( { "xmpp_id": 1 }, { sparse: true } ) //필드값 존재하는 문서의 값만 인덱싱

Index

• TTL Index

– 날짜 필드를 가진문서에, 일정시간 지나면 데이터를 삭제하도록 인덱싱

• Geospatial Index

– 2차원 인덱싱

– {loc: [ x , y ]}

– db.places.ensureIndex( { loc : "2d" } )

– 검색• 4각형: db.collection.find( { location: { $near: [100,100] } } );

• 원형: db.collection.find( { location: { $within: { $center: [ center, radius } } } );

• 다각형: db.collection.find( { location: { $within: { $box: [[100,120], [100,100], [120,100], [240,200]] } } } );

Update, Delete

Reference

• 문서

• 강의

MONGO DBDBA Level

REPLICATION

• Replica set

– A replica set consists of two or more nodes that are copies of each other. (i.e.: replicas)

– The replica set automatically elects a primary (master). No one member is intrinsically primary; that is, this is a share-nothing design.

– Drivers (and mongos) can automatically detect when a replica set primary changes and will begin sending writes to the new primary. (The mongos sharding process does this too.)

• Uses

– Data Redundancy

– Automated Failover / High Availability

– Distributing read load

– Simplify maintenance (compared to "normal" master-slave)

– Disaster recovery

eventual consistencyorconsistency

REPLICATION

• Replica Set Member Type

– Default

– Secondary-Only: These members have data but cannot become primary under any circumstance. Hidden: These members are invisible to client applications.

– Delayed: These members apply operations from the primary’s oplog after a specified delay. You can think of a delayed member as a form of “rolling backup.”

– Arbiters: These members have no data and exist solely to participate in elections.

– Non-Voting: These members do not vote in elections. Non-voting members are only used for larger sets with more than 12 members.

REPLICATION

• OPLog

– (operations log) is a special capped collection that keeps a rolling record of all operations that modify that data stored in your databases.

• Rollbacks

– MongoDB writes the rollback data to a BSON file in the database’s dbpath directory

oplog

oplogoplog

Sharding

• MongoDB의 수평확장성은 Auto-sharding (partitioning) 구조를 기반으로 함.– Automatic load balancing

– Easy addition of new machines without down time

– Scaling to one thousand nodes

– No single points of failure

– Automatic failover

Sharding

Sharding Status

MAP/REDUCE

// function finalize(key, value)-> final_value

MAP/REDUCE

Map Reduce Command

입력

출력입력데이터 검색(필터)

MongoDB’s Map/Reduce

분석 프로그램(분석알고리즘)

MongoD Shard MongoD Shard MongoD Shard MongoD Shard

알고리즘

1-25 25-50 51-7576-100Result:X

알고리즘 알고리즘 알고리즘

GRID FS

mongod mongod mongod

File

c1 c2 c3

split

chunks

File1c1

File2c2

File3c3

File2

File2c1

File2c1

Grid FS파일 검색가능파일정보에 인덱싱 가능File에 대한 Meta정보 추가/변경 가능

Memory Map

커널에 의해 여유 시간에 RAM과 DISK 의 동기화가 될 때까지서로 다른 데이터를 가질 수 있다. 개발자가 직접 커널에 동기화를 명령 할 수 있다. fsync()

Shred Memory-Map메모리 맵 변경 시 원본 파일과 데이터가 동기화가 되는방식

Private Memory-Map처음 메모리 맵에 매핑 될때 파일의 내용을 읽어와서복사하고 그 이후 동기화 하지 않는 방식.

MongoDB’s Consistency And Durability

MongoDB Journaling

• Your disk has your data files and your journal files, which we’ll represent like this:

MongoDB’s Consistency And Durability

MongoDB Journaling

• When you start up mongod, it maps your data files to a shared view. Basically, the operating system says: “Okay, your data file is 2,000 bytes on disk. I’ll map that to memory address 1,000,000-1,002,000. So, if you read the memory at memory address 1,000,042, you’ll be getting the 42nd byte of the file.” (Also, the data won’t necessary be loaded until you actually access that memory.)

MongoDB’s Consistency And Durability

MongoDB Journaling

• This memory is still backed by the file: if you make changes in memory, the operating system will flush these changes to the underlying file. This is basically how mongod works without journaling: it asks the operating system to flush in-memory changes every 60 seconds.

• However, with journaling, mongod makes a second mapping, this one to a private view. Incidentally, this is why enabling journalling doubles the amount of virtual memory mongod uses.

MongoDB’s Consistency And Durability

MongoDB Journaling

• Note that the private view is not connected to the data file, so the operating system cannot flush any changes from the private view to disk.

• Now, when you do a write, mongod writes this to the private view.

MongoDB’s Consistency And Durability

MongoDB Journaling

• mongod will then write this change to the journal file, creating a little description of which bytes in which file changed.

MongoDB’s Consistency And Durability

MongoDB Journaling

• The journal appends each change description it gets.

MongoDB’s Consistency And Durability

MongoDB Journaling

• At this point, the write is safe. If mongod crashes, the journal can replay the change, even though it hasn’t made it to the data file yet.

• The journal will then replay this change on the shared view.

MongoDB’s Consistency And Durability

MongoDB Journaling

• Finally, at a glacial speed compared to everything else, the shared view will be flushed to disk. By default, mongod requests that the OS do this every 60 seconds.

MongoDB’s Consistency And Durability

MongoDB Journaling

• The last step is that mongod remaps the shared view to the private view. This prevents the private view from getting too “dirty” (having too many changes from the shared view it was mapped from).

MongoDB’s Consistency And Durability

MongoDB’s WriteConcern

Data File

Memory

Journal File

Data File

Memory

Journal File

Primary SecondaryReplication

1. Write Request 2. To Memory3. To Journal File (SAFE )4. To Data File (deprecated since v1.8)5. To 2nd, 3rd … Nodes6. To 2nd, 3rd … Nodes’ Journal File

MongoDB’s Consistency And Durability

MongoDB’s WriteConcern

FSYNC_SAFEExceptions are raised for network issues, and server errors; the write operation waits for the server to flush the data to disk

JOURNAL_SAFEExceptions are raised for network issues, and server errors; the write operation waits for the server to group commit to the journal file on disk

MAJORITYExceptions are raised for network issues, and server errors; waits on a majority of servers for the write operation

NONENo exceptions are raised, even for network issues

NORMALExceptions are raised for network issues, but not server errors

REPLICAS_SAFEExceptions are raised for network issues, and server errors; waits for at least 2 servers for the write operation

SAFEExceptions are raised for network issues, and server errors; waits on a server for the write operation

MongoDB’s Consistency And Durability

MongoDB’s Consistency And Durability

MongoDB’s Consistency And Durability

Disk Backup 전략RAID 10

Block-level stripingwithout parity or mirroring.

Mirroringwithout parity or striping. Ex) Software-based RAID

Linux RAID(mdadm), LVM

Disk 활용도 및 성능을 위해

Client Libraries

MongoDB Developer & DBA

• Mongo shell

• Cluster Design

– Operations

– Replication

– Sharding

• Schema Design

• Admin & Operation

– Monitoring

– Capability planning

– Disaster Recovery

– Backup

– Hardware Selection

• Performance Tuning

• App Developer– 애플리케이션 개발: MongoDB Driver 기반의

CRUD, M/R 개발

• DBA– 설치와 환경설정

– 보안 관리

– 운영: 백업과 복원, 사용자 관리, 운영 업무

– 서비스 레벨 유지: 성능 최적화 및 성능 모니터링, 용량 계획 (Capacity Planning)

– 시스템 가동 시간 관리: 시스템 정지 시간의 계획과 일정 관리

– 작업 절차 계획 및 규격화: 운영 유지보수 계획 수립, 재난 복구 계획 수립

– 설계 및 개발 지원: 데이터 모델링, 데이터베이스설계

– 긴급 상황 해결/장애 복구

MongoDB를 잘 사용하기 위해서는