【发布时间】:2015-10-22 16:12:20
【问题描述】:
我有一个这样的文章模型:
var ArticleSchema = new Schema({
type: String
,title: String
,content: String
,hashtags: [String]
,comments: [{
type: Schema.ObjectId
,ref: 'Comment'
}]
,replies: [{
type: Schema.ObjectId
,ref: 'Reply'
}]
, status: String
,statusMeta: {
createdBy: {
type: Schema.ObjectId
,ref: 'User'
}
,createdDate: Date
, updatedBy: {
type: Schema.ObjectId
,ref: 'User'
}
,updatedDate: Date
,deletedBy: {
type: Schema.ObjectId,
ref: 'User'
}
,deletedDate: Date
,undeletedBy: {
type: Schema.ObjectId,
ref: 'User'
}
,undeletedDate: Date
,bannedBy: {
type: Schema.ObjectId,
ref: 'User'
}
,bannedDate: Date
,unbannedBy: {
type: Schema.ObjectId,
ref: 'User'
}
,unbannedDate: Date
}
}, {minimize: false})
当用户创建或修改article时,我将创建主题标签
ArticleSchema.pre('save', true, function(next, done) {
var self = this
if (self.isModified('content')) {
self.hashtags = helper.listHashtagsInText(self.content)
}
done()
return next()
})
例如,如果用户写"Hi, #greeting, i love #friday",我会将['greeting', 'friday'] 存储在标签列表中。
我正在考虑为主题标签创建索引,以便更快地查询主题标签。但是从猫鼬手册中,我发现了这个:
当您的应用程序启动时,Mongoose 会自动调用 确保架构中每个已定义索引的索引。猫鼬会打电话 为每个索引顺序确保索引,并在上发出一个“索引”事件 所有 ensureIndex 调用成功或存在时的模型 一个错误。虽然很适合开发,但建议使用此行为 在生产中被禁用,因为索引创建可能会导致显着 性能影响。通过设置 autoIndex 禁用该行为 您的架构选项为 false。
http://mongoosejs.com/docs/guide.html
那么对于 mongoDB/Mongoose,索引是更快还是更慢?
另外,即使我创建了类似的索引
hashtags: { type: [String], index: true }
如何在查询中使用索引?或者对于普通查询,它会神奇地变得更快,例如:
Article.find({hashtags: 'friday'})
【问题讨论】:
-
您是否阅读了
.createIndex()的核心文档?具体来说:“如果同时调用多个具有相同索引规范的createIndex()方法,只有第一个操作会成功,其他操作无效。”.索引也需要写入成本,但它们会加快读取速度。这是索引的基本概念。有很多文档可以解释索引的作用。也许做一些阅读。 -
@BlakesSeven 我正在使用 Mongoose,我认为这是一个 mongoDB 包装器。官方文档让我感到困惑,建议在生产中将其关闭