问题
I am trying to create indices with pymongo, but failing with error
File "D:/Users/Dims/Design/EnergentGroup/Python GIS Developer/worker/Approach03\sentinel\mongo.py", line 46, in get_results_collection
results_collection.create_index(["uwi", "date_part"], name=index_name, unique=True)
File "C:\Anaconda3\lib\site-packages\pymongo\collection.py", line 1386, in create_index
name = kwargs.setdefault("name", helpers._gen_index_name(keys))
File "C:\Anaconda3\lib\site-packages\pymongo\helpers.py", line 49, in _gen_index_name
return _UUNDER.join(["%s_%s" % item for item in keys])
File "C:\Anaconda3\lib\site-packages\pymongo\helpers.py", line 49, in <listcomp>
return _UUNDER.join(["%s_%s" % item for item in keys])
TypeError: not enough arguments for format string
Apparently, error occurs inside the library in the code creating default index name, which is
def _gen_index_name(keys):
"""Generate an index name from the set of fields it is over."""
return _UUNDER.join(["%s_%s" % item for item in keys])
apparently incorrect.
My code is following:
index_name = 'uwi_date_part'
if index_name not in index_information:
print("Creating index '%s'..." % index_name)
results_collection.create_index(["uwi", "date_part"], name=index_name, unique=True)
index_name = 'uwi'
if index_name not in index_information:
print("Creating index '%s'..." % index_name)
results_collection.create_index("uwi", name=index_name, unique=False)
How to overcome?
回答1:
This syntax is not what PyMongo requires:
results_collection.create_index(["uwi", "date_part"], name=index_name, unique=True)
You want an index on the two fields, "uwi" and "date_part"? Choose carefully what order to index the fields in (see Optimizing MongoDB Compound Indexes) and whether to index them in ascending or descending order.
If you want to index "uwi" and "date_part" in that order, both ascending, then do this:
results_collection.create_index([("uwi", 1), ("date_part", 1)], name=index_name, unique=True)
For more info on creating indexes with PyMongo, see the documentation.
来源:https://stackoverflow.com/questions/46564974/cant-create-index-due-to-typeerror-not-enough-arguments-for-format-string