mongokit索引做n

2024-10-03 23:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Flask和MongoDB开发一个Web应用程序。我使用(Flask-)MongoKit来定义一个模式来验证我的数据。在

在我的数据库中,有一个名为“users”(见下文)的集合,其中包含一个字段“email”。尝试在oka文档中指定的字段上创建唯一的索引(http://namlook.github.com/mongokit/index.html). 但是,当我通过MongoDB客户端shell检查集合索引时,根本没有索引“email”。在

我在网上发现了一个类似的问题:“唯一索引不起作用”(https://github.com/namlook/mongokit/issues/98)在

有人知道为什么它不起作用吗?在

用户集合:

@db.register
class User(Model):

    __collection__ = 'users'

    structure = {
        'first_name': basestring,
        'last_name': basestring,
        'email': basestring,
        'password': unicode,
        'registration_date': datetime,
    }

    required_fields = ['first_name', 'last_name', 'email', 'password', 'registration_date']

    default_values = {
        'registration_date': datetime.utcnow,
    }

    # Create a unique index on the "email" field
    indexes = [
        {
            'fields': 'email',  # note: this may be an array
            'unique': True,     # only unique values are allowed 
            'ttl': 0,           # create index immediately
        },
    ]

在db.users.getIndexes数据库()输出:

^{pr2}$

请注意,我也尝试不使用“ttl”:0,并且可以使用以下代码创建索引:

db.users.create_index('email', unique=True)

我认为这直接使用了pymongo连接对象。在

提前谢谢你的帮助。在


Tags: namegithubcom数据库flaskdbdateindex
3条回答

对,您需要使用单独的脚本用索引重新创建数据库。它将在需要时调用,而不是每次服务器运行时调用。示例:

def recreatedb(uri, database_name):
    connection = Connection(uri)
    connection.drop_database(database_name)
    #noinspection PyStatementEffect
    connection[database_name]
    connection.register(_DOCUMENTS)
    for document_name, obj in connection._registered_documents.iteritems():
        obj.generate_index(connection[database_name][obj._obj_class.__collection__])

要防止使用没有索引的数据库,请执行以下操作:

^{pr2}$

你做的正是你应该做的。从版本0.7.1(可能是版本0.8?)起,自动索引创建已经从MongoKit中删除。Here对它来说是个问题。在

它背后的原因是它必须对集合调用ensureIndex。名称中的“确保”部分使它看起来像是检查索引,然后在不存在的情况下创建索引,但是来自Mongo的一位开发人员说,它可能最终还是会(重新)创建整个索引,这可能会非常昂贵。开发商还表示,应该将其视为管理任务,而不是开发任务。在

解决方法是为列表中定义为升级/创建脚本一部分的每个索引调用create_index。在

我使用Flask脚本,所以很容易将Marboni的答案作为命令添加到我的manage脚本中,这个脚本很容易运行。在

@manager.command
def setup_indexes():
    """
    create index for all the registered_documents
    """
    for doc in application.db.registered_documents:
        collection = application.db[doc.__collection__]
        doc.generate_index(collection)

我把我的数据库作为app的成员保存(应用程序数据库)为各种各样的管理工作。现在,每当我添加少量索引或更改任何内容时,我都会运行管理器命令。在

^{pr2}$

您可以在这里阅读有关管理器模块的更多信息 http://flask-script.readthedocs.org/en/latest/

相关问题 更多 >