Saturday, 21 February 2015

mongoDB : Creating Indexes


Before creating an index, let’s see an example program, how efficiently it works without indexing.

Below java program inserts 10000000 dummy records into the collection “student” of database “school”. Below program takes approximately 15 to 20 minutes to insert all the records into student collection.

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

public class Test {
  /* Step 1 : get mongoCLient */
  public static MongoClient getMongoClient() {
    MongoClient mongoClient = null;
    try {
      mongoClient = new MongoClient("localhost", 27017);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return mongoClient;
  }

  public static void main(String args[]) {
    MongoClient mongoClient = getMongoClient();

    /* Step 2: Connect to DB */
    DB db = mongoClient.getDB("school");

    /* Step 3 : Get collection */
    DBCollection collection = db.getCollection("students");

    for (int i = 1; i <= 10000000; i++) {
      BasicDBObject obj = new BasicDBObject();
      obj.append("student_id", i).append("first_name", "first_name" + i)
          .append("last_name", "last_name" + i);
      collection.insert(obj);
    }
    
    System.out.println("Records inserted");

  }
}


Let’s try to retrieve student with student_id 1.

> db.students.find({"student_id" : 1})
{ "_id" : ObjectId("54c8769e308045e8235e9c9a"), "student_id" : 1, "first_name" : "first_name1", "last_name" : "last_name1" }


To fetch for student with student_id "1", it takes approximately 5 minutes. It is because currently there is no index for student collection. Let's try by creating index on student collection and check.

db.students.ensureIndex({"student_id": 1})

> db.students.ensureIndex({"student_id": 1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}


After creating index, all my queries on field “student_id” runs much faster.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment