简体   繁体   中英

Mongodb - Default Index Creation - Background Construction

I am currently using 3.2.1 mongo driver version .

Use Case -

Write - Bulk Insert in Collection or per row insert Read - Read on basis of _id .

No extra indexes required, default index which mongodb creates on _id field is enough.

Problem - My Mongo Service (calling mongodb) is taking too much of CPU load.

1.) Does Mongodb creates indexes on _id field in background.

2.) If not do i need to make it create index in background to fasten the process. How can i do that programmatically.

Maybe something like this,

collection.createIndex(new BasicDBObject("_id", 1),new BasicDBObject("background", true));

I came across this link

If you are using java api, here is the reference for the correct usage:

http://api.mongodb.org/java/3.0/com/mongodb/client/MongoCollection.html?_ga=1.119232521.1817714352.1461227368#createIndex-org.bson.conversions.Bson-

http://api.mongodb.org/java/3.0/com/mongodb/client/model/IndexOptions.html

Basically you need to provide the background option correctly using api's IndexOptions.

Running an index in the background does not make inserting run faster, on the contrary, it runs slower. However, the query will be asynchronous, thus allowing your application to run other queries in the mean time.

You can try the following approaches to improve the performance on bulk inserts

  • Create a replica that allows reads on secondary nodes. This will have inserts running on the primary node while reads will be directed to the secondary. Running indexing in the background will help in this case. It is important to avoid reading stale data in this case.
  • Create a new index that works well with the shape of data you are inserting.
    • Create several indexes using a variation of keys on the collection.
    • Run an insert query on a small data set. Mongo will analyze all the indexes available on the collection and pick the one that performs the best for the shape of data you are inserting.
    • Run db..explain("executionStats") on the query to find out which of the indexes is being used.
    • Remove all other indexes as they will affect your inserts performance.
    • Run your full query and see how it performs using the new index.

如果您使用的是Spring Data MongoDB,则可以使用Index()类上的builder方法来设置background属性:

new Index(CREATED_DATE_FIELD_NAME, Sort.Direction.DESC).background();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM