【问题标题】:Motor Index not created on empty Collection未在空集合上创建电机索引
【发布时间】:2015-11-01 20:29:46
【问题描述】:

我有以下代码来设置我的数据库:

self.con = motor.MotorClient(host, port)
self.Db = self.con.DB
self.Col = self.Db.Col

self.Col.create_index("c")
self.Col.create_index("h")

当我运行index_information() 时,我只看到 _id 字段上的索引信息。但是,如果我在插入一些条目后移动create_index()index_information() 会显示新索引。这是否意味着我必须等到集合中有条目才能创建索引?既然我从一个空集合开始,还有其他方法可以做到这一点吗?

【问题讨论】:

    标签: mongodb tornado-motor


    【解决方案1】:

    可以在空的或不存在的 MongoDB 集合上创建索引,该索引出现在 index_information

    >>> from tornado import ioloop, gen
    >>> import motor
    >>>
    >>> con = motor.MotorClient()
    >>> db = con.test
    >>> col = db.collection
    >>>
    >>>
    >>> @gen.coroutine
    ... def coro():
    ...     yield db.drop_collection("collection")
    ...     yield col.create_index("c")
    ...     yield col.create_index("h")
    ...     print((yield col.index_information()))
    ...
    >>> ioloop.IOLoop.current().run_sync(coro)
    {u'c_1': {u'key': [(u'c', 1)], u'v': 1}, u'_id_': {u'key': [(u'_id', 1)], u'v': 1}, u'h_1': {u'key': [(u'h', 1)], u'v': 1}}
    

    由于我在您的示例代码中没有看到任何“yield”语句或任何回调,我怀疑您没有正确使用 Motor。电机是异步的;为了等待与数据库服务器对话的任何 Motor 方法完成,您必须将回调传递给该方法,或者生成该方法返回的 Future。

    有关更多信息,请参阅教程:

    http://motor.readthedocs.org/en/stable/tutorial.html#inserting-a-document

    关于使用 Motor 调用异步方法的讨论(这适用于所有 Tornado 库,而不仅仅是 Motor)从“插入文档”部分开始。

    【讨论】:

    • 嗨,杰西,感谢您的回复。我确实产生了除 create_index() 之外的所有内容,因为我在构造函数中执行了该操作。我会看看这是否有影响,并回信谢谢。
    • 我刚刚意识到在 init 中创建索引后,我出于调试目的删除了集合
    • 这是不在构造函数中进行网络操作的一个很好的理由!我发现这通常是一种反模式,基本上不可能在异步代码中正确执行。最好不要在构造函数中进行网络 I/O,而是在对象上的“open()”之类的函数中进行。
    【解决方案2】:

    您可以非常轻松地在 mongodb 上创建索引(即使在空集合上)使用 field_namedirection

    field_name: 可以是您要在其上创建索引的任何字段。
    direction: 可以是以下值中的任何一个:@ 987654326@、-12dspheretexthashed

    Refer MotorCollection Doc for details

    在下面的代码中,我尝试使用 motor 库和 python 创建索引。

    db.collection_name.create_index([("field_name", 1)] # To create ascending index
    db.collection_name.create_index([("geoloc_field_name", "2dsphere")] # To create geo index
    db.collection_name.create_index([("field_name", "text")] # To create text based index
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      • 2013-12-24
      • 2015-05-27
      • 2011-08-13
      相关资源
      最近更新 更多