python - 由于类型错误 : not enough arguments for format string,无法创建索引

标签 python mongodb indexing pymongo

我正在尝试使用 pymongo 创建索引,但因错误而失败

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

显然,在创建默认索引名称的代码中库内部发生了错误,即

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 所需要的:

results_collection.create_index(["uwi", "date_part"], name=index_name, unique=True)

您想要“uwi”和“date_part”这两个字段的索引吗?仔细选择字段索引的顺序(请参阅 Optimizing MongoDB Compound Indexes )以及是否按升序或降序对它们进行索引。

如果您想按升序索引“uwi”和“date_part”,请执行以下操作:

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 .

关于python - 由于类型错误 : not enough arguments for format string,无法创建索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46564974/

相关文章:

python - 在 Python 中使用 if 条件加速逐行循环

python - Numpy:评估高于/低于平均值的值的标准偏差

sql - 为什么表中的记录排序不是按照聚集索引?

python - 如何检查列中的所有值是否满足 Data Frame 中的条件?

python - search() 中的 Elasticsearch-py 无法识别 'analyzer' 参数

mongodb - 如何统计mongodb中游标的迭代次数?

java - 以两种不同的方式序列化 jackson 场

javascript - 如何在 MongoDb .aggregate() 中的 $lookup 中添加条件?

r - 如何找出矩阵的多少行满足相当复杂的标准(在 R 中)?

python - 从系列/列中查找第一个元素的索引(例如 "True")