pymongo創建hash和text索引


來源於

 

不止於python

 

報錯中.......

在使用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空間, 所以不建議對較大的創建普通索引


關於mongo官方文檔關於index key的限制

 

解決中......

最簡單方法

最簡單也是最難的方法:

想辦法減少字段值的大小, 不超過1024字節

改變mongo配置

選擇其一即可

1. 使用以下命令啟動mongod

mongod --setParameter failIndexKeyTooLong=false


2. 在mongo中執行

db.getSiblingDB('admin').runCommand( { setParameter: 1, failIndexKeyTooLong: false } )

 

創建hash索引

建立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索引一個集合只能創建一個, 再次創建會報錯

創建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
}

 

到這里這個錯誤就被愉快的解決了, 有問題歡迎留言哦!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM