1. 程式人生 > 其它 >pymongo.errors:Sort operation used more than the maximum 33554432 bytes of RAM. Add an index,

pymongo.errors:Sort operation used more than the maximum 33554432 bytes of RAM. Add an index,

在 mongo 使用過程中遇到了一個問題,需求就是要對mongo 庫中查詢到資料進行分頁,mongo庫我們知道都會儲存大容量的資料,剛開始使用的 skip 和 limit 聯合使用的方法,來達到擷取所需資料的功能,這種方法在庫裡資料容量小的情況下完全可以勝任,但是如果庫裡資料多的話,上面兩個方法就不好使了,就像題目中那個錯誤,這時會報一個 Query failed with error code 96 and error message 'Executor error during find command:OperationFailed: Sort operation used more than the maximum 33554432 bytes of RAM.Add an index, or specify a smaller limit.'

按照錯誤提示,知道這是排序的時候報的錯,因為 mongo 的 sort 操作是在記憶體中操作的,必然會佔據記憶體,同時mongo 內的一個機制限制排序時最大記憶體為 32M,當排序的資料量超過 32M,就會報上面的這個錯,解決辦法就像上面提示的意思,一是加大 mongo 的排序記憶體,這個一般是運維來管,也有弊端,就是資料量如果再大,還要往上加。另一個辦法就是加索引,這個方法還是挺方便的。建立索引及時生效,不需要重啟服務。 建立索引也不難, db.你的collection.createIndex({“你的欄位”: -1}),此處 -1 代表倒序,1 代表正序; db.你的collecton.getIndexes(); 這兩個語句,第一個是新增索引,第二個是查詢索引,如果檢視到你剛才新增的那個索引欄位,就說明索引新增成功了。這時候在你的程式裡再運用 sort 方法的話,這樣就不會報錯而且速度很快。 新增索引會帶來一定的弊端,這樣會導致資料插入的時候相對之前較慢,因為索引會佔據空間的。綜上考慮,根據實際情況判斷採用合適的方法。 案例: mongodb執行如下語句

db.three_province_poi_v9.find({ "sum_n.sum_4_x":{ $gt:0} } ).sort({"sum_n.sum_4_x":-1}) 

報錯如下:

Error: error: {
    "ok" : 0,
    "errmsg" : "Executor error during find command: OperationFailed: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.",
    "code" : 96,
    "codeName" : "OperationFailed"
}

按照前面所述:執行

db.three_province_poi_v9.createIndex({"sum_n.sum_4_x": -1})

則在執行語句,即可得到結果

python 下pymongo執行

db_first.three_province_poi_v9.find({"sum_n.sum_4_x":{ "$gt":0} } ).sort([("sum_n.sum_4_x",-1)])

報錯

在上面基礎之上以修改完成。