SlideShare une entreprise Scribd logo
1  sur  35
Tugdual Grall (@tgrall)
Alain Hélaïli (@AlainHelaili)
#MongoDBBasics @MongoDB
Construire une application avec MongoDB
Stratégies et options
d’indexation
2
• Résumé des épisodes précédents
• Fondamentaux de l’indexation
– Types d’index dans notre application
– Compound index
– Covered index
• Evaluation / Tuning
– Explain plan
– Database profiler
• Geospatial
• Text Search
Agenda
3
VERSION 2.6
4
• Virtual Genius Bar
– Utilisez la fenêtre de chat
– Tug & Alain dispo
pendant, et après…
• MUGs à Paris, Toulouse,
Bordeaux, Rennes, Lyon
• Groupes LinkedIn
« MongoDB France » et
« MongoDB » sur
Viadeo
Q & A
@tgrall, tug@mongodb.com - @AlainHelaili, alain.helaili@mongodb.cm
Résumé des épisodes
précédents….
6
Inserts
• ObjectId()
• _id
• Durability
• WriteConcerns
• For updates too
>db.articles.insert({
'text': 'Article
content…’,
'date' : ISODate(...),
'title' : ’Intro to
MongoDB’,
'author' : 'Dan Roberts’,
'tags' : [
'mongodb',
'database',
'nosql’
]
});
options w: MAJORITY, j : true
7
Queries
• Comparison
operators
• projections
• cursors
operators
$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" }
8
Updates
• Manipulate
documents efficiently
• Bucketing
• Pre Aggregated
reports
• In place updates
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 }
)
Fondamentaux de l’indexation
10
• Plus important réglage dans la DB en matière de
performance (le schéma n’est pas un réglage).
– L’efficacité des index doit être examinée très tôt
– Eviter les duplications
– .
// index on author (ascending)
>db.articles.ensureIndex( { author : 1 } )
// index on title (descending)
>db.articles.ensureIndex( { title: -1 } )
// index on arrays of values – multi key index
>db.articles.ensureIndex( { tags : 1 } )
Fondamentaux
11
• Indexation des sous documents
– Utilisation de la dot-notation
Sous documents
{
‘_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 }
)
12
Index = Btree, O(log(n))
13
• Index utilisant de multiples attributs
Index composé (compound)
> db.articles.ensureIndex( { author : 1, tags : 1 } )
> db.articles.find( { author : ‘Dan Roberts’, tags : ‘MongoDB’} )
//et aussi
> db.articles.find( { author : ‘Dan Roberts’ } )
// Cet index est inutile
> db.articles.ensureIndex( { author : 1 } )
14
Index multiclés (multikey)
• Index utilisant de multiples valeurs
{ "_id" : ObjectId("..."), .. ,"tags" : [ "weather", "hot", "record", "april" ]}
> db.articles.ensureIndex( { tags : 1 } )
> db.articles.find( {tags : ‘record’} )
15
• Le tri n’a pas d’importance pour les index simples
– Lecture dans les deux sens du BTree
• { attribute: 1 } ou { attribute: -1 }
• Le tri est important pour les ‘compound indexes’
– Requête sur auteur, et tri par date
Ordre de tri
// index sur author croissant et décroissant sur date
>db.articles.ensureIndex( { ‘author’ : 1, ‘date’ -1 } )
16
• Retourne uniquement des données comprises
dans l’index
– Pas d’utilisation du fichier DB
– Performance optimale
– Valide pour les index composés
• Invoke with a projection
Requête couverte (covered)
> db.users.ensureIndex( { user : 1, password :1 } )
> db.user.find({user:"danr"}, {_id:0, password:1})
{ "password" : ”*********" }
Tip: utiliser les projections au maximum pour limiter
les quantités de données à acheminer vers le client
17
• TTL
– db.address.ensureIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )
– db.adress.ensureIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )
• Unique
– db.address.ensureIndex( { "user_id": 1 }, { unique: true } )
• Sparse
– db.address.ensureIndex( { ”etage": 1 }, { sparse: true } )
• Intersection
Autres concepts
18
• Permet d’évaluer l’efficactié des requêtes et index
– Quels index ont été utilisés… ou pas
– Combien de documents ou objets ont été scannés
– Utilisable via la console ou en code
Explication du plan d’exécution
//To view via the console
> db.articles.find({author:'Dan Roberts'}).sort({date:-1}).explain()
19
Sortie de la commande 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" :
….
Autres types:
• BasicCursor
• Full collection scan
• BtreeCursor
• GeoSearchCursor
• Complex Plan
• TextCursor
20
• Permet de logger les requêtes lentes
– Au-delà d’un temps d’exécution (défaut 100ms)
– Toutes les requêtes également
Profiler
//Enable database profiler on the console, 0=off 1=slow 2=all
> db.setProfilingLevel(1, 100)
{ "was" : 0, "slowms" : 100, "ok" : 1 }
//View profile with
> show profile
//or
>db.system.profile.find().pretty()
21
Sortie du profiler
{
"op" : "query",
"ns" : "test.articles",
"query" : {
"query" : {
"author" : "Dan Roberts"
},
"orderby" : {
"date" : -1
}
},
"ntoreturn" : 0,
"ntoskip" : 0,
"nscanned" : 1,
"nreturned" : 1,
……
Index Geo Spatiaux
23
• Index sur des champs geospatiaux
– Utilise le format GeoJSON
– Geometrie sur plans et spheres
2d et 2dSphere
//GeoJSON object structure for indexing
"location" : { "type" : "Point", "coordinates" : [ -0.128, 51.507 ] }
// Index on GeoJSON objects
>db.articles.ensureIndex( { location: “2dsphere” } )
24
Geo Capabilities
{loc: {type: "Point”,
coordinates: [ 40, 5 ] } }
{loc: {type: "LineString",
coordinates: [[40, 5], [41, 6]]}}
{loc : {type : "Polygon”,
coordinates : [[[0,0],[3,6],[6,1],[0,0]],
[[2,2],[3,3],[4,2],[2,2]]]}}
25
• $geoWithin, $geoIntersects, $near
• db.<collection>.find( { <location field> :
{ $geoWithin : { $box|$polygon|$center :
<coordinates> }}})
• db.<collection>.find( { <location field> :
{ $geoWithin : { $centerSphere : [ [ <x>,
<y> ] , <radius> ] } }})
Opérateurs
26
Extension de notre exemple
• Stockage du lieu
d’origine du post
• Geolocalisation
récupérée depuis le
navigateur
Collection article
>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 ]
}
});
//Javascript function to get geolocation.
navigator.geolocation.getCurrentPosition();
//You will need to translate into GeoJSON
27
– Requête et explain
Exemple
>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,
….
Text Search
29
• Permet la recherche de texte avec support
de :
• Stemming, languages, weighting, phrases et
aggregation framework
• Officiel en 2.6
Index text
30
Recherche texte
• Un seul index texte
par collection
• Operateur $** pour
indexer tous les
champs d’une
collection
• Utiliser les poids pour
modifier l’importance
des champs
>db.articles.ensureIndex(
{text :”text”}
)
>db.articles.ensureIndex(
{ "$**" : “text”,
name : “TextIndex”} )
>db.articles.ensureIndex(
{ "$**" : "text”},
{ weights :
{ ”title" : 10, ”text" : 5},
name : "TextIndex” }
)
Operators
$text, $search, $language,
$meta
31
• Utilisation de $text et $search pour requêter
• Retourne un curseur
• $meta pour la récupération du score
– .
// Search articles 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 }
Recherche texte
Résumé
33
• Indexing
– #1 pour l’amélioration de la performance….
• Durant le développement, n’oubliez pas
– Explain plan
– Database profiler
• Geospatial
• Text Search
Summary
34
– Reporting et Analytique
– Framework d’agrégation
Prochaine session – 22 Avril
2014 04-09-fr - app dev series - session 4 - indexing

Contenu connexe

Tendances

Webinaire 3 de la série « Retour aux fondamentaux » : Conception de schémas :...
Webinaire 3 de la série « Retour aux fondamentaux » : Conception de schémas :...Webinaire 3 de la série « Retour aux fondamentaux » : Conception de schémas :...
Webinaire 3 de la série « Retour aux fondamentaux » : Conception de schémas :...MongoDB
 
Les différents design patterns pour CoreData par Emmanuel Furnon
Les différents design patterns pour CoreData par Emmanuel FurnonLes différents design patterns pour CoreData par Emmanuel Furnon
Les différents design patterns pour CoreData par Emmanuel FurnonNicolas Lourenço
 
CocoaHeads Rennes #13 : Magical Record
CocoaHeads Rennes #13 : Magical RecordCocoaHeads Rennes #13 : Magical Record
CocoaHeads Rennes #13 : Magical RecordCocoaHeadsRNS
 
Design patterns et Design Emergeant - Micro Days - Modern Software Developmen...
Design patterns et Design Emergeant - Micro Days - Modern Software Developmen...Design patterns et Design Emergeant - Micro Days - Modern Software Developmen...
Design patterns et Design Emergeant - Micro Days - Modern Software Developmen...Tarik Zakaria Benmerar
 
Atelier : Développement rapide d&rsquo;une application basée surXWiki
Atelier : Développement rapide d&rsquo;une application basée surXWikiAtelier : Développement rapide d&rsquo;une application basée surXWiki
Atelier : Développement rapide d&rsquo;une application basée surXWikiKorteby Farouk
 
Webinaire 1 de la série Retour aux fondamentaux : Introduction à NoSQL
Webinaire 1 de la série Retour aux fondamentaux : Introduction à NoSQLWebinaire 1 de la série Retour aux fondamentaux : Introduction à NoSQL
Webinaire 1 de la série Retour aux fondamentaux : Introduction à NoSQLMongoDB
 
Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...
Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...
Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...Bruno Bonnin
 
MongoDB : la base NoSQL qui réinvente la gestion de données
MongoDB : la base NoSQL qui réinvente la gestion de donnéesMongoDB : la base NoSQL qui réinvente la gestion de données
MongoDB : la base NoSQL qui réinvente la gestion de donnéesSOAT
 
Construisez votre première application MongoDB
Construisez votre première application MongoDBConstruisez votre première application MongoDB
Construisez votre première application MongoDBMongoDB
 
Présentation de ElasticSearch / Digital apéro du 12/11/2014
Présentation de ElasticSearch / Digital apéro du 12/11/2014Présentation de ElasticSearch / Digital apéro du 12/11/2014
Présentation de ElasticSearch / Digital apéro du 12/11/2014Silicon Comté
 
Jug algeria x wiki-atelier
Jug algeria x wiki-atelierJug algeria x wiki-atelier
Jug algeria x wiki-atelierAlgeria JUG
 
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...MongoDB
 
Journées SQL Server 2011 Extended Events
Journées SQL Server 2011  Extended Events Journées SQL Server 2011  Extended Events
Journées SQL Server 2011 Extended Events David BAFFALEUF
 
Des mises à jour? Emmenez votre application Stitch encore plus loin grâce aux...
Des mises à jour? Emmenez votre application Stitch encore plus loin grâce aux...Des mises à jour? Emmenez votre application Stitch encore plus loin grâce aux...
Des mises à jour? Emmenez votre application Stitch encore plus loin grâce aux...MongoDB
 
CocoaHeads Rennes #3 : Bien débuter sur iOS
CocoaHeads Rennes #3 : Bien débuter sur iOSCocoaHeads Rennes #3 : Bien débuter sur iOS
CocoaHeads Rennes #3 : Bien débuter sur iOSCocoaHeadsRNS
 
Guide (un tout petit peu) pratique (et totalement subjectif) du stream proces...
Guide (un tout petit peu) pratique (et totalement subjectif) du stream proces...Guide (un tout petit peu) pratique (et totalement subjectif) du stream proces...
Guide (un tout petit peu) pratique (et totalement subjectif) du stream proces...Bruno Bonnin
 

Tendances (20)

Webinaire 3 de la série « Retour aux fondamentaux » : Conception de schémas :...
Webinaire 3 de la série « Retour aux fondamentaux » : Conception de schémas :...Webinaire 3 de la série « Retour aux fondamentaux » : Conception de schémas :...
Webinaire 3 de la série « Retour aux fondamentaux » : Conception de schémas :...
 
Les différents design patterns pour CoreData par Emmanuel Furnon
Les différents design patterns pour CoreData par Emmanuel FurnonLes différents design patterns pour CoreData par Emmanuel Furnon
Les différents design patterns pour CoreData par Emmanuel Furnon
 
CocoaHeads Rennes #13 : Magical Record
CocoaHeads Rennes #13 : Magical RecordCocoaHeads Rennes #13 : Magical Record
CocoaHeads Rennes #13 : Magical Record
 
Crud
CrudCrud
Crud
 
Design patterns et Design Emergeant - Micro Days - Modern Software Developmen...
Design patterns et Design Emergeant - Micro Days - Modern Software Developmen...Design patterns et Design Emergeant - Micro Days - Modern Software Developmen...
Design patterns et Design Emergeant - Micro Days - Modern Software Developmen...
 
Atelier : Développement rapide d&rsquo;une application basée surXWiki
Atelier : Développement rapide d&rsquo;une application basée surXWikiAtelier : Développement rapide d&rsquo;une application basée surXWiki
Atelier : Développement rapide d&rsquo;une application basée surXWiki
 
Webinaire 1 de la série Retour aux fondamentaux : Introduction à NoSQL
Webinaire 1 de la série Retour aux fondamentaux : Introduction à NoSQLWebinaire 1 de la série Retour aux fondamentaux : Introduction à NoSQL
Webinaire 1 de la série Retour aux fondamentaux : Introduction à NoSQL
 
Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...
Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...
Breizhcamp 2015 - Comment (ne pas réussir à) modéliser ses data dans elastics...
 
Pg jsonb format 16-9
Pg jsonb format 16-9Pg jsonb format 16-9
Pg jsonb format 16-9
 
MongoDB : la base NoSQL qui réinvente la gestion de données
MongoDB : la base NoSQL qui réinvente la gestion de donnéesMongoDB : la base NoSQL qui réinvente la gestion de données
MongoDB : la base NoSQL qui réinvente la gestion de données
 
Construisez votre première application MongoDB
Construisez votre première application MongoDBConstruisez votre première application MongoDB
Construisez votre première application MongoDB
 
Présentation de ElasticSearch / Digital apéro du 12/11/2014
Présentation de ElasticSearch / Digital apéro du 12/11/2014Présentation de ElasticSearch / Digital apéro du 12/11/2014
Présentation de ElasticSearch / Digital apéro du 12/11/2014
 
Jug algeria x wiki-atelier
Jug algeria x wiki-atelierJug algeria x wiki-atelier
Jug algeria x wiki-atelier
 
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...
Webinaire 5 de la série « Retour aux fondamentaux » : Introduction à Aggregat...
 
Introduction au Jquery
Introduction au JqueryIntroduction au Jquery
Introduction au Jquery
 
Mongodb102
Mongodb102Mongodb102
Mongodb102
 
Journées SQL Server 2011 Extended Events
Journées SQL Server 2011  Extended Events Journées SQL Server 2011  Extended Events
Journées SQL Server 2011 Extended Events
 
Des mises à jour? Emmenez votre application Stitch encore plus loin grâce aux...
Des mises à jour? Emmenez votre application Stitch encore plus loin grâce aux...Des mises à jour? Emmenez votre application Stitch encore plus loin grâce aux...
Des mises à jour? Emmenez votre application Stitch encore plus loin grâce aux...
 
CocoaHeads Rennes #3 : Bien débuter sur iOS
CocoaHeads Rennes #3 : Bien débuter sur iOSCocoaHeads Rennes #3 : Bien débuter sur iOS
CocoaHeads Rennes #3 : Bien débuter sur iOS
 
Guide (un tout petit peu) pratique (et totalement subjectif) du stream proces...
Guide (un tout petit peu) pratique (et totalement subjectif) du stream proces...Guide (un tout petit peu) pratique (et totalement subjectif) du stream proces...
Guide (un tout petit peu) pratique (et totalement subjectif) du stream proces...
 

En vedette

Webinar: Replication and Replica Sets
Webinar: Replication and Replica SetsWebinar: Replication and Replica Sets
Webinar: Replication and Replica SetsMongoDB
 
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based Sharding
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based ShardingWebinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based Sharding
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based ShardingMongoDB
 
Schema Design
Schema DesignSchema Design
Schema DesignMongoDB
 
Advanced Replication
Advanced ReplicationAdvanced Replication
Advanced ReplicationMongoDB
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
 

En vedette (6)

Webinar: Replication and Replica Sets
Webinar: Replication and Replica SetsWebinar: Replication and Replica Sets
Webinar: Replication and Replica Sets
 
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based Sharding
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based ShardingWebinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based Sharding
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based Sharding
 
Schema Design
Schema DesignSchema Design
Schema Design
 
Advanced Replication
Advanced ReplicationAdvanced Replication
Advanced Replication
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 

Similaire à 2014 04-09-fr - app dev series - session 4 - indexing

Retour aux fondamentaux : Penser en termes de documents
Retour aux fondamentaux : Penser en termes de documentsRetour aux fondamentaux : Penser en termes de documents
Retour aux fondamentaux : Penser en termes de documentsMongoDB
 
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp012014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01MongoDB
 
Hands on lab Elasticsearch
Hands on lab ElasticsearchHands on lab Elasticsearch
Hands on lab ElasticsearchDavid Pilato
 
Lausanne JUG - Elasticsearch
Lausanne JUG - ElasticsearchLausanne JUG - Elasticsearch
Lausanne JUG - ElasticsearchDavid Pilato
 
Mettez du temps réel dans votre Drupal avec Node JS
Mettez du temps réel dans votre Drupal avec Node JSMettez du temps réel dans votre Drupal avec Node JS
Mettez du temps réel dans votre Drupal avec Node JSMatthieu Guillermin
 
Azure Camp 9 Décembre - slides session développeurs webmedia
Azure Camp 9 Décembre - slides session développeurs webmediaAzure Camp 9 Décembre - slides session développeurs webmedia
Azure Camp 9 Décembre - slides session développeurs webmediaMicrosoft
 
Lyon JUG - Elasticsearch
Lyon JUG - ElasticsearchLyon JUG - Elasticsearch
Lyon JUG - ElasticsearchDavid Pilato
 
Microservices-DDD-Telosys-Devoxx-FR-2022
Microservices-DDD-Telosys-Devoxx-FR-2022Microservices-DDD-Telosys-Devoxx-FR-2022
Microservices-DDD-Telosys-Devoxx-FR-2022Laurent Guérin
 
Présentation mongoDB et mongoId
Présentation mongoDB et mongoIdPrésentation mongoDB et mongoId
Présentation mongoDB et mongoIdvtabary
 
ch5_indexation.pdf
ch5_indexation.pdfch5_indexation.pdf
ch5_indexation.pdfnihedattia2
 
JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDB
JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDBJugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDB
JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDBSébastien Prunier
 
SSL 2011 : Présentation de 2 bases noSQL
SSL 2011 : Présentation de 2 bases noSQLSSL 2011 : Présentation de 2 bases noSQL
SSL 2011 : Présentation de 2 bases noSQLHervé Leclerc
 
Elasticsearch - OSDC France 2012
Elasticsearch - OSDC France 2012Elasticsearch - OSDC France 2012
Elasticsearch - OSDC France 2012David Pilato
 
Devoxx: Tribulation d'un développeur sur le Cloud
Devoxx: Tribulation d'un développeur sur le CloudDevoxx: Tribulation d'un développeur sur le Cloud
Devoxx: Tribulation d'un développeur sur le CloudTugdual Grall
 
MongoDB_presentation_ye.pptx
MongoDB_presentation_ye.pptxMongoDB_presentation_ye.pptx
MongoDB_presentation_ye.pptxZALIMAZA
 
MongoDB_presentation_tts.pptx
MongoDB_presentation_tts.pptxMongoDB_presentation_tts.pptx
MongoDB_presentation_tts.pptxZALIMAZA
 
Cours j query-id1575
Cours j query-id1575Cours j query-id1575
Cours j query-id1575kate2013
 
MongoDB_presentation_Moyou.pptx
MongoDB_presentation_Moyou.pptxMongoDB_presentation_Moyou.pptx
MongoDB_presentation_Moyou.pptxZALIMAZA
 
Elasticsearch - Montpellier JUG
Elasticsearch - Montpellier JUGElasticsearch - Montpellier JUG
Elasticsearch - Montpellier JUGDavid Pilato
 

Similaire à 2014 04-09-fr - app dev series - session 4 - indexing (20)

Retour aux fondamentaux : Penser en termes de documents
Retour aux fondamentaux : Penser en termes de documentsRetour aux fondamentaux : Penser en termes de documents
Retour aux fondamentaux : Penser en termes de documents
 
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp012014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01
2014 03-26-appdevseries-session3-interactingwiththedatabase-fr-phpapp01
 
Hands on lab Elasticsearch
Hands on lab ElasticsearchHands on lab Elasticsearch
Hands on lab Elasticsearch
 
Introduction à node.js
Introduction à node.js Introduction à node.js
Introduction à node.js
 
Lausanne JUG - Elasticsearch
Lausanne JUG - ElasticsearchLausanne JUG - Elasticsearch
Lausanne JUG - Elasticsearch
 
Mettez du temps réel dans votre Drupal avec Node JS
Mettez du temps réel dans votre Drupal avec Node JSMettez du temps réel dans votre Drupal avec Node JS
Mettez du temps réel dans votre Drupal avec Node JS
 
Azure Camp 9 Décembre - slides session développeurs webmedia
Azure Camp 9 Décembre - slides session développeurs webmediaAzure Camp 9 Décembre - slides session développeurs webmedia
Azure Camp 9 Décembre - slides session développeurs webmedia
 
Lyon JUG - Elasticsearch
Lyon JUG - ElasticsearchLyon JUG - Elasticsearch
Lyon JUG - Elasticsearch
 
Microservices-DDD-Telosys-Devoxx-FR-2022
Microservices-DDD-Telosys-Devoxx-FR-2022Microservices-DDD-Telosys-Devoxx-FR-2022
Microservices-DDD-Telosys-Devoxx-FR-2022
 
Présentation mongoDB et mongoId
Présentation mongoDB et mongoIdPrésentation mongoDB et mongoId
Présentation mongoDB et mongoId
 
ch5_indexation.pdf
ch5_indexation.pdfch5_indexation.pdf
ch5_indexation.pdf
 
JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDB
JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDBJugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDB
JugSummerCamp 2013 - Un backend NoSQL pour Geektic avec MongoDB
 
SSL 2011 : Présentation de 2 bases noSQL
SSL 2011 : Présentation de 2 bases noSQLSSL 2011 : Présentation de 2 bases noSQL
SSL 2011 : Présentation de 2 bases noSQL
 
Elasticsearch - OSDC France 2012
Elasticsearch - OSDC France 2012Elasticsearch - OSDC France 2012
Elasticsearch - OSDC France 2012
 
Devoxx: Tribulation d'un développeur sur le Cloud
Devoxx: Tribulation d'un développeur sur le CloudDevoxx: Tribulation d'un développeur sur le Cloud
Devoxx: Tribulation d'un développeur sur le Cloud
 
MongoDB_presentation_ye.pptx
MongoDB_presentation_ye.pptxMongoDB_presentation_ye.pptx
MongoDB_presentation_ye.pptx
 
MongoDB_presentation_tts.pptx
MongoDB_presentation_tts.pptxMongoDB_presentation_tts.pptx
MongoDB_presentation_tts.pptx
 
Cours j query-id1575
Cours j query-id1575Cours j query-id1575
Cours j query-id1575
 
MongoDB_presentation_Moyou.pptx
MongoDB_presentation_Moyou.pptxMongoDB_presentation_Moyou.pptx
MongoDB_presentation_Moyou.pptx
 
Elasticsearch - Montpellier JUG
Elasticsearch - Montpellier JUGElasticsearch - Montpellier JUG
Elasticsearch - Montpellier JUG
 

Plus de 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
 

Plus de 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 04-09-fr - app dev series - session 4 - indexing

  • 1. Tugdual Grall (@tgrall) Alain Hélaïli (@AlainHelaili) #MongoDBBasics @MongoDB Construire une application avec MongoDB Stratégies et options d’indexation
  • 2. 2 • Résumé des épisodes précédents • Fondamentaux de l’indexation – Types d’index dans notre application – Compound index – Covered index • Evaluation / Tuning – Explain plan – Database profiler • Geospatial • Text Search Agenda
  • 4. 4 • Virtual Genius Bar – Utilisez la fenêtre de chat – Tug & Alain dispo pendant, et après… • MUGs à Paris, Toulouse, Bordeaux, Rennes, Lyon • Groupes LinkedIn « MongoDB France » et « MongoDB » sur Viadeo Q & A @tgrall, tug@mongodb.com - @AlainHelaili, alain.helaili@mongodb.cm
  • 6. 6 Inserts • ObjectId() • _id • Durability • WriteConcerns • For updates too >db.articles.insert({ 'text': 'Article content…’, 'date' : ISODate(...), 'title' : ’Intro to MongoDB’, 'author' : 'Dan Roberts’, 'tags' : [ 'mongodb', 'database', 'nosql’ ] }); options w: MAJORITY, j : true
  • 7. 7 Queries • Comparison operators • projections • cursors operators $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" }
  • 8. 8 Updates • Manipulate documents efficiently • Bucketing • Pre Aggregated reports • In place updates 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 } )
  • 10. 10 • Plus important réglage dans la DB en matière de performance (le schéma n’est pas un réglage). – L’efficacité des index doit être examinée très tôt – Eviter les duplications – . // index on author (ascending) >db.articles.ensureIndex( { author : 1 } ) // index on title (descending) >db.articles.ensureIndex( { title: -1 } ) // index on arrays of values – multi key index >db.articles.ensureIndex( { tags : 1 } ) Fondamentaux
  • 11. 11 • Indexation des sous documents – Utilisation de la dot-notation Sous documents { ‘_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 } )
  • 12. 12 Index = Btree, O(log(n))
  • 13. 13 • Index utilisant de multiples attributs Index composé (compound) > db.articles.ensureIndex( { author : 1, tags : 1 } ) > db.articles.find( { author : ‘Dan Roberts’, tags : ‘MongoDB’} ) //et aussi > db.articles.find( { author : ‘Dan Roberts’ } ) // Cet index est inutile > db.articles.ensureIndex( { author : 1 } )
  • 14. 14 Index multiclés (multikey) • Index utilisant de multiples valeurs { "_id" : ObjectId("..."), .. ,"tags" : [ "weather", "hot", "record", "april" ]} > db.articles.ensureIndex( { tags : 1 } ) > db.articles.find( {tags : ‘record’} )
  • 15. 15 • Le tri n’a pas d’importance pour les index simples – Lecture dans les deux sens du BTree • { attribute: 1 } ou { attribute: -1 } • Le tri est important pour les ‘compound indexes’ – Requête sur auteur, et tri par date Ordre de tri // index sur author croissant et décroissant sur date >db.articles.ensureIndex( { ‘author’ : 1, ‘date’ -1 } )
  • 16. 16 • Retourne uniquement des données comprises dans l’index – Pas d’utilisation du fichier DB – Performance optimale – Valide pour les index composés • Invoke with a projection Requête couverte (covered) > db.users.ensureIndex( { user : 1, password :1 } ) > db.user.find({user:"danr"}, {_id:0, password:1}) { "password" : ”*********" } Tip: utiliser les projections au maximum pour limiter les quantités de données à acheminer vers le client
  • 17. 17 • TTL – db.address.ensureIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } ) – db.adress.ensureIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } ) • Unique – db.address.ensureIndex( { "user_id": 1 }, { unique: true } ) • Sparse – db.address.ensureIndex( { ”etage": 1 }, { sparse: true } ) • Intersection Autres concepts
  • 18. 18 • Permet d’évaluer l’efficactié des requêtes et index – Quels index ont été utilisés… ou pas – Combien de documents ou objets ont été scannés – Utilisable via la console ou en code Explication du plan d’exécution //To view via the console > db.articles.find({author:'Dan Roberts'}).sort({date:-1}).explain()
  • 19. 19 Sortie de la commande 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" : …. Autres types: • BasicCursor • Full collection scan • BtreeCursor • GeoSearchCursor • Complex Plan • TextCursor
  • 20. 20 • Permet de logger les requêtes lentes – Au-delà d’un temps d’exécution (défaut 100ms) – Toutes les requêtes également Profiler //Enable database profiler on the console, 0=off 1=slow 2=all > db.setProfilingLevel(1, 100) { "was" : 0, "slowms" : 100, "ok" : 1 } //View profile with > show profile //or >db.system.profile.find().pretty()
  • 21. 21 Sortie du profiler { "op" : "query", "ns" : "test.articles", "query" : { "query" : { "author" : "Dan Roberts" }, "orderby" : { "date" : -1 } }, "ntoreturn" : 0, "ntoskip" : 0, "nscanned" : 1, "nreturned" : 1, ……
  • 23. 23 • Index sur des champs geospatiaux – Utilise le format GeoJSON – Geometrie sur plans et spheres 2d et 2dSphere //GeoJSON object structure for indexing "location" : { "type" : "Point", "coordinates" : [ -0.128, 51.507 ] } // Index on GeoJSON objects >db.articles.ensureIndex( { location: “2dsphere” } )
  • 24. 24 Geo Capabilities {loc: {type: "Point”, coordinates: [ 40, 5 ] } } {loc: {type: "LineString", coordinates: [[40, 5], [41, 6]]}} {loc : {type : "Polygon”, coordinates : [[[0,0],[3,6],[6,1],[0,0]], [[2,2],[3,3],[4,2],[2,2]]]}}
  • 25. 25 • $geoWithin, $geoIntersects, $near • db.<collection>.find( { <location field> : { $geoWithin : { $box|$polygon|$center : <coordinates> }}}) • db.<collection>.find( { <location field> : { $geoWithin : { $centerSphere : [ [ <x>, <y> ] , <radius> ] } }}) Opérateurs
  • 26. 26 Extension de notre exemple • Stockage du lieu d’origine du post • Geolocalisation récupérée depuis le navigateur Collection article >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 ] } }); //Javascript function to get geolocation. navigator.geolocation.getCurrentPosition(); //You will need to translate into GeoJSON
  • 27. 27 – Requête et explain Exemple >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, ….
  • 29. 29 • Permet la recherche de texte avec support de : • Stemming, languages, weighting, phrases et aggregation framework • Officiel en 2.6 Index text
  • 30. 30 Recherche texte • Un seul index texte par collection • Operateur $** pour indexer tous les champs d’une collection • Utiliser les poids pour modifier l’importance des champs >db.articles.ensureIndex( {text :”text”} ) >db.articles.ensureIndex( { "$**" : “text”, name : “TextIndex”} ) >db.articles.ensureIndex( { "$**" : "text”}, { weights : { ”title" : 10, ”text" : 5}, name : "TextIndex” } ) Operators $text, $search, $language, $meta
  • 31. 31 • Utilisation de $text et $search pour requêter • Retourne un curseur • $meta pour la récupération du score – . // Search articles 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 } Recherche texte
  • 33. 33 • Indexing – #1 pour l’amélioration de la performance…. • Durant le développement, n’oubliez pas – Explain plan – Database profiler • Geospatial • Text Search Summary
  • 34. 34 – Reporting et Analytique – Framework d’agrégation Prochaine session – 22 Avril