【发布时间】:2014-06-10 12:17:31
【问题描述】:
我有一个数据库,其中包含一个包含大量文档(数百万)的集合。 在这个数据库中,我有(除其他外)字段 _VIOLATIONTYPE (int) 和 _DURATION (int)。 现在我想计算 _VIOLATIONTYPE 为 15 或更少且 _DURATION 为 10 或更少的文档数量。 为此,我执行以下 Python 脚本:
#!/usr/bin/env python
import pymongo
import timeit
client = pymongo.MongoClient('localhost', 27017)
database = client['bgp_route_leaks']
collection = database['valleys']
collection.ensure_index('_VIOLATIONTYPE', unique=False)
collection.ensure_index('_DURATION', unique=False)
start = timeit.default_timer()
cursor = collection.find({'$and': [{'_VIOLATIONTYPE': {'$lt': 16}}, {'_DURATION': {'$lt': 10}}]}, {'_DURATION': 1, '_id': 0})
print('Explain: {}'.format(cursor.explain()))
print('Count: {}'.format(cursor.count()))
print('Time: {}'.format(timeit.default_timer() - start))
打印出来:
Explain: {u'nYields': 4, u'nscannedAllPlans': 6244545, u'allPlans': [{u'cursor': u'BtreeCursor _VIOLATIONTYPE_1', u'indexBounds': {u'_VIOLATIONTYPE': [[-1.7976931348623157e+308, 16]]}, u'nscannedObjects': 124, u'nscanned': 124, u'n': 34}, {u'cursor': u'BtreeCursor _DURATION_1', u'indexBounds': {u'_DURATION': [[-1.7976931348623157e+308, 10]]}, u'nscannedObjects': 6244298, u'nscanned': 6244298, u'n': 5678070}, {u'cursor': u'BasicCursor', u'indexBounds': {}, u'nscannedObjects': 123, u'nscanned': 123, u'n': 36}], u'millis': 30815, u'nChunkSkips': 0, u'server': u'area51:27017', u'n': 5678107, u'cursor': u'BtreeCursor _DURATION_1', u'scanAndOrder': False, u'indexBounds': {u'_DURATION': [[-1.7976931348623157e+308, 10]]}, u'nscannedObjectsAllPlans': 6244545, u'isMultiKey': False, u'indexOnly': True, u'nscanned': 6244298, u'nscannedObjects': 6244298}
Count: 5678107
Time: 52.4030768871
在运行时,我还在另一个窗口中执行了 db.currentOp(),它返回了
{
"inprog" : [
{
"opid" : 15,
"active" : true,
"secs_running" : 4,
"op" : "query",
"ns" : "bgp_route_leaks.valleys",
"query" : {
"$query" : {
"$and" : [
{
"_VIOLATIONTYPE" : {
"$lt" : 16
}
},
{
"_DURATION" : {
"$lt" : 10
}
}
]
},
"$explain" : true
},
"client" : "127.0.0.1:46819",
"desc" : "conn1",
"threadId" : "0x7fd69b31c700",
"connectionId" : 1,
"locks" : {
"^" : "r",
"^bgp_route_leaks" : "R"
},
"waitingForLock" : false,
"numYields" : 5,
"lockStats" : {
"timeLockedMicros" : {
"r" : NumberLong(8816104),
"w" : NumberLong(0)
},
"timeAcquiringMicros" : {
"r" : NumberLong(4408723),
"w" : NumberLong(0)
}
}
}
]
}
现在我了解到,最常见的慢速 MongoDB 查询来源是缺少索引。 但是,我确保了 _VIOLATIONTYPE 和 _DURATION 的索引,并且解释告诉我 u'indexOnly': True。 我还读到 NUMA 架构可能会减慢速度,我应该通过命令启动服务
sudo numactl --interleave=all /usr/bin/mongod --dbpath=/var/lib/mongodb
(/proc/sys/vm/zone_reclaim_mode is already set to 0)
我知道已经完成了,但是这个计数仍然需要大约一分钟,其他计数甚至更长,所以我想知道如何做才能使查询更快。
跑步
db.runCommand({compact: 'bgp_route_leaks'})
在 mongo shell 中也尝试过,但没有成功。
关于如何更快地获得计数的任何建议?
MongoDB 版本是 2.4.9。
【问题讨论】:
标签: python mongodb count pymongo