pymongo读取大数据时报错
Traceback (most recent call last):
File "MongodbConvertMysql.py", line 91, in
mcm.mongoConvertMysql()
File "MongodbConvertMysql.py", line 82, in mongoConvertMysql
ret_val = self.__delmysqlInsert(val)
File "MongodbConvertMysql.py", line 66, in __delmysqlInsert
for v in val:
File "build/bdist.linux-x86_64/egg/pymongo/cursor.py", line 1090, in next
File "build/bdist.linux-x86_64/egg/pymongo/cursor.py", line 1012, in _refresh
File "build/bdist.linux-x86_64/egg/pymongo/cursor.py", line 903, in __send_message
File "build/bdist.linux-x86_64/egg/pymongo/helpers.py", line 137, in _unpack_response
pymongo.errors.OperationFailure: database error: Plan executor error during find: Overflow sort stage buffered data usage of 33554492 bytes exceeds internal limit of 33554432 bytes
原因比较明确:Sort operation used more than the maximum 33554432 bytes of RAM.
,33554432 bytes
算下来正好是32Mb
,而Mongodb的sort操作是把数据拿到内存中再进行排序的,为了节约内存,默认给sort操作限制了最大内存为32Mb
,当数据量越来越大直到超过32Mb
的时候就自然抛出异常了!
解决方案有两个思路,一个是既然内存不够用那就修改默认配置多分配点内存空间;一个是像错误提示里面说的那样创建索引。
首先说如何修改默认内存配置,在Mongodb命令行窗口中执行如下命令即可:
db.adminCommand({setParameter:1, internalQueryExecMaxBlockingSortBytes:335544320})
我直接把内存扩大了10倍,变成了320Mb。从这里可以看出,除非你服务器的内存足够大,否则sort占用的内存会成为一个严重的资源消耗!然后是创建索引,也比较简单:
db.yourCollection.createIndex({<field>:<1 or -1>})
db.yourCollection.getIndexes() //查看当前collection的索引
其中1
表示升序排列,-1
表示降序排列。索引创建之后即时生效,不需要重启数据库和服务器程序,也不需要对原来的数据库查询语句进行修改。创建索引的话也有不好的地方,会导致数据写入变慢,同时Mongodb数据本身占用的存储空间也会变多。不过从查询性能和服务器资源消耗这两方面来看,通过创建索引来解决这个问题还是最佳的方案!
来源:https://blog.csdn.net/cloume/article/details/70767061
http://blog.sina.com.cn/s/blog_4b623d4e0102wztq.html