Skip to content
namlook edited this page Aug 22, 2011 · 2 revisions

Indexes

Sometimes, it's desirable to have indexes on your dataset - especially unique ones. In order to do that, you must fill the indexes attribute. The indexes attribute is a list of dictionary which have a fields field:

from mongolite import INDEX_ASCENDING, INDEX_DESCENDING
@connection.register
class BlogPost(Document):
    __database__ = "tutorial"
    __collection__ = "blogposts"
    skeleton = {
        'title':unicode,
        'body':unicode,
        'author':unicode,
        'date_creation':datetime.datetime,
    }
    optional = {
        'tags': [unicode],
        'rank':int,
    }
    indexes = [
        {"fields": "tags"},
        {
            "fields": [("author", INDEX_DESCENDING), ("date_creation": INDEX_DESCENDING)]},
            "unique": True,
        }
    ]

The fields take the same value as pymongo's ensure_index method.

You can add any other pymongo's supported variables by adding them to the dict (see "unique" in the example).

Note that MongoLite will check if the fields specified into indexes are present in the structure.

To generate the indexes just do:

>>> connection.BlogPost.generate_indexes()

FAQ

I want do generate my indexes in a dynamic collection. How do I do this ?

>>> for lang in ["en", "fr", "es", "de"]:
...     dyn_col = connection.tutorial.blogposts[lang]
...     dyn_col.BlogPost.generate_indexes()

I have the following document and I get an error. What can I do ?

@self.connection.register
class MyDoc(Document):
    skeleton = {
        "foo": dict,
        "bar": int
    }
    indexes = [
            {"fields": "foo.title", "check":False},
    ]

foo is a dict and we index against foo.title which is not declared in skeleton. To bypass this, add "check": False to the indexes declaration.

I don't want to use this index declaration can I just use pymongo's ensure_index

Sure ! Just do it:

connection.tutorial.blogposts.ensure_index([("author", INDEX_DESCENDING), ("date_creation": INDEX_DESCENDING)], unique=True)