nitinjain110588
nitinjain110588

Reputation: 177

How to set expiry of records in Mnesia

I am writing records to mnesia using dirty write

:mnesia.dirty_write({Table_Name, id, Node.self(), timestamp, msg})

I want to delete records which are older than 1 hour, how can I set the Expiry or TTL?

Upvotes: 2

Views: 893

Answers (2)

nitinjain110588
nitinjain110588

Reputation: 177

Since mnesia dont have any ttl mechanism (atleast I couldn't find one) I wrote a gen server which deletes all the records from mnesia older than 1 hour. This gen server gets active every 1 hour, deletes older records and go back to sleep state. Here is the code snippet of logic

  {:atomic, list} =
    :mnesia.transaction(fn ->
      :mnesia.select(Table_Name, [
        {{Table_Name, :"$1", :"$2", :"$3", :"$4", :"$5", :"$6", :"$7", :"$8", :"$9", :"$10"},
         [{:<, :"$3", cutoff_time}], [:"$$"]}
      ])
    end)

  for record <- list do
    [id, _, _, _, _, _, _, _, _, _] = record
    :mnesia.dirty_delete(Table_Name, id)
  end

Note - Each Record in the table has 10 fields and first field (id) is the key. Parameter $3 is the timestamp and cutoff time = current timestamp - 1 hour

Upvotes: 1

D&#225;niel Szoboszlay
D&#225;niel Szoboszlay

Reputation: 570

Mnesia doesn't have built-in support for record expiry/TTL. You have to implement this feature on your own, for example by periodically scanning the table for expired records and deleting them.

Upvotes: 2

Related Questions