- Indexes take addtional space, but provide much faster data retrieval.
- Creating indexes
- .ensureIndex( )
- e.g. "db.students.ensureIndex( { student_id : 1 } );
- e.g. "db.students.ensureIndex( { student_id : 1, "class" : -1 } );
- Multi-key index
- index key can be array
- e.g. db.bbb.insert( { a: [1, 2, 3], b: 1 } );
- keys cannot both be arrays
- e.g.
db.bbb.insert( { a: [1, 2, 3], b: [4, 5, 6] } ); - Unique index
- index key has to be unique, duplicate not allowed
- e.g. db.students.ensureIndex( { student_id: 1, name: 1 }, {unique: true} );
- Foreground vs background indexing
- Foreground: fast, but blocks writes. Suitable for DBA. Can lock a replica while it's being indexed.
- Background: slow (2~4x slower), concurrent with writes. Suitable for developers in a production setting.
- .explained( )
- Useful to examine a query to see if indexing is utlilized
- Important keys: "cursor" (did it use BtreeCursor?), "nscannedObjects" (how many objects actually queried?)
- .hint( )
- $natural: returns result in its natural order
- .hint( { $natural: 1 } ) will use BasicCursor instead of BTreeCursor
Tuesday, August 20, 2013
Indexes, just like relational database!
Week 4 on M101J - Indexes
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment