Upcoming SlideShare
×

# Indexing and Query Optimizer (Aaron Staple)

10,033 views
9,889 views

Published on

Published in: Technology
36 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
•
Are you sure you want to  Yes  No
• Congratulations! It's very interactive and easy to understand. Thanks.

Are you sure you want to  Yes  No
Views
Total views
10,033
On SlideShare
0
From Embeds
0
Number of Embeds
392
Actions
Shares
0
366
2
Likes
36
Embeds 0
No embeds

No notes for slide

### Indexing and Query Optimizer (Aaron Staple)

1. 1. IndicesQuery OptimizerPerformance Tuning<br />Aaron Staple aaron@10gen.com<br />
2. 2. What is an index?<br />A set of references to your documents, efficiently ordered by key<br />{x:0.5,y:0.5}<br />{x:2,y:0.5}<br />{x:5,y:2}<br />{x:-4,y:10}<br />{x:3,y:’f’}<br />
3. 3. What is an index?<br />A set of references to your documents, efficiently ordered by key<br />{x:1}<br />{x:0.5,y:0.5}<br />{x:2,y:0.5}<br />{x:5,y:2}<br />{x:-4,y:10}<br />{x:3,y:’f’}<br />
4. 4. What is an index?<br />A set of references to your documents, efficiently ordered by key<br />{y:1}<br />{x:0.5,y:0.5}<br />{x:2,y:0.5}<br />{x:5,y:2}<br />{x:-4,y:10}<br />{x:3,y:’f’}<br />
5. 5. How is an index stored?<br />B-tree<br />{x:2}<br />{x:3}<br />3<=x<4<br />4<=x<5<br />{x:0.5}<br />2<=x<5<br />{x:5}<br />0<=x<1<br />x>=5<br />x<0<br />{x:-4}<br />{x:1}<br />
6. 6. What if I have multiple indices?<br />{c:1}<br />{a:3}<br />{c:2}<br />{c:3}<br />{b:’x’}<br />{d:null}<br />{<br />a:3,<br />b:’x’,<br />c:[1,2,3]<br />}<br />{a:1}<br />{c:1}<br />{b:1}<br />{d:1}<br />
7. 7. How does a simple query work?<br />Tree traversal<br />{x:2}<br />{x:3}<br />3<=x<4<br />4<=x<5<br />{x:0.5}<br />2<=x<5<br />{x:5}<br />0<=x<1<br />x>=5<br />x<0<br />{x:-4}<br />{x:1}<br />
8. 8. Simple document lookup <br />db.c.findOne( {_id:2} ), using index {_id:1}<br />db.c.find( {x:2} ), using index {x:1}<br />db.c.find( {x:{\$in:[2,3]}} ), using index {x:1}<br />db.c.find( {‘x.a’:1} ), using index {‘x.a’:1}<br />Matches {_id:1,x:{a:1}}<br />db.c.find( {x:{a:1}} ), using index {x:1}<br />Matches {_id:1,x:{a:1}}, but not {_id:2,x:{a:1,b:2}}<br />QUESTION: What about db.c.find( {\$where:“this.x == this.y”} ), using index {x:1}?<br />Indices cannot be used for \$where type queries, but if there are non-where elements in the query then indices can be used for the non-where elements.<br />
9. 9. How does a range query work?<br />Tree traversal + scan: find({x:{\$gte:3,\$lte:5}})<br />{x:2}<br />{x:3}<br />{x:4}<br />3<=x<4<br />4<=x<5<br />{x:0.5}<br />2<=x<5<br />{x:5}<br />0<=x<1<br />{x:6}<br />x>=5<br />x<0<br />{x:-4}<br />{x:1}<br />
10. 10. Document range scan<br />db.c.find( {x:{\$gt:2}} ), using index {x:1}<br />db.c.find( {x:{\$gt:2,\$lt:5}} ), using index {x:1}<br />db.c.find( {x:/^a/} ), using index {x:1}<br />QUESTION: What about db.c.find( {x:/a/} ), using index {x:1}?<br />The letter ‘a’ can appear anywhere in a matching string, so lexicographic ordering on strings won’t help. However, we can use the index to find the range of documents where x is string (eg not a number) or x is the regular expression /a/.<br />
11. 11. Other operations<br />db.c.count( {x:2} ) using index {x:1}<br />db.c.distinct( {x:2} ) using index {x:1}<br />db.c.update( {x:2}, {x:3} ) using index {x:1}<br />db.c.remove( {x:2} ) using index {x:1}<br />QUESTION: What about db.c.update( {x:2}, {\$inc:{x:3}} ), using index {x:1}?<br />Older versions of mongoDB didn’t support modifiers on indexed fields, but we now support this.<br />
12. 12. Missing fields<br />db.c.find( {x:null} ), using index {x:1}<br />Matches {_id:5}<br />Matches {_id:5,x:null}<br />QUESTION: What about db.c.find( {x:{\$exists:true}} ), using index {x:1}?<br />The index is not currently used, though we will fix this in MongoDB 1.6.<br />
13. 13. Array matching<br />All the following match {_id:6,x:[2,10]} and use index {x:1}<br />db.c.find( {x:2} )<br />db.c.find( {x:10} )<br />db.c.find( {x:{\$gt:5}} )<br />db.c.find( {x:[2,10]} )<br />db.c.find( {x:{\$in:[2,5]}} )<br />QUESTION: What about db.c.find( {x:{\$all:[2,10]}} )?<br />The index will be used to look up all documents matching {x:2}.<br />
14. 14. What is a compound index?<br />{x:2,y:3}<br />{x:1,y:5}<br />{x:2,y:9}<br />{x:3,y:1}<br />{x:1,y:1}<br />
15. 15. How are bounds determined for a compound index?<br />find( {x:{\$gte:2,\$lte:4},y:6} )<br />{x:3,y:1}<br />{x:2,y:6}<br />{x:3,y:7}<br />{x:3.5,y:6}<br />{x:2,y:3}<br />{x:4,y:6}<br />{x:1,y:5}<br />{x:5,y:6}<br />{x:1,y:1}<br />
16. 16. How does an ordered range query work?<br />Simple range scan if index already ensures desired ordering: find( {x:2} ).sort( {y:1} )<br />{x:2,y:3}<br />{x:1,y:5}<br />{x:2,y:9}<br />{x:3,y:1}<br />{x:1,y:1}<br />
17. 17. How does an ordered range query work?<br />Otherwise, in-memory sort of matching documents: find( {x:2} ).sort( {y:1} )<br />{x:2,y:3}<br />{x:2,y:9}<br />{x:1,y:5}<br />{x:2,y:3}<br />{x:2,y:9}<br />…<br />{x:3,y:1}<br />{x:1}<br />
18. 18. Document ordering<br />db.c.find( {} ).sort( {x:1} ), using index {x:1}<br />db.c.find( {} ).sort( {x:-1} ), using index {x:1}<br />db.c.find( {x:{\$gt:4}} ).sort( {x:-1} ), using index {x:1}<br />db.c.find( {} ).sort( {‘x.a’:1} ), using index {‘x.a’:1}<br />QUESTION: What about db.c.find( {y:1} ).sort( {x:1} ), using index {x:1}?<br />The index will be used to ensure ordering, provided there is no better index.<br />
19. 19. Compound indices and ordering<br />db.c.find( {x:10,y:20} ), using index {x:1,y:1}<br />db.c.find( {x:10,y:20} ), using index {x:1,y:-1}<br />db.c.find( {x:{\$in:[10,20]},y:20} ), using index {x:1,y:1}<br />db.c.find().sort( {x:1,y:1} ), using index {x:1,y:1}<br />db.c.find().sort( {x:-1,y:1} ), using index {x:1,y:-1}<br />db.c.find( {x:10} ).sort( {y:1} ), using index {x:1,y:1}<br />QUESTION: What about db.c.find( {y:10} ).sort( {x:1} ), using index {x:1,y:1}?<br />The index will be used to ensure ordering, provided no better index is available.<br />
20. 20. What if we negate a query?<br />find({x:{\$ne:2}})<br />{x:2}<br />{x:1}<br />{x:2}<br />{x:3}<br />{x:1}<br />
21. 21. When indices are less helpful<br />db.c.find( {x:{\$ne:1}} )<br />db.c.find( {x:{\$mod:[10,1]}} )<br />Uses index {x:1} to scan numbers only<br />db.c.find( {x:{\$not:/a/}} )<br />db.c.find( {x:{\$gte:0,\$lte:10},y:5} ) using index {x:1,y:1}<br />Currently must scan all elements from {x:0,y:5} to {x:10,y:5}, but some improvements may be possible<br />db.c.find( {\$where:’this.x = 5’} )<br />QUESTION: What about db.c.find( {x:{\$not:/^a/}} ), using index {x:1}?<br />The index is not used currently, but will be used in mongoDB 1.6<br />
22. 22. How is an index chosen?<br />find( {x:2,y:3} )<br />{x:2,y:1}<br />{y:3,x:1}<br />{x:2,y:3}<br />{x:2,y:9}<br />{y:3,x:2}<br />{y:9,x:2}<br />{x:1,y:3}<br />{y:1,x:2}<br />{x:1}<br />{y:1}<br />√<br />{x:2,y:3}<br />{x:2,y:1}<br />{x:2,y:9}<br />{y:3,x:2}<br />{y:3,x:1}<br />
23. 23. Query pattern matching<br />Very simple algorithm, few complaints so far<br />find({x:1})<br />find({x:2})<br />find({x:100})<br />find({x:{\$gt:4}})<br />find({x:{\$gte:6}})<br />find({x:1,y:2})<br />find({x:{\$gt:4,\$lte:10}})<br />find({x:{\$gte:6,\$lte:400}})<br />find({x:1}).sort({y:1})<br />
24. 24. Query optimizer<br />In charge of picking which index to use for a query/count/update/delete/etc<br />Usually it does a good job, but if you know what you’re doing you can override it<br />db.c.find( {x:2,y:3} ).hint( {y:1} )<br />Use index {y:1} and avoid trying {x:1}<br />As your data changes, different indices may be chosen. Ordering requirements should be made explicit using sort().<br />QUESTION: How can you force a full collection scan instead of using indices?<br />db.c.find( {x:2,y:3} ).hint( {\$natural:1} ) to bypass indices<br />
25. 25. Geospatial indices<br />db.c.find( {a:[50,50]} ) using index {a:’2d’}<br />db.c.find( {a:{\$near:[50,50]}} ) using index {a:’2d’}<br />Results are sorted closest - farthest<br />db.c.find( {a:{\$within:{\$box:[[40,40],[60,60]]}}} ) using index {a:’2d’}<br />db.c.find( {a:{\$within:{\$center:[[50,50],10]}}} ) using index {a:’2d’}<br />db.c.find( {a:{\$near:[50,50]},b:2} ) using index {a:’2d’,b:1}<br />QUESTION: Most queries can be performed with or without an index. Is this true of geospatial queries?<br />No. A geospatial query requires an index.<br />
26. 26. How does an insert work?<br />Tree traversal and insert, split if necessary<br />{x:3.5}<br />{x:2}<br />{x:3}<br />{x:4}<br />3<=x<4<br />4<=x<5<br />{x:0.5}<br />2<=x<5<br />{x:5}<br />0<=x<1<br />{x:6}<br />x>=5<br />x<0<br />{x:-4}<br />{x:1}<br />
27. 27. What if my keys are increasing?<br />You’ll always insert on the right<br />{x:2}<br />{x:3}<br />{x:4}<br />3<=x<4<br />4<=x<5<br />{x:0.5}<br />2<=x<5<br />{x:5}<br />0<=x<1<br />{x:6}<br />x>=5<br />x<0<br />{x:7}<br />{x:-4}<br />{x:8}<br />{x:1}<br />{x:9}<br />
28. 28. Why is RAM important?<br />RAM is basically used as a LIFO disk cache<br />Whole index in RAM<br />Portion of index in RAM<br />
29. 29. Creating an index<br />{_id:1} index created automatically<br />For non-capped collections<br />db.c.ensureIndex( {x:1} )<br />Can create an index at any time, even when you already have plenty of data in your collection<br />Creating an index will block mongoDB unless you specify background index creation<br />db.c.ensureIndex( {x:1}, {background:true} )<br />Background index creation is a still impacts performance – run at non peak times if you’re concerned<br />QUESTION: Can an index be removed during background creation?<br />Not at this time.<br />
30. 30. Unique key constraints<br />db.c.ensureIndex( {x:1}, {unique:true} )<br />Don’t allow {_id:10,x:2} and {_id:11,x:2}<br />Don’t allow {_id:12} and {_id:13} (both match {x:null}<br />What if duplicates exist before index is created?<br />Normally index creation fails and the index is removed<br />db.ensureIndex( {x:1}, {unique:true,dropDups:true} )<br />QUESTION: In dropDups mode, which duplicates will be removed?<br />The first document according to the collection’s “natural order” will be preserved.<br />
31. 31. Cleaning up an index<br />db.system.indices.find( {ns:’db.c’} )<br />db.c.dropIndex( {x:1} )<br />db.c.dropindices()<br />db.c.reIndex()<br />Rebuilds all indices, removing index cruft that has built up over large numbers of updates and deletes. Index cruft will not exist in mongoDB 1.6, so this command will be deprecated.<br />QUESTION: Why would you want to drop an index?<br />See next slide…<br />
32. 32. Limits and tradeoffs<br />Max 40 indices per collection<br />Logically equivalent indices are not prevented (eg {x:1} and {x:-1})<br />indices can improve speed of queries, but make inserts slower<br />A more specific index {a:1,b:1,c:1} can be more helpful than less specific index {a:1} but the more specific index will be larger, thus harder to fit in RAM<br />QUESTION: Do indices make updates slower? How about deletes?<br />It depends – finding your document might be faster, but if any indexed fields are changed the indices must be updated.<br />
33. 33. Mongod log output<br />query test.c ntoreturn:1 reslen:69 nscanned:100000 { i: 99999.0 } nreturned:1 157ms<br />query test.\$cmd ntoreturn:1 command: { count: "c", query: { type: 0.0, i: { \$gt: 99000.0 } }, fields: {} } reslen:64 256ms<br />query:{ query: {}, orderby: { i: 1.0 } } ... query test.c ntoreturn:0 exception 1378ms ... User Exception 10128:too much key data for sort() with no index. add an index or specify a smaller limit<br />query test.c ntoreturn:0 reslen:4783 nscanned:100501 { query: { type: 500.0 }, orderby: { i: 1.0 } } nreturned:101 390ms<br />Occasionally may see a slow operation as a result of disk activity or mongo cleaning things up – some messages about slow ops are spurious<br />Keep this in mind when running the same op a massive number of times, and it appears slow very rarely<br />
34. 34. Profiling<br />Record same info as with log messages, but in a database collection<br />> db.system.profile.find()<br />{"ts" : "Thu Jan 29 2009 15:19:32 GMT-0500 (EST)" , "info" : "query test.\$cmd ntoreturn:1 reslen:66 nscanned:0 <br>query: { profile: 2 } nreturned:1 bytes:50" , "millis" : 0}...<br />> db.system.profile.find( { info: /test.foo/ } )<br />> db.system.profile.find( { millis : { \$gt : 5 } } )<br />> db.system.profile.find().sort({\$natural:-1})<br />Enable explicitly using levels (0:off, 1:slow ops (>100ms), 2:all ops)<br />> db.setProfilingLevel(2);<br />{"was" : 0 , "ok" : 1}<br />> db.getProfilingLevel()<br />2<br />> db.setProfilingLevel( 1 , 10 ); // slow means > 10ms<br />Profiling impacts performance, but not severely<br />
35. 35. Query explain<br />> db.c.find( {x:1000,y:0} ).explain()<br />{<br /> "cursor" : "BtreeCursor x_1",<br /> "indexBounds" : [<br /> [<br /> {<br /> "x" : 1000<br /> },<br /> {<br /> "x" : 1000<br /> }<br /> ]<br /> ],<br /> "nscanned" : 10,<br /> "nscannedObjects" : 10,<br /> "n" : 10,<br /> "millis" : 0,<br /> "oldPlan" : {<br /> "cursor" : "BtreeCursor x_1",<br /> "indexBounds" : [<br /> [<br /> {<br /> "x" : 1000<br /> },<br /> {<br /> "x" : 1000<br /> }<br /> ]<br /> ]<br /> },<br /> "allPlans" : [<br /> {<br /> "cursor" : "BtreeCursor x_1",<br /> "indexBounds" : [<br /> [<br /> {<br /> "x" : 1000<br /> },<br /> {<br /> "x" : 1000<br /> }<br /> ]<br /> ]<br /> },<br /> {<br /> "cursor" : "BtreeCursor y_1",<br /> "indexBounds" : [<br /> [<br /> {<br /> "y" : 0<br /> },<br /> {<br /> "y" : 0<br /> }<br /> ]<br /> ]<br /> },<br /> {<br /> "cursor" : "BasicCursor",<br /> "indexBounds" : [ ]<br /> }<br /> ]<br />}<br />
36. 36. Example 1<br />> db.c.findOne( {i:99999} )<br />{ "_id" : ObjectId("4bb962dddfdcf5761c1ec6a3"), "i" : 99999 }<br />query test.c ntoreturn:1 reslen:69 nscanned:100000 { i: 99999.0 } nreturned:1 157ms<br />> db.c.find( {i:99999} ).limit(1).explain()<br />{<br /> "cursor" : "BasicCursor",<br /> "indexBounds" : [ ],<br /> "nscanned" : 100000,<br /> "nscannedObjects" : 100000,<br /> "n" : 1,<br /> "millis" : 161,<br /> "allPlans" : [<br /> {<br /> "cursor" : "BasicCursor",<br /> "indexBounds" : [ ]<br /> }<br /> ]<br />}<br />> db.c.ensureIndex( {i:1} );<br />> for( i = 0; i < 100000; ++i ) { db.c.save( {i:i} ); }<br />
37. 37. Example 2<br />> db.c.count( {type:0,i:{\$gt:99000}} )<br />499<br />query test.\$cmd ntoreturn:1 command: { count: "c", query: { type: 0.0, i: { \$gt: 99000.0 } }, fields: {} } reslen:64 256ms<br />> db.c.find( {type:0,i:{\$gt:99000}} ).limit(1).explain()<br />{<br /> "cursor" : "BtreeCursor type_1",<br /> "indexBounds" : [<br /> [<br /> {<br /> "type" : 0<br /> },<br /> {<br /> "type" : 0<br /> }<br /> ]<br /> ],<br /> "nscanned" : 49502,<br /> "nscannedObjects" : 49502,<br /> "n" : 1,<br /> "millis" : 349,<br />...<br />> db.c.ensureIndex( {type:1,i:1} );<br />> for( i = 0; i < 100000; ++i ) { db.c.save( {type:i%2,i:i} ); }<br />
38. 38. Example 3<br />> db.c.find().sort( {i:1} )<br />error: {<br /> "\$err" : "too much key data for sort() with no index. add an index or specify a smaller limit"<br />}<br />> db.c.find().sort( {i:1} ).explain()<br />JS Error: uncaught exception: error: {<br /> "\$err" : "too much key data for sort() with no index. add an index or specify a smaller limit"<br />}<br />> db.c.ensureIndex( {i:1} );<br />> db.c.find().sort( {i:1} ).limit( 1000 ); //alternatively<br />> for( i = 0; i < 1000000; ++i ) { db.c.save( {i:i} ); }<br />
39. 39. Example 4<br />> db.c.find( {type:500} ).sort( {i:1} )<br />{ "_id" : ObjectId("4bba4904dfdcf5761c2f917e"), "i" : 500, "type" : 500 }<br />{ "_id" : ObjectId("4bba4904dfdcf5761c2f9566"), "i" : 1500, "type" : 500 }<br />...<br />query test.c ntoreturn:0 reslen:4783 nscanned:100501 { query: { type: 500.0 }, orderby: { i: 1.0 } } nreturned:101 390ms<br />> db.c.find( {type:500} ).sort( {i:1} ).explain()<br />{<br /> "cursor" : "BtreeCursor i_1",<br /> "indexBounds" : [<br /> [<br /> {<br /> "i" : {<br /> "\$minElement" : 1<br /> }<br /> },<br /> {<br /> "i" : {<br /> "\$maxElement" : 1<br /> }<br /> }<br /> ]<br /> ],<br /> "nscanned" : 1000000,<br /> "nscannedObjects" : 1000000,<br /> "n" : 1000,<br /> "millis" : 5388,<br />...<br />> db.c.ensureIndex( {type:1,i:1} );<br />> for( i = 0; i < 1000000; ++i ) { db.c.save( {i:i,type:i%1000} ); }<br />
40. 40. Questions?<br />Get involved www.mongodb.org<br />Downloads, user group, chat room<br />Follow @mongodb<br />Upcoming events <br />www.mongodb.org/display/DOCS/Events<br />SF MongoDB office hours <br />Mondays 4-6pm at Epicenter Café<br />SF MongoDBmeetup<br />May 17 at Engine Yard<br />Commercial support www.10gen.com<br />jobs@10gen.com<br />