开发者

How does MongoEngine handle Indexes (creation, update, removal)?

开发者 https://www.devze.com 2023-04-13 09:03 出处:网络
Best practice question about setting Mongo indexes.Mongoengine, the Python ORM wrapper, allows you to set indexes in the Document meta class.

Best practice question about setting Mongo indexes. Mongoengine, the Python ORM wrapper, allows you to set indexes in the Document meta class.

When is this meta class introspected and the index added? Can I build a collection via a mongoengine Docum开发者_开发知识库ent class and then add an index after the fact?

If I remove the index from the meta class, is the index automatically removed from the corresponding collection?

Thanks,


You can add an index at any time and ensureIndex will be called behind the scenes so it will be added if it doesn't exist.

If you remove an index from the meta - you will have to use pymongo or the shell to remove the index.


MongoEngine provides a programming construct to maintain all indexes from your python application.It uses metadata on collection class to define all your indexes. Here is an example

class User(Document):
    meta = {        
    'indexes': [
    {
         'fields': ['+name']                   
    },
    {
         'fields': ['#email']
    }]             
}

The User class defined above declares two indexes: 1. name (sort order) and 2. email (hashed). MongoEngine creates each declared index at the first upsert operation. These indexes are created on the collection via a createIndex/ensureIndex call . MongoEngine attempts to create these indexes every time a document is inserted into the collection.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号