【发布时间】:2015-06-20 17:05:19
【问题描述】:
我在集合中添加了一个索引。我启动的第一个查询比没有索引的同一个查询要慢。以下那些比没有索引的更快,所以这是有道理的。
我想知道为什么会发生这种情况,是因为索引必须从磁盘转到内存吗?然后,对我来说更难理解的是我删除了索引,重新启动了 mongod,我再次创建了索引,它确实运行得很快,不像第一次那样。万一我重新启动计算机的行为就像第一次一样,所以只有第一次使用索引时它才会缓慢。
谁能清楚地解释这种行为?
下面我给出一些关于文档、索引和查询信息的信息。集合内的文档如下所示:
> db.posts.findOne()
{
"_id" : ObjectId("557d73e1fab73211b00f3080"),
"title" : "aaa",
"author" : "nuevo",
"body" : "aaa",
"permalink" : "aaa",
"tags" : [
"a"
],
"comments" : [ ],
"date" : ISODate("2015-06-14T12:30:25.733Z")
}
集合大小:
> db.posts.find().count()
1008
无索引查询,耗时3ms(explain的输出我不放,只放相关部分):
> db.posts.explain("executionStats").find({ permalink: "ambzrbxvnorazgnqvzbw"});
{
....
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 1,
"executionTimeMillis" : 3,
"totalKeysExamined" : 0,
"totalDocsExamined" : 1008,
....
}
创建索引:
> db.posts.createIndex({permalink:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 3,
"numIndexesAfter" : 4,
"ok" : 1
}
创建索引的查询(71 毫秒):
> db.posts.explain("executionStats").find({ permalink: "ambzrbxvnorazgnqvzbw"});
{
....
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 1,
"executionTimeMillis" : 71,
"totalKeysExamined" : 1,
"totalDocsExamined" : 1,
....
}
使用其他永久链接重新启动相同的查询,以避免从内存(或类似的东西)中获取它。耗时 0 毫秒:
> db.posts.explain("executionStats").find({ permalink: "orrjnueekntvjegzvbjk"});
{
....
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 1,
"executionTimeMillis" : 0,
"totalKeysExamined" : 1,
"totalDocsExamined" : 1,
....
}
【问题讨论】: