在MongoDB上建索引可能会对MongoDB集群对可用性产生负面影响。在生产服务上,如果针对一个大集合触发建立索引,且在前台运行,你可能会发现,在索引建完之前,整个集群都无响应。在一个大集合上,这个过程可能会持续几个小时,甚至几天。一旦你触发一个索引,简单的重启服务并不能解决这个问题,因为MongoDB会继续重启前的建索引的工作。如果之前你运行后台建索引任务,在服务重启后它会变成前台运行的任务。在这种情况下,重启会让问题变得更糟糕。
解决办法:使用db.currentOp()定位建索引进程,然后使用db.killOp(
db.currentOp();
{
"host" : "server-053.localdomain:27017",
"desc" : "conn",
"threadId" : "140264163313408",
"connectionId" : 946.0,
"client" : "192.168.1.93:49372",
"clientMetadata" : {
"driver" : {
"name" : "mongo-java-driver",
"version" : "3T_5.1.1-478-gfd17fbf"
},
"os" : {
"type" : "Windows",
"name" : "Windows 7",
"architecture" : "amd64",
"version" : "6.1"
},
"platform" : "Java/Oracle Corporation/1.8.0_131-b11"
},
"active" : true,
"currentOpTime" : "2018-05-28T09:52:40.567+0800",
"opid" : 1420164.0,
"secs_running" : NumberLong(679),
"microsecs_running" : NumberLong(679091899),
"op" : "command",
"ns" : "data_test.$cmd",
"command" : {
"createIndexes" : "achievement",
"indexes" : [
{
"key" : {
"record.documents.0.docTitle" : 1.0
},
"name" : "record.documents.0.docTitle_1",
"ns" : "data_test.achievement"
}
],
"$db" : "data_test"
},
"msg" : "Index Build Index Build: 469019/78412152 0%",
"progress" : {
"done" : 469019.0,
"total" : 78412152.0
},
"numYields" : 0.0,
"locks" : {
"Global" : "w",
"Database" : "W",
"Collection" : "w"
},
"waitingForLock" : false,
"lockStats" : {
"Global" : {
"acquireCount" : {
"r" : NumberLong(1),
"w" : NumberLong(1)
}
},
"Database" : {
"acquireCount" : {
"W" : NumberLong(1)
},
"acquireWaitCount" : {
"W" : NumberLong(1)
},
"timeAcquiringMicros" : {
"W" : NumberLong(1336357)
}
},
"Collection" : {
"acquireCount" : {
"w" : NumberLong(1)
}
}
}
}
db.killOp(1420164);
让索引在后台创建,添加{background:true}
参数:
db.works.createIndex({a:1,b:1},{background:true})