ming

How to set a TTL index using Ming?


I'm trying to ensure that my collection expires documents older than 2 weeks using the ming ODM mapper:

class SloData(MappedClass):

    class __mongometa__:
        session = session
        name = 'slo_data'
        indexes = ['application']
        custom_indexes = [
            # expire records after two weeks
            dict(fields=('datetime',), expireAfterSeconds=14*24*60*60)
        ]

    _id = FieldProperty(schema.ObjectId)
    datetime = FieldProperty(schema.DateTime)
    value = FieldProperty(str)
    application = RelationProperty('SloApplication')

def ensure_indexes():
    for mapper in ming.odm.Mapper.all_mappers():
        session.ensure_indexes(mapper.collection)

But when I drop the collection and re-ensure the indexes, the expireAfterSeconds index is not set:

 {
                "v" : 1,
                "key" : {
                        "datetime" : 1
                },
                "ns" : "performance.slo_data",
                "name" : "datetime_1",
                "background" : true,
                "sparse" : false
        }

Solution

  • Currently declaring indexes on Ming through the declarative interface only accepts the sparse and unique options. You can achieve this by using session.impl.db.collection_name.ensure_index which directly exposes the pymongo API. Simply put this inside your def ensure_indexes method so that it is performed whenever the database is initialized