SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Serie Sviluppo di
un’Applicazione
Back to Basics
Strategie 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
– EMEASolution
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 geografica
navigator.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 eAnalytics
• Come usare i Report
– Aggregation Framework
• Introduzione
2014   it - app dev series - 04 - indicizzazione

Weitere ähnliche Inhalte

Was ist angesagt?

Back to Basics, webinar 1: Introduzione a NoSQL
Back to Basics, webinar 1: Introduzione a NoSQLBack to Basics, webinar 1: Introduzione a NoSQL
Back to Basics, webinar 1: Introduzione a NoSQLMongoDB
 
E suap - tecnologie client
E suap - tecnologie client E suap - tecnologie client
E suap - tecnologie client Sabino Labarile
 
Back to Basics, webinar 6: Messa in esercizio
Back to Basics, webinar 6: Messa in esercizioBack to Basics, webinar 6: Messa in esercizio
Back to Basics, webinar 6: Messa in esercizioMongoDB
 
MongoDb and Scala SpringFramework Meeting
MongoDb and Scala SpringFramework MeetingMongoDb and Scala SpringFramework Meeting
MongoDb and Scala SpringFramework Meetingguest67beeb9
 
MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009Massimiliano Dessì
 
Advanced Database Models and Architectures: Big Data: MySQL VS MongoDB
Advanced Database Models and Architectures: Big Data: MySQL VS MongoDBAdvanced Database Models and Architectures: Big Data: MySQL VS MongoDB
Advanced Database Models and Architectures: Big Data: MySQL VS MongoDBLuca Marignati
 
MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009Massimiliano Dessì
 
Javascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerJavascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerMatteo Magni
 
jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerMatteo Magni
 
MongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBMongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBStefano Dindo
 
jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerMatteo Magni
 

Was ist angesagt? (11)

Back to Basics, webinar 1: Introduzione a NoSQL
Back to Basics, webinar 1: Introduzione a NoSQLBack to Basics, webinar 1: Introduzione a NoSQL
Back to Basics, webinar 1: Introduzione a NoSQL
 
E suap - tecnologie client
E suap - tecnologie client E suap - tecnologie client
E suap - tecnologie client
 
Back to Basics, webinar 6: Messa in esercizio
Back to Basics, webinar 6: Messa in esercizioBack to Basics, webinar 6: Messa in esercizio
Back to Basics, webinar 6: Messa in esercizio
 
MongoDb and Scala SpringFramework Meeting
MongoDb and Scala SpringFramework MeetingMongoDb and Scala SpringFramework Meeting
MongoDb and Scala SpringFramework Meeting
 
MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009MongoDB Scala Roma SpringFramework Meeting2009
MongoDB Scala Roma SpringFramework Meeting2009
 
Advanced Database Models and Architectures: Big Data: MySQL VS MongoDB
Advanced Database Models and Architectures: Big Data: MySQL VS MongoDBAdvanced Database Models and Architectures: Big Data: MySQL VS MongoDB
Advanced Database Models and Architectures: Big Data: MySQL VS MongoDB
 
MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009MongoDB SpringFramework Meeting september 2009
MongoDB SpringFramework Meeting september 2009
 
Javascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerJavascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesigner
 
jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesigner
 
MongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBMongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDB
 
jQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesignerjQuery - 1 | WebMaster & WebDesigner
jQuery - 1 | WebMaster & WebDesigner
 

Ähnlich wie 2014 it - app dev series - 04 - indicizzazione

Layered Expression Trees feat. CQRS
Layered Expression Trees feat. CQRSLayered Expression Trees feat. CQRS
Layered Expression Trees feat. CQRSAndrea Saltarello
 
Deploy MongoDB su Infrastruttura Amazon Web Services
Deploy MongoDB su Infrastruttura Amazon Web ServicesDeploy MongoDB su Infrastruttura Amazon Web Services
Deploy MongoDB su Infrastruttura Amazon Web ServicesStefano Dindo
 
I Graph Database: analisi del comportamento degli utenti
I Graph Database: analisi del comportamento degli utentiI Graph Database: analisi del comportamento degli utenti
I Graph Database: analisi del comportamento degli utentiThinkOpen
 
Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Martino Bordin
 
Corso avanzato di Tecnologie WEB - jquery e d3js
Corso avanzato di Tecnologie WEB - jquery e d3jsCorso avanzato di Tecnologie WEB - jquery e d3js
Corso avanzato di Tecnologie WEB - jquery e d3jsStudiabo
 
Azure No-Sql approach: DocumentDB
Azure No-Sql approach: DocumentDBAzure No-Sql approach: DocumentDB
Azure No-Sql approach: DocumentDBDavide Benvegnù
 
Introduzione a Node.js
Introduzione a Node.jsIntroduzione a Node.js
Introduzione a Node.jsMichele Capra
 
CommunityDays 2015 - NPM, GRUNT E BOWER: IL NUOVO PACKAGE MANAGER DI VISUAL S...
CommunityDays 2015 - NPM, GRUNT E BOWER: IL NUOVO PACKAGE MANAGER DI VISUAL S...CommunityDays 2015 - NPM, GRUNT E BOWER: IL NUOVO PACKAGE MANAGER DI VISUAL S...
CommunityDays 2015 - NPM, GRUNT E BOWER: IL NUOVO PACKAGE MANAGER DI VISUAL S...Gianluca Carucci
 
How I did it (in .NET): idiomatic Domain Driven Design
How I did it (in .NET): idiomatic Domain Driven DesignHow I did it (in .NET): idiomatic Domain Driven Design
How I did it (in .NET): idiomatic Domain Driven DesignAndrea Saltarello
 
Programmazione web libera dai framework
Programmazione web libera dai frameworkProgrammazione web libera dai framework
Programmazione web libera dai frameworkFrancesca1980
 
CDays15 - AZ08 - DocumentDB: il NoSql secondo Azure
CDays15 - AZ08 - DocumentDB: il NoSql secondo AzureCDays15 - AZ08 - DocumentDB: il NoSql secondo Azure
CDays15 - AZ08 - DocumentDB: il NoSql secondo AzureDavide Benvegnù
 
Never Mind the Bollocks: here's the Domain Driven Design
Never Mind the Bollocks: here's the Domain Driven DesignNever Mind the Bollocks: here's the Domain Driven Design
Never Mind the Bollocks: here's the Domain Driven DesignAndrea Saltarello
 
Una PA agile, funzionale e serverless: si può fare! by Federico Feroldi and D...
Una PA agile, funzionale e serverless: si può fare! by Federico Feroldi and D...Una PA agile, funzionale e serverless: si può fare! by Federico Feroldi and D...
Una PA agile, funzionale e serverless: si può fare! by Federico Feroldi and D...Codemotion
 

Ähnlich wie 2014 it - app dev series - 04 - indicizzazione (20)

Layered Expression Trees feat. CQRS
Layered Expression Trees feat. CQRSLayered Expression Trees feat. CQRS
Layered Expression Trees feat. CQRS
 
Deploy MongoDB su Infrastruttura Amazon Web Services
Deploy MongoDB su Infrastruttura Amazon Web ServicesDeploy MongoDB su Infrastruttura Amazon Web Services
Deploy MongoDB su Infrastruttura Amazon Web Services
 
JavaScript
JavaScriptJavaScript
JavaScript
 
MyTask
MyTaskMyTask
MyTask
 
I Graph Database: analisi del comportamento degli utenti
I Graph Database: analisi del comportamento degli utentiI Graph Database: analisi del comportamento degli utenti
I Graph Database: analisi del comportamento degli utenti
 
Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3Entity Framework 4 vs NHibernate 3
Entity Framework 4 vs NHibernate 3
 
Corso avanzato di Tecnologie WEB - jquery e d3js
Corso avanzato di Tecnologie WEB - jquery e d3jsCorso avanzato di Tecnologie WEB - jquery e d3js
Corso avanzato di Tecnologie WEB - jquery e d3js
 
Azure No-Sql approach: DocumentDB
Azure No-Sql approach: DocumentDBAzure No-Sql approach: DocumentDB
Azure No-Sql approach: DocumentDB
 
Introduzione a node.js
Introduzione a node.jsIntroduzione a node.js
Introduzione a node.js
 
Introduzione a Node.js
Introduzione a Node.jsIntroduzione a Node.js
Introduzione a Node.js
 
CommunityDays 2015 - NPM, GRUNT E BOWER: IL NUOVO PACKAGE MANAGER DI VISUAL S...
CommunityDays 2015 - NPM, GRUNT E BOWER: IL NUOVO PACKAGE MANAGER DI VISUAL S...CommunityDays 2015 - NPM, GRUNT E BOWER: IL NUOVO PACKAGE MANAGER DI VISUAL S...
CommunityDays 2015 - NPM, GRUNT E BOWER: IL NUOVO PACKAGE MANAGER DI VISUAL S...
 
How I did it (in .NET): idiomatic Domain Driven Design
How I did it (in .NET): idiomatic Domain Driven DesignHow I did it (in .NET): idiomatic Domain Driven Design
How I did it (in .NET): idiomatic Domain Driven Design
 
Programmazione web libera dai framework
Programmazione web libera dai frameworkProgrammazione web libera dai framework
Programmazione web libera dai framework
 
CDays15 - AZ08 - DocumentDB: il NoSql secondo Azure
CDays15 - AZ08 - DocumentDB: il NoSql secondo AzureCDays15 - AZ08 - DocumentDB: il NoSql secondo Azure
CDays15 - AZ08 - DocumentDB: il NoSql secondo Azure
 
Never Mind the Bollocks: here's the Domain Driven Design
Never Mind the Bollocks: here's the Domain Driven DesignNever Mind the Bollocks: here's the Domain Driven Design
Never Mind the Bollocks: here's the Domain Driven Design
 
Repository pattern
Repository patternRepository pattern
Repository pattern
 
JOSM per “ninja”
JOSM per “ninja”JOSM per “ninja”
JOSM per “ninja”
 
Azure DocumentDb
Azure DocumentDbAzure DocumentDb
Azure DocumentDb
 
What's new in C# 7
What's new in C# 7What's new in C# 7
What's new in C# 7
 
Una PA agile, funzionale e serverless: si può fare! by Federico Feroldi and D...
Una PA agile, funzionale e serverless: si può fare! by Federico Feroldi and D...Una PA agile, funzionale e serverless: si può fare! by Federico Feroldi and D...
Una PA agile, funzionale e serverless: si può fare! by Federico Feroldi and D...
 

Mehr von MongoDB

MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB
 
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!MongoDB
 
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...MongoDB
 
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDBMongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDBMongoDB
 
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...MongoDB
 
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series DataMongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series DataMongoDB
 
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 MongoDB SoCal 2020: MongoDB Atlas Jump Start MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB SoCal 2020: MongoDB Atlas Jump StartMongoDB
 
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]MongoDB
 
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB
 
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB
 
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB
 
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB
 
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB
 
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB
 
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB
 
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB
 
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB
 
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB
 
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB
 
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB
 

Mehr von MongoDB (20)

MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
 
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDBMongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
 
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
 
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series DataMongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
 
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 MongoDB SoCal 2020: MongoDB Atlas Jump Start MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
 
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
 
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
 
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
 
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
 
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
 
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
 
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
 
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
 
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
 
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
 
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
 

2014 it - app dev series - 04 - indicizzazione

  • 1. Serie Sviluppo di un’Applicazione Back to Basics Strategie di Indicizzazione Senior Solutions Architect, MongoDB Inc. Massimo Brignoli #MongoDBBasics
  • 2. 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
  • 3. Q & A Virtual Genius Bar – Use the chat to post questions – EMEASolution Architecture / Support team are on hand – Make use of them during the sessions!!!
  • 5. 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
  • 6. 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" }
  • 7. 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 } )
  • 9. 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 } )
  • 10. 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 } )
  • 11. Gli indici in MongoDB sono B-Tree
  • 13. 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 } )
  • 14. 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 } )
  • 15. 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
  • 16. 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()
  • 17. 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
  • 18. 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()
  • 19. 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, ……
  • 21. 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” } )
  • 22. 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 geografica navigator.geolocation.getCurrentPosition(); //Da tradurre in un GeoJSON
  • 23. 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, ….
  • 25. 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
  • 26. 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
  • 27. 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 }
  • 29. 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
  • 30. Prossima Sessione – 13th May – Reporting eAnalytics • Come usare i Report – Aggregation Framework • Introduzione