[erlang-questions] Mnesia list of keys query

Mikael Pettersson mikpelinux@REDACTED
Sat Aug 27 10:57:02 CEST 2016

nato writes:
 > Hi List -- long time lurker, first-time poster...
 > I can't seem to find a satisfactory answer to getting all the records
 > from an Mnesia table, given a list of keys to match on. Much
 > preferably, I wanted to stay clear of a match-spec solution, in favor
 > of qlc (if even needed).
 > There wasn't anything I found in the manual on a couple of passes
 > going through it and my first-pass attempt just *seems* like it would
 > be dog slow:
 > L = ManyKeys.
 > Fn = fun() ->
 >       do(qlc:q([ X || X <- mnesia:table(foo),
 >         lists:member(X#foo.bar_id, L) ]))
 >     end.
 > {atomic, L2} = mnesia:transaction(Fn).

You don't say so explicitly, but I'm assuming the 'bar_id' field isn't
the primary key of those 'foo' records.  (If it is, then just loop over
L and read each key individually.)

You want a secondary index on the 'bar_id' field.  See the mnesia docs
for details.

Without a secondary index, any solution reduces to enumerating the entire
'foo' table followed by filtering on L.  That filtering is quadratic as
written above (size of foo times length of L), so you may want to replace
the list with a better lookup structure.

More information about the erlang-questions mailing list