mnesia usage optimisation

Ulf Wiger <>
Wed Jul 24 23:06:36 CEST 2002

On 24 Jul 2002, Luke Gorrie wrote:

>I'm using Mnesia 3.10.2 on R7.
>The following operations are needed, and they have to be fast:
>  insert an element
>  delete all elements with a particular From field
>  lookup all elements with a particular To field

You could perhaps try using two ordered sets:

  -record(myrec, {key, value}).

In one table, key is {From, To}, and in the other, it's
{To, From}. You have to have at least a non-key field, and worst
case, you'd have to make up a dummy field, e.g. 0.

>This module runs as part of a transaction, and it would be more
>convenient to make it run fast in Mnesia than to use some other
>data structure.

A problem with this, of course, is that the data will be
duplicated during the transaction. But that's more a general
trait of transaction semantics than a specific mnesia problem.
You have to have a rollback image if you want transaction

You will get two updates each time you insert or delete an
element, but they will be fast.

Finding all elements with a particular From field:

     FromTable, #myrec{key = {From, '_'}, _='_'}).

Finding all elements with a particular To field:

     ToTable, #myrec{key = {To, '_'}, _='_'}).

Both operations will be equally efficient, and having performed
the match on one table, deleting the same objects in the other
table is just a matter of reversing the key and deleting each
object in O(logN) time.

Naturally, you trade some memory for predictable performance,
since you duplicate the data. If each object has significant
payload, you can store that in only one of the tables, and dummy
payload in the other.


Ulf Wiger, Senior Specialist,
   / / /   Architecture & Design of Carrier-Class Software
  / / /    Strategic Product & System Management
 / / /     Ericsson Telecom AB, ATM Multiservice Networks

More information about the erlang-questions mailing list