2014 it - app dev series - 04 - indicizzazione
DESCRIPTION
TRANSCRIPT
Serie Sviluppo di un’ApplicazioneBack to BasicsStrategie di Indicizzazione
Senior Solutions Architect, MongoDB Inc.
Massimo Brignoli
#MongoDBBasics
Agenda
• Riassunto delle puntate precedenti
• Le Basi dell’indicizzazione– Tipi di indice nella nostra applicazione– Indici composti– Indici Covered
• Valutazione/Tuning– Piano di esecuzione: Explain– Profiler del Database
• Geografia
• Ricerca full-text
Q & A
Virtual Genius Bar
– Use the chat to post questions
– EMEA Solution Architecture / Support team are on hand
– Make use of them during the sessions!!!
Riassunto delle puntate precedenti….
Inserimenti
• ObjectId()
• _id
• Durabilità
• WriteConcerns
• Anche per update
>db.articles.insert({'text': 'Article
content…’, 'date' : ISODate(...), 'title' : ’Intro to MongoDB’, 'author' : 'Dan Roberts’, 'tags' : [
'mongodb',
'database', 'nosql’
]});
opzioni w: MAJORITY, j : true
Query
• Operatori di comparazione
• proiezioni
• cursori
operatori
$gt, $gte, $in, $lt,
$lte, $ne, $nin>var cursor = db.articles.find( { ’author' : ’Dan Roberts’ } , {‘_id’:0, ‘title’:1})
>cursor.hasNext()true
>cursor.next(){ "title" : "Intro to MongoDB" }
Update
• Manipolare i documenti in modo efficiente
• Buckets
• Repor pre-aggregati
• Update sul posto
operators
$each, $slice, $sort, $inc, $push
$inc, $rename, $setOnInsert, $set, $unset, $max, $min
$, $addToSet, $pop, $pullAll, $pull, $pushAll, $push
$each, $slice, $sort
>db.comments.update(
{‘c’: {‘$lt’:10}}, {
‘$inc’ : {c:1},
'$push' : {
'comments' : ‘Excellent’ }},{ upsert : true }
)
Basi dell’Indicizzazione
Basi dell’Indicizzazione
E’ il più grande fattore di miglioramento delle performance in un DB
L’efficienza degli indici va studiata fin da subito
– .// indice sull’autore (ascendente)>db.articles.ensureIndex( { author : 1 } )
// indice sull’autore (discendente)>db.articles.ensureIndex( { author : -1 } )
// indice su un array di valori – indice multi-key>db.articles.ensureIndex( { tags : 1 } )
Indici su Sottodocumenti
E’ possibile creare indici su sottodocumenti:
– Usando la “dot notation”
{‘_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 } }}
>db.interactions.ensureIndex(
{ “daily.comments” : 1}
}
>db.interactions.find(
{“daily.comments” : { $gte : 150} } ,
{ _id:0, “daily.comments” : 1 } )
Gli indici in MongoDB sono B-Tree
Costo O(log(n))
Indici Composti
Sono indici che usano più di un valore
//Da effettuare nella console mongo> db.articles.ensureIndex( { author : 1, tags : 1 } )
> db.articles.find( { author : ‘Dan Roberts’, tags : ‘MongoDB’} )//e> db.articles.find( { author : ‘Dan Roberts’ } )
// Non avete bisogno di questo indice:> db.articles.ensureIndex( { author : 1 } )
Ordinamento
L’ordinamento non ha importanza sugli indici singoli
– Possiamo leggere da entrambe le parti di un btree• { attribute: 1 } o{ attribute: -1 }
L’ordinamento ha importanza negli indici composti
– Ad esempio vogliamo fare una query sull’autore ed ordinare per data// indici su autore crescente ma data decrescente
>db.articles.ensureIndex( { ‘author’ : 1, ‘date’ -1 } )
Query su Covered Index
Ritornano i dati solamente dall’indice
– Invece che dai file del database– Ottimizzazione delle performance– Funziona con gli indici composti
• Invoke with a projection
> db.users.ensureIndex( { user : 1, password :1 } )
> db.user.find({user:"danr"}, {_id:0, password:1})
{ "password" : ”*********" }
Tip: use projections anyway to reduce data sent back to the client
Piano di Explain
Usato per valutare per operazioni e gli indici
– Indica che indice e’ stato usato, se ce n’e’– Quanti documenti sono stati scansionati– Puo’ essere visualizzato nella console o
nell’applicazione
//Da fare nella console> db.articles.find({author:'Dan Roberts'}).sort({date:-1}).explain()
Output del piano di Explain
{"cursor" : "BtreeCursor
author_1_date_-1","isMultiKey" : false,"n" : 1,"nscannedObjects" : 1,"nscanned" : 1,"nscannedObjectsAllPlans" : 1,"nscannedAllPlans" : 1,"scanAndOrder" : false,"indexOnly" : false,"nYields" : 0,"nChunkSkips" : 0,"millis" : 0,"indexBounds" :….
Other Types:
• BasicCursor• Full collection scan
• BtreeCursor• GeoSearchCursor• Complex Plan• TextCursor
Database profiler
Da abilitare per vedere le query lente
– (o tutte le query)– Default 100ms
//Abilita il database profiler nella console, 0=off 1=slow 2=all> db.setProfilingLevel(1, 100){ "was" : 0, "slowms" : 100, "ok" : 1 }
//Vedere il profilo con> show profile
//oppure>db.system.profile.find().pretty()
Output del Database profiler
{"op" : "query","ns" : "test.articles","query" : {
"query" : {"author" : "Dan Roberts"
},"orderby" : {
"date" : -1}
},"ntoreturn" : 0,"ntoskip" : 0,"nscanned" : 1,"nreturned" : 1,
……
Indici Geografici
2dSphere
Indici su campi geospaziali
– Usando la notazione degli oggetti GeoJSON– Geometria su sfera
//Struttura di un oggetto GeoJSON per l’indicizzazione
"location" : { "type" : "Point", "coordinates" : [ -0.128, 51.507 ] }
// Indice su oggetti GeoJSON>db.articles.ensureIndex( { location: “2dsphere” } )
Documenti degli Articoli Esteso
• Memorizza la posizione dove e’ stato postato l’articolo
• Posizione Geo dal browser
Collection degli Articoli>db.articles.insert({
'text': 'Article content…’, 'date' : ISODate(...), 'title' : ’Intro to MongoDB’, 'author' : 'Dan Roberts’, 'tags' : ['mongodb',
'database',
'nosql’],
‘location’ : { ‘type’ : ‘Point’, ‘coordinates’ :
[ -0.128, 51.507 ] }
});
//Funzione per leggere la posizione geograficanavigator.geolocation.getCurrentPosition();
//Da tradurre in un GeoJSON
Esempio
– Query e explain>db.articles.find( { location :
{ $near :{ $geometry :{ type : "Point" ,coordinates : [-
0.128, 51.507] } }, $maxDistance : 5000 }
} )//explain output…{
"cursor" : "S2NearCursor","isMultiKey" : true,"n" : 1,"nscannedObjects" : 1,"nscanned" : 1,….
Ricerca Testuale
Indici di Testo
• Abilita la ricerca full-text• Include il supporto per:– Stemming, 15 lingue, peso, frasi e supporto
all’aggregazione framework– Aggiornata e abilita nella versione 2.6
(rilasciata da poco)• Questi esempio usano la sintassi e le
caratteristiche della 2.6
• La ricerca full-text è importante per i CMS
Ricerca Testuale
• Solo un indice di testo per collection
• Operatore $** per indicizzare tutti i campi testo
• Usa weights per cambiare l’importanza dei campi
>db.articles.ensureIndex({text :”text”}
)
>db.articles.ensureIndex( { "$**" : “text”,
name : “TextIndex”} )
>db.articles.ensureIndex( { "$**" :
"text”}, { weights :
{ ”title" : 5, ”text" : 10}, name : "TextIndex” })
Operatori$text, $search, $language, $meta
Ricerca
Si usano gli operatori $text e $search per fare una query
Ritornano un cursore (finalmente).
$meta for scoring results
– .
// Ricerca gli articoli nella collection> db.articles.find ({$text: { $search: ”MongoDB" }})
> db.articles.find({ $text: { $search: "MongoDB" }}, { score: { $meta: "textScore" }, _id:0,
title:1 } )
{ "title" : "Intro to MongoDB", "score" : 0.75 }
Sommario
Sommario
• Indicizzazione– #1 per migliorare le performance
• Usate durante lo sviluppo per controllare di andare nella direzione corretta:
– Explain plan– Database profiler
• Geospaziale
• Ricerca Full-Text
Prossima Sessione – 13th May
– Reporting e Analytics• Come usare i Report
– Aggregation Framework
• Introduzione