【发布时间】:2016-08-24 16:22:46
【问题描述】:
在使用 PyMongo 的 Python 脚本中,使用以下行为集合创建索引
myCollection.create_index('Datetime', unique=True)
但是这会在下次执行脚本时抛出错误,因为索引已经存在。
问题:有没有办法在决定是否调用create_index之前检查索引是否存在?
【问题讨论】:
标签: python mongodb python-2.7 pymongo
在使用 PyMongo 的 Python 脚本中,使用以下行为集合创建索引
myCollection.create_index('Datetime', unique=True)
但是这会在下次执行脚本时抛出错误,因为索引已经存在。
问题:有没有办法在决定是否调用create_index之前检查索引是否存在?
【问题讨论】:
标签: python mongodb python-2.7 pymongo
这可能有效:
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)
【讨论】:
在 PyMongo 3.6.0 及更高版本中,调用 create_index 将不会重新创建已存在的索引并且不会引发错误。如果索引已经存在,则索引创建将被忽略。
【讨论】:
pymongo.errors.OperationFailure: Index with name: {INDEX_NAME} already exists with a different name。有没有人有类似的问题?
你可以使用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() 方法,看起来正是您要问的,但现在已弃用此方法。
【讨论】: