Wednesday, June 10, 2015

Mongo DB indexing pitfalls and how to avoid it.

Querying and adding Index to Mongo DB is a bit straight forward. But to use both together to optimize the response time can be a bit tricky.
As adding Index, can help to reduce to response time to find an item, similarly adding unwanted index can lead to other memory and response time-related issue.

So below are some quick  rules/suggestion which should be followed to avoid any pitfalls of indexing

  1.  If you have a field X on which you have an index with a unique key constraint.  Then you don't have to have any other index with other fields along with this X field.
e.g
db.myCollection.ensureIndex({X:1},{unique:true})

Then there is no point of having index like:

db.myCollection.ensureIndex({X:1,b:1})  // no need can be removed
db.myCollection.ensureIndex({X:1,b:1,c:1}) // no need can be removed



2. If you have a compound index and you want to use this index in your query then make sure your query being fired always have the first element of the index.
e.g
compound index : { w:1,x: 1, y: 1, z: 1 }

Then you can fire any query having the FIRST element (w) to use the index.

wxy
wxz
wyz
xyw
yxw
zxw
All above query will use the compound index defined above.
But you CAN'T fire any query which does not have the first element of the indexed as it won't use the index.
e.g  
xyz
xy
zy
For more info read : compound-index   and index-intersection-compound-indexes

3. You should always check your index and write query against it and  not to do vise-verse. If there is no index to cater your query first add the index and then make the query against it.

No comments:

Post a Comment