簡體   English   中英

PyMongo create_index 僅當它不存在時

[英]PyMongo create_index only if it does not exist

在使用 PyMongo 的 Python 腳本中,使用以下行為集合創建索引

myCollection.create_index('Datetime', unique=True)

但是,這將在下次執行腳本時引發錯誤,因為索引已存在。

問題:在決定是否調用create_index之前,有沒有辦法檢查索引是否存在?

在 PyMongo 3.6.0 及更高版本中,如果索引已經存在,調用create_index將不會重新創建索引,也不會拋出錯誤。 如果索引已經存在,則索引創建將被忽略。

您可以使用index_information()方法:

獲取有關此集合索引的信息。

返回一個字典,其中鍵是索引名稱(由 create_index() 返回),值是包含有關每個索引的信息的字典。

index_name = 'Datetime'
if index_name not in myCollection.index_information():
    myCollection.create_index(index_name, unique=True)

還有list_indexes()方法也可以用來解決它,但輸出格式不如index_information()

而且,有一個ensure_index()方法,它看起來正是您要問的,但是現在不推薦使用該方法。

這可能有效:

def ensure_index(conn, index):
    """
    Creates the index if it does not exist.
    Input Args:
        conn: MongoClient object, created using uri.
        index: List of index tuples. Example:
            [('age', pymongo.DESCENDING), ('sex', pymongo.ASCENDING)]
    """
    index = index or []
    index_str = '_'.join(
        map(lambda x: '%s_%s' %(x[0], x[1]), index)
    )

    indexes = conn.index_information().keys()
    if index_str and index_str not in indexes:
        conn.create_index(index, background=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM