Erlang / Erlang Advanced Interview questions
How can you use match specifications to filter ETS data efficiently?
A match specification is a low-level, compiled query format — a list of
{Pattern, Guards, Result} tuples — that ets:select/2 executes directly inside
the table engine, so filtering happens without copying every row out to the calling process first.
%% Find {Key, Value} pairs where Value > 100, returning just the Key ets:select(Tab, [{{'$1', '$2'}, [{'>', '$2', 100}], ['$1']}]).
Writing match specs by hand is error-prone, so most code generates them with the
ets:fun2ms/1 parse-transform, which lets you write an ordinary-looking fun and have it converted
into the equivalent match spec at compile time:
ets:fun2ms(fun({K, V}) when V > 100 -> K end).
The performance benefit over pulling all rows and filtering in Erlang code is significant on large tables, since the match spec engine avoids constructing and copying rows that don't pass the guard at all.
More Related questions...