31
Serie Sviluppo di un’Applicazione Back to Basics Interagire con il Database Senior Solutions Architect, MongoDB Inc. Massimo Brignoli #MongoDBBasicsIT

2014 it - app dev series - 03 - interagire con il database

  • Upload
    mongodb

  • View
    470

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 2014   it - app dev series - 03 - interagire con il database

Serie Sviluppo di un’ApplicazioneBack to BasicsInteragire con il Database

Senior Solutions Architect, MongoDB Inc.

Massimo Brignoli

#MongoDBBasicsIT

Page 2: 2014   it - app dev series - 03 - interagire con il database

Agenda

• Riassunto della lezione precedente

• Gli Operatori di Query di MongoDB – Restituire documenti - cursori– Proiezioni

• Gli Operatori di Update di MongoDB– Pacchetti Fissi– Report Pre Aggregati

• Write Concern– Compromesso tra Durabilità e Velocità

Page 3: 2014   it - app dev series - 03 - interagire con il database

Q & A

• Virtual Genius Bar

– Usate la chat per fare domande

– Il team italiano vi risponderà

– Usatelo durante la sessione!

Page 4: 2014   it - app dev series - 03 - interagire con il database

Riassunto dell’Ultima Lezione

Page 5: 2014   it - app dev series - 03 - interagire con il database

Abbia visto l’architettura applicativa– JSON / RESTful– Basata su Python

Schema design– Modellato

• Articoli• Commenti• Interazioni

Schema e Architectura

Client-sideJSON(eg

AngularJS) (BSON)Pymongo

driver

Python web app

HTTP(S) REST

Page 6: 2014   it - app dev series - 03 - interagire con il database

Modellazione degli Articoli

• Post degli articoli

• Ottenere la lista degli articoli

• Ritornare un cursore

• Ottenere un articolo individuale

{ '_id' : ObjectId(...),

'text': 'Article content…',

'date' : ISODate(...),

'title' : ’Intro to MongoDB',

'author' : 'Dan Roberts',

'tags' : ['mongodb',

'database',

'nosql’]

}

Collection degli articoli

METODIdef get_article(article_id)def get_articles():def create_article():

Page 7: 2014   it - app dev series - 03 - interagire con il database

Modellazione dei Commenti

• Memorizzare i commenti

• Ottenere velocemente i commenti più recenti

• Aggiungere nuovi commenti a un documento

• ‘Bucketing’

{‘_id’ : ObjectId(..),

‘article_id’ : ObjectId(..), ‘page’ : 1, ‘count’ : 42 ‘comments’ : [

{ ‘text’ : ‘A great article, helped me understand schema design’, ‘date’ : ISODate(..), ‘author’ : ‘johnsmith’ }, …}

Collection dei commenti

METODIdef add_comment(article_id):def get_comments(article_id):

Page 8: 2014   it - app dev series - 03 - interagire con il database

Modellazione delle Interazioni

• Usato per reportistica sugli articoli

• Creazione di report “pre-aggregati”

{‘_id’ : ObjectId(..),

‘article_id’ : ObjectId(..), ‘section’ : ‘schema’,

‘date’ : ISODate(..),‘daily’: {

‘views’ : 45,

‘comments’ : 150 } ‘hours’ : { 0 : { ‘views’ : 10 }, 1 : { ‘views’ : 2 }, … 23 : { ‘views’ : 14,

‘comments’ : 10 } }}

Collection interazioni

METPDIdef add_interaction(article_id, type):

Page 9: 2014   it - app dev series - 03 - interagire con il database

Eseguire le Query

Page 10: 2014   it - app dev series - 03 - interagire con il database

$gt, $gte, $in, $lt, $lte, $ne, $nin

Usati per cercare nei documenti– Array inclusi

Gli Operatori delle Query

db.articles.find( { 'title' : ’Intro to MongoDB’ } )

db.articles.find({ ’date' : { ‘$lt’ :

{ISODate("2014-02-19T00:00:00.000Z") }} )

db.articles.find( { ‘tags’ : { ‘$in’ : [‘nosql’, ‘database’] } } );

Page 11: 2014   it - app dev series - 03 - interagire con il database

La Find restituisce un cursore– Usato per iterate il set dei risultati– Il cursore ha molti metodi

Cursori

>var cursor = db.articles.find( { ’author' : ’Dan Roberts’ } )>cursor.hasNext()true>cursor.next(){ '_id' : ObjectId(...),

'text': 'Article content…’, 'date' : ISODate(...), 'title' : ’Intro to MongoDB’, 'author' : 'Dan Roberts’, 'tags' : [ 'mongodb', 'database’,'nosql’ ]

}

Page 12: 2014   it - app dev series - 03 - interagire con il database

Restituiscono solamente gli attributi necessari

– La sintassi per selezionare gli attributi usa i booleani 0 e 1

– Aumenta l’efficienza

Proiezioni

>var cursor = db.articles.find( { ’author' : ’Dan Roberts’ } , {‘_id’:0, ‘title’:1})>cursor.hasNext()true>cursor.next(){ "title" : "Intro to MongoDB" }

Page 13: 2014   it - app dev series - 03 - interagire con il database

Update dei dati

Page 14: 2014   it - app dev series - 03 - interagire con il database

$each, $slice, $sort, $inc, $push

$rename, $setOnInsert, $set, $unset, $max, $min

$addToSet, $pop, $pullAll, $pull, $pushAll, $push

Operatori di Update

>db.articles.update(

{ '_id' : ObjectId(...)},

{ '$push' : {'comments' :

‘Great article!’}}

)

{ 'text': 'Article content…’ 'date' : ISODate(...),

'title' : ’Intro to MongoDB’,

'author' : 'Dan Roberts’,

'tags' : ['mongodb',

'database’,'nosql’ ],’comments' :

[‘Great article!’ ]

}

Page 15: 2014   it - app dev series - 03 - interagire con il database

Aggiungere un elemento ad un array di lunghezza fissa

con…

$push, $each, $slice

Operatori di Update

>db.articles.update(

{ '_id' : ObjectId(...)},

{ '$push' : {'comments' :

{

'$each' : [‘Excellent’], '$slice' : -3}}, })

{ 'text': 'Article content…’ 'date' : ISODate(...),

'title' : ’Intro to MongoDB’,

'author' : 'Dan Roberts’,

'tags' : ['mongodb',

'database’,'nosql’ ],’comments' :

[‘Great article!’, ‘More please’, ‘Excellent’ ]

}

Page 16: 2014   it - app dev series - 03 - interagire con il database

Operatori di Update - Bucketing

• Scriviamo 10 commenti in un singolo documento (bucket)

• Crea automaticamente un nuovo documento

• Use {upsert: true} not insert.

>db.comments.update(

{‘c’: {‘$lt’:10}}, {

‘$inc’ : {c:1},

'$push' : {

'comments' : ‘Excellent’}},{upsert : true}

)

{‘_id’ : ObjectId( … )‘c’ : 3,’comments' :

[‘Great article!’,

‘More please’, ‘Excellent’ ]

}

Page 17: 2014   it - app dev series - 03 - interagire con il database

Analitica– Report Pre-Aggregati

• Usato per fare statistiche sugli articoli

• Crea report pre-aggregati

{‘_id’ : ObjectId(..),

‘article_id’ : ObjectId(..), ‘section’ : ‘schema’,

‘date’ : ISODate(..),‘daily’: {

‘views’ : 45,

‘comments’ : 150 } ‘hours’ : { 0 : { ‘views’ : 10 }, 1 : { ‘views’ : 2 }, … 23 : { ‘views’ : 14,

‘comments’ : 10 } }}

Collections Interazioni

METODOdef add_interaction(article_id, type):

Page 18: 2014   it - app dev series - 03 - interagire con il database

Incrementare i Contatori

• Usate $inc per incrementare contatori multipli

• Singola operazione Atomica

• Incrementa i contatori giornalieri e orari>db.interactions.update({‘article_id’ :

ObjectId(..)}, {

‘$inc’ : {

‘daily.views’:1,

‘daily.comments’:1

‘hours.8.views’:1

‘hours.8.comments’:1 })

{‘_id’ : ObjectId(..),

‘article_id’ : ObjectId(..), ‘section’ : ‘schema’,

‘date’ : ISODate(..),‘daily’: {

‘views’ : 45,

‘comments’ : 150 } ‘hours’ : { 0 : { ‘views’ : 10 }, 1 : { ‘views’ : 2 }, … 23 : { ‘views’ : 14,

‘comments’ : 10 } }}

Page 19: 2014   it - app dev series - 03 - interagire con il database

Incrementare i Contatori

• Incrementate nuovi contatori>db.interactions.update({‘article_id’ :

ObjectId(..)}, {

‘$inc’ : {

‘daily.views’:1,

‘daily.comments’:1,

‘hours.8.views’:1,

‘hours.8.comments’:1,

‘referrers.bing’ : 1})

{‘_id’ : ObjectId(..),

‘article_id’ : ObjectId(..), ‘section’ : ‘schema’,

‘date’ : ISODate(..),‘daily’: {

‘views’ : 45,

‘comments’ : 150 } ‘hours’ : {

…..}‘referrers’ : {

‘google’ : 27

}}

Page 20: 2014   it - app dev series - 03 - interagire con il database

Incrementare i Contatori

• Incrementate nuovi contatori>db.interactions.update({‘article_id’ :

ObjectId(..)}, {

‘$inc’ : {

‘daily.views’:1,

‘daily.comments’:1,

‘hours.8.views’:1,

‘hours.8.comments’:1,

‘referrers.bing’ : 1})

{‘_id’ : ObjectId(..),

‘article_id’ : ObjectId(..), ‘section’ : ‘schema’,

‘date’ : ISODate(..),‘daily’: {

‘views’ : 45,

‘comments’ : 150 } ‘hours’ : {

…..}‘referrers’ : {

‘google’ : 27,‘bing’ : 1

}}

Page 21: 2014   it - app dev series - 03 - interagire con il database

Durabilità

Page 22: 2014   it - app dev series - 03 - interagire con il database

Durabilità

• Con MongoDB potete scegliere• In memoria• Su disco• Su multipli server

• Write Concern• Ritorna dopo il successo di un’operazione di

scrittura• Il driver chiama getLastError

• Compromesso• Latenza della risposta

Page 23: 2014   it - app dev series - 03 - interagire con il database

Unacknowledged

Page 24: 2014   it - app dev series - 03 - interagire con il database

MongoDB Acknowledged

Page 25: 2014   it - app dev series - 03 - interagire con il database

Wait for Journal Sync

Page 26: 2014   it - app dev series - 03 - interagire con il database

Replica Set

• Replica Set – due o più copie

• E’ uno shard “Self-healing”

• Indirizza diverse esigenze:

- High Availability

- Disaster Recovery

- Manutenzione

Page 27: 2014   it - app dev series - 03 - interagire con il database

Wait for Replication

Page 28: 2014   it - app dev series - 03 - interagire con il database

Riassunto

Page 29: 2014   it - app dev series - 03 - interagire con il database

Riassumendo

• Interagendo con il database– Query e proiezioni– Insert e Upsert

– Operatori– Bucketing– Report Pre Aggregated

Page 30: 2014   it - app dev series - 03 - interagire con il database

Prossima Sessione: 29 Aprile.

– Indicizzazione• Strategie di indicizzazione• Search testuale• Ricerche geografiche

– Esempi di Codice

Page 31: 2014   it - app dev series - 03 - interagire con il database