[erlang-questions] select on tuple in mnesia

Ulf Wiger ulf.wiger@REDACTED
Fri May 14 10:02:25 CEST 2010


On 05/14/2010 09:05 AM, Rapsey wrote:
> If I have a tuple saved in an indexed field in mnesia, something like this:
> -record(mnesia_record,{key,val})
> #mnesia_record{key = {atom1,something}, val = "blabla"}
> 
> Will select call for all keys that are of the {atom1,_} pattern use an
> index, or will it have to scan the whole table?

If the key pattern is constant, it will amount to a lookup if the
table is a hash set, or a constrained search if it's an ordered_set.

Note that the head pattern must be constant; if you use a dollar
variable in the head pattern and constrain it in a guard, it will
be a full scan.

Ordered sets can be extremely useful with this trick. If you use
a hierarchical key, you can do very efficient range queries, by
binding the first part of the key. As a silly example, you could
have a table keyed on datetime tuples:

same_minute({Date, {H,M,_}}) ->
   HeadPat = #events{time = {Date,{H,M,'_'}}, _='_'},
   mnesia:select(mytab, [{HeadPat,[],['$_']}]).

...which could be called as

  same_minute(erlang:universaltime()).

BR,
Ulf W
---------------------------------------------------

---------------------------------------------------

WE'VE CHANGED NAMES!

Since January 1st 2010 Erlang Training and Consulting Ltd. has become ERLANG SOLUTIONS LTD.

www.erlang-solutions.com



More information about the erlang-questions mailing list