來源於
報錯中.......
在使用pymongo創建基礎索引, 出現以下錯誤
pymongo.errors.OperationFailure: WiredTigerIndex::insert: key too large to index, failing
代碼如下:
import pymongo user_col = pymongo.MongoClient()["test"]["t"] user_col.create_index("description") user_col.insert_one({"age": 18, "description": "tests"*260})
google原因.......
這個是因為在MongoDB中,從2.6開始,索引項的總大小(根據BSON類型可能包括結構開銷)必須小於1024字節。
就是要建立的索引字段的值特別大, 超過了1024字節, 對於比較大的值建立索引, 建立的索引也會非常大, 效率也會很慢, 占用更大的RAM空間, 所以不建議對較大的創建普通索引
解決中......
最簡單方法
最簡單也是最難的方法:
想辦法減少字段值的大小, 不超過1024字節
改變mongo配置
選擇其一即可
1. 使用以下命令啟動mongod
mongod --setParameter failIndexKeyTooLong=false
2. 在mongo中執行
db.getSiblingDB('admin').runCommand( { setParameter: 1, failIndexKeyTooLong: false } )
創建hash索引
建立hash索引
Collection.create_index([("description", pymongo.HASHED)])
例:將創建索引改為
user_col.create_index([("description", pymongo.HASHED)])
進入mongo, 查看索引如下
> use test
switched to db test
> db.user.getIndexes()
[ { "v": 2, "key": { "_id": 1 }, "name": "_id_", "ns": "test.user" }, { "v": 2, "key": { "description": "hashed" }, "name": "description_hashed", "ns": "test.user" } ]
創建text索引
注意 : text索引一個集合只能創建一個, 再次創建會報錯
Collection.create_index([("description", pymongo.TEXT)])
只需要將pymongo.HASHED 改為 pymongo.TEXT 就可以了
user_col.create_index([("description", pymongo.TEXT)])
再次查看db.user.getIndexes(), 會多出一個text索引:
{ "v": 2, "key": { "_fts": "text", "_ftsx": 1 }, "name": "description_text", "ns": "test.user", "weights": { "description": 1 }, "default_language": "english", "language_override": "language", "textIndexVersion": 3 }
到這里這個錯誤就被愉快的解決了, 有問題歡迎留言哦!