Mongodb:什么时候调用ensureIndex?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7000777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongodb: when to call ensureIndex?
提问by Johnny
When should I call ensureIndex? Before inserting a single record, after inserting a single record, or before calling find()?
我应该什么时候调用 ensureIndex?在插入单条记录之前,插入单条记录之后,还是在调用 find() 之前?
Regards,
问候,
Johnny
约翰尼
采纳答案by Code Magician
It seems my comment has been a little misunderstood, so I'll clarify. It doesn't really matter when you call it so long as it's called at some point before you call find() for the first time.In other words, it doesn't really matter when you create the index, as long as it's there before you expect to use it.
看来我的评论有点被误解了,所以我会澄清一下。只要在第一次调用 find() 之前的某个时间点调用它,什么时候调用它并不重要。换句话说,什么时候创建索引并不重要,只要它在您期望使用它之前就已经存在了。
A common pattern that I've seen a lot is coding the ensureIndex
at the same time (and in the same place) as the find()
call. ensureIndex
will check if the index exists and create it if it doesn't. There is undoubted some overhead (albeit very small) in calling ensureindex before ever call to find() so it's preferable not to do this.
我经常看到的一个常见模式是ensureIndex
在find()
调用的同时(并在同一个地方)编码。ensureIndex
将检查索引是否存在,如果不存在则创建它。毫无疑问,在调用 find() 之前调用 ensureindex 会产生一些开销(尽管非常小),因此最好不要这样做。
I do call ensureIndex
in code to simplify deployments and to avoid having to manage the db and codebase separately. The tradeoff of ease of deployment balances out the redundancy of subsequent calls to ensureIndex (for me.)
我确实调用ensureIndex
了代码来简化部署并避免分别管理数据库和代码库。易于部署的权衡平衡了后续调用 ensureIndex(对我而言)的冗余。
回答by UpTheCreek
I'd recommend calling ensureIndex once, when your application starts.
我建议在您的应用程序启动时调用一次 ensureIndex。
回答by Karoly Horvath
It doesn't matter, but you only have to do this once. If you want to batch insert a large amount of data to an empty collection then it is best to create the index after the inserts but otherwise it doesn't really matter.
没关系,但你只需要做一次。如果你想批量插入大量数据到一个空集合,那么最好在插入后创建索引,否则它并不重要。
回答by elslooo
You only need to do this once. Example:
您只需执行此操作一次。例子:
db.table.insert({foo: 'bar'});
var foo = db.table.findOne({foo: 'bar'}); // => delivered from FS, not RAM
db.table.ensureIndex({foo: 1});
var foo = db.table.findOne({foo: 'bar'}); // => delivered from RAM, not FS
db.table.insert({foo: 'foo'});
var foo = db.table.findOne({foo: 'foo'}); // => delivered from RAM, not FS
回答by jacobra
If you add an index before hand, every insert/update/delete call has to modify each index also. So, from an optimization stand point, you probably want to put it off as long as possible before issuing queries. However, from a functional stand point, it doesn't matter.
如果您事先添加了索引,则每个插入/更新/删除调用也必须修改每个索引。因此,从优化的角度来看,您可能希望在发出查询之前尽可能地推迟它。但是,从功能的角度来看,这并不重要。
回答by ericsoco
I typically put my ensureIndex()
calls within an init block for the part of my application that manages communication with MongoDB. Also, I wrap those ensureIndex()
calls within a check for existence of a collection I know must exist for the application to function; this way, the ensureIndex() calls are only ever called once, ever, the first time the application is run against a specific MongoDB instance.
我通常将我的ensureIndex()
调用放在管理与 MongoDB 通信的应用程序部分的 init 块中。此外,我将这些ensureIndex()
调用包装在检查是否存在集合中,我知道应用程序必须存在该集合才能正常运行;这样,在应用程序第一次针对特定 MongoDB 实例运行时,仅调用一次 ensureIndex() 调用。
I've read elsewhere an opinion against putting ensureIndex() calls in application code, as other developers can mistakenly change them and alter the DB (the indexes), but wrapping it in a check for a collection's existence helps to guard against this.
我在别处读到过反对将 ensureIndex() 调用放在应用程序代码中的意见,因为其他开发人员可能会错误地更改它们并更改 DB(索引),但是将其包装在检查集合是否存在的检查中有助于防止这种情况发生。
Java MongoDB driver example:
Java MongoDB 驱动程序示例:
DB db = mongo.getDB("databaseName");
Set<String> existingCollectionNames = db.getCollectionNames();
// init collections; ensureIndexes only if creating collection
// (let application set up the db if it's not already)
DBCollection coll = db.getCollection("collectionName");
if (!existingCollectionNames.contains("collectionName")) {
// ensure indexes...
coll.ensureIndex(BasicDBObjectBuilder.start().add("date", 1).get());
// ...
}
回答by GauravLuthra
If you have a collection that have millions of records and you are building multiple compound indices with auto-indexing turned off then you MUST ensure that you are invoking ensureIndexes() much before your first find query, possibly synchronously i.e. after ensureIndexes method returns.
如果您有一个包含数百万条记录的集合,并且您正在构建多个关闭自动索引的复合索引,那么您必须确保在第一次查找查询之前调用 ensureIndexes(),可能是同步的,即在 ensureIndexes 方法返回之后。
The mode(foreground vs background) in which indexes are build adds extra complexity. Foreground mode locks the complete db while it is building the indexes whereas background mode allows you to query the db. However background mode of index building takes extra time.
构建索引的模式(前景与背景)增加了额外的复杂性。前台模式在构建索引时锁定完整的数据库,而后台模式允许您查询数据库。然而,索引构建的后台模式需要额外的时间。
So you must make sure that indexes have been created successfully. You can use db.currentOp() to check progress of ensureIndexes() while it is still creating indexes.
因此,您必须确保已成功创建索引。您可以使用 db.currentOp() 在 ensureIndexes() 仍在创建索引时检查它的进度。