Reputation: 63619
In a Python script using PyMongo, an index is created for a collection using the line
myCollection.create_index('Datetime', unique=True)
However this throws an error the next time the script is executed because the index already exist.
Question: Is there a way to check for the existance of an index before deciding whether to call create_index
?
Upvotes: 19
Views: 10862
Reputation: 1288
This might work:
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)
Upvotes: 1
Reputation: 698
In PyMongo 3.6.0 and later, calling create_index
will not recreate the index if it already exists and will not throw an error. The index creation will just be ignored if the index already exists.
Upvotes: 23
Reputation: 473813
You can use index_information()
method:
Get information on this collection’s indexes.
Returns a dictionary where the keys are index names (as returned by create_index()) and the values are dictionaries containing information about each index.
index_name = 'Datetime'
if index_name not in myCollection.index_information():
myCollection.create_index(index_name, unique=True)
There is also list_indexes()
method which can also be used to solve it, but the output format is not that convenient as in case of index_information()
.
And, there is that ensure_index()
method, that looks exactly what you are asking about, but this method is now deprecated.
Upvotes: 16