由于TypeError无法创建索引:格式字符串的参数不足 [英] Can't create index due to TypeError: not enough arguments for format string
问题描述
我正在尝试使用pymongo创建索引,但是由于错误而失败
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])
显然不正确.
我的代码如下:
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)
如何克服?
推荐答案
PyMongo不需要此语法:
This syntax is not what PyMongo requires:
results_collection.create_index(["uwi", "date_part"], name=index_name, unique=True)
您要在两个字段"uwi"和"date_part"上建立索引吗?仔细选择索引字段的顺序(请参见优化MongoDB复合索引)以及是否按升序或降序索引它们.
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.
如果要按升序索引"uwi"和"date_part",请执行以下操作:
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)
这篇关于由于TypeError无法创建索引:格式字符串的参数不足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!