Upload
mongodb
View
470
Download
0
Embed Size (px)
Citation preview
Serie Sviluppo di un’ApplicazioneBack to BasicsInteragire con il Database
Senior Solutions Architect, MongoDB Inc.
Massimo Brignoli
#MongoDBBasicsIT
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à
Q & A
• Virtual Genius Bar
– Usate la chat per fare domande
– Il team italiano vi risponderà
– Usatelo durante la sessione!
Riassunto dell’Ultima Lezione
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
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():
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):
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):
Eseguire le Query
$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’] } } );
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’ ]
}
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" }
Update dei dati
$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!’ ]
}
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’ ]
}
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’ ]
}
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):
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 } }}
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
}}
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
}}
Durabilità
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
Unacknowledged
MongoDB Acknowledged
Wait for Journal Sync
Replica Set
• Replica Set – due o più copie
• E’ uno shard “Self-healing”
• Indirizza diverse esigenze:
- High Availability
- Disaster Recovery
- Manutenzione
Wait for Replication
Riassunto
Riassumendo
• Interagendo con il database– Query e proiezioni– Insert e Upsert
– Operatori– Bucketing– Report Pre Aggregated
Prossima Sessione: 29 Aprile.
– Indicizzazione• Strategie di indicizzazione• Search testuale• Ricerche geografiche
– Esempi di Codice