【问题标题】:PyMongo create_index only if it does not existPyMongo create_index 仅当它不存在时
【发布时间】:2016-08-24 16:22:46
【问题描述】:

在使用 PyMongo 的 Python 脚本中,使用以下行为集合创建索引

myCollection.create_index('Datetime', unique=True)

但是这会在下次执行脚本时抛出错误,因为索引已经存在。

问题:有没有办法在决定是否调用create_index之前检查索引是否存在?

【问题讨论】:

    标签: python mongodb python-2.7 pymongo


    【解决方案1】:

    这可能有效:

    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)
    

    【讨论】:

      【解决方案2】:

      在 PyMongo 3.6.0 及更高版本中,调用 create_index 将不会重新创建已存在的索引并且不会引发错误。如果索引已经存在,则索引创建将被忽略。

      【讨论】:

      • 您能否引用任何记录此行为的来源?
      • documentation 的第二个要点
      • 谁能处理这些不切实际的科学证据标准? :) 感谢@GabrielFair,默认行为的详细说明。
      • 这仅适用于非唯一索引。如果你已经有一个唯一的索引,你会在再次调用 create_index 时得到 pymongo.errors.DuplicateKeyError。
      • 我的 pymongo 版本是 3.11.3,mongodb 版本是 4.4.3,但是如果存在具有相同字段的索引,它会给出pymongo.errors.OperationFailure: Index with name: {INDEX_NAME} already exists with a different name。有没有人有类似的问题?
      【解决方案3】:

      你可以使用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() 方法,看起来正是您要问的,但现在已弃用此方法。

      【讨论】:

      • index_information()返回的dict的key为索引名(create_index返回),与索引key不同。你确定你的代码有效吗?请注意,创建索引时可以指定自定义名称。
      猜你喜欢
      • 2021-03-05
      • 2011-02-18
      • 2011-04-12
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 2019-07-12
      • 2012-10-09
      相关资源
      最近更新 更多