生产代码中的猫鼬索引 [英] Mongoose indexing in production code
问题描述
针对MongooseJS
和MongoDB
/Node.js
的猫鼬文档:
应用程序启动时,Mongoose会自动为架构中的每个已定义索引调用
ensureIndex
.虽然对开发有利,但建议在生产中禁用此行为,因为创建索引会严重影响性能.通过将架构的autoIndex
选项设置为false来禁用该行为.
When your application starts up, Mongoose automatically calls
ensureIndex
for each defined index in your schema. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting theautoIndex
option of your schema to false.
这似乎指示从Mongoose删除自动索引,然后再部署以优化Mongoose,从指示Mongo在应用程序启动时遍历所有索引开始,这似乎是有道理的.
This appears to instruct removal of auto-indexing from mongoose prior to deploying to optimize Mongoose from instructing Mongo to go and churn through all indexes on application startup, which seems to make sense.
在生产代码中处理索引的正确方法是什么?也许外部脚本应该生成索引?或者,如果单个应用程序是集合的唯一读取器/写入器,也许ensureIndex
是不必要的,因为每次数据库写入时它将继续索引?
What is the proper way to handle indexing in production code? Maybe an external script should generate indexes? Or maybe ensureIndex
is unnecessary if a single application is the sole reader/writer to a collection because it will continue an index every time a DB write occurs?
To supplement, MongoDB provides good documentation for the how to do indexing, but not why or when explicit indexing directives should be done. It seems to me that indexes should be kept up to date by writer applications automatically on collections with existing indexes and that ensureIndex
is really more of a one-time thing (done when a new index is being applied), in which case Mongoose's autoIndex
should be a no-op under a normal server restart.
推荐答案
我从不理解为什么Mongoose文档如此广泛地建议在生产中禁用autoIndex
.添加索引后,随后的ensureIndex
调用将简单地看到该索引已存在,然后返回.因此,只有在您首次创建索引时,它才会对性能产生影响,并且那时集合通常是空的,因此无论如何创建索引都将很快.
I've never understood why the Mongoose documentation so broadly recommends disabling autoIndex
in production. Once the index has been added, subsequent ensureIndex
calls will simply see that the index already exists and then return. So it only has an effect on performance when you're first creating the index, and at that time the collections are often empty so creating an index would be quick anyway.
我的建议是除非您遇到特殊情况而使autoIndex
处于启用状态,否则请启用它.例如,如果您想向具有数百万个文档的现有集合中添加新索引,并且希望对其创建时间进行更多控制.
My suggestion is to leave autoIndex
enabled unless you have a specific situation where it's giving you trouble; like if you want to add a new index to an existing collection that has millions of docs and you want more control over when it's created.
这篇关于生产代码中的猫鼬索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!