Pymongo index索引相關操作總結


簡單總結一下pymongo中與index操作相關一些函數, 常用的有:

  • create_index
  • drop_index
  • index_information

其中最主要的是create_index, 可以用它來為mongo的collection建立索引。
以下操作一些簡單的例子,代碼如下:

>>>import pymongo as pm
>>>client = pm.MongoClient('mongodb://user:password@127.0.0.1:27017, ssl=True, ssl_ca_certs='/tmp/mongo_local.pem')
>>>db = client['my_db']
>>>collection = db['my_collection']
#list all index related methods
>>>print([x for x in dir(collection]) if 'index' in x)
#['Collection__create_index', 'create_index','create_indexes','drop_index','drop_indexes',\ # 'ensure_index','index_information','list_indexes','reindex']
#create a index on attr. x
>>>collection.create_index([('x',1)], unique = True, background = True)
#get more help using help method
>>>help(collection.create_index)
#show index information
collection.index_infomation()
#{ 
# '_id_': {'key' ['_id',1)], 'ns':'my_db.my_collection', 'v':1},
# 'x_1' : { 'unique':True, 'key': [('x',1)], 'ns':'my_db.my_collection', 'v':1}
#}
#drop an index by index specifier
>>>collection.drop_index([('x',1)])
#drop an index by index name
>>>#collection.drop_index('x_1')
#WARN: if an index is create with option name specified, it can only be dropped by name
>>>collection.create_index([('x',1)], name = 'idx_x')
>>>collection.drop_index('idx_x')

create_index函數也可以使用多個字段創建索引,例如

>>>collection.create_index([('x',1),('y',1)])

語法中(‘x’,1), x 值為要創建的索引字段名,1 為指定按升序創建索引,也可以用pymongo.ASCENDING代替。如果你想按降序來創建索引,則指定為 -1 或 pymongo.DESCENDING.

在使用create_index()創建索引時,也可指定特定的參數(options),常用可選參數如下:

參數名 類型 描述
background Boolean 建索引過程會阻塞其它數據庫操作,background可指定以后台方式創建索引,即增加 “background” 可選參數。 “background” 默認值為False。
unique Boolean 建立的索引是否唯一。指定為True來創建唯一索引。默認值為False. 默認情況下,MongoDB在創建集合時會生成唯一索引字段_id。
name string 索引的名稱。如果未指定,MongoDB的通過連接索引的字段名和排序順序生成一個索引名稱。例如create_index([(‘x’,1)]在不指定name時會生成默認的索引名稱 ‘x_1’
expireAfterSeconds integer 指定一個以秒為單位的數值,完成 TTL設定,設定集合的生存時間。需要在值為日期或包含日期值的數組的字段的創建。


免責聲明!

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



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