[erlang-questions] searching in an ETS table for substring

Steve Vinoski vinoski@REDACTED
Sat Feb 11 16:19:56 CET 2012


On Sat, Feb 11, 2012 at 8:28 AM, Avinash Dhumane <avinash@REDACTED> wrote:
> I am learning Erlang, and I must be doing something wrong here; please
> correct me! Thanks.
>
> avinash@REDACTED:~$ erl
> Erlang R14B02 (erts-5.8.3) [source] [smp:2:2] [rq:2] [async-threads:0]
> [kernel-poll:false]
>
> Eshell V5.8.3  (abort with ^G)
> 1>  T=ets:new(test, [set]).
> 16400
> 2>  ets:insert(T, {"erlang", 1}).
> true
> 3>  ets:insert(T, {"ericsson", 2}).
> true
> 4> ets:insert(T, {"erring", 3}).
> true
> 5>
> 5> ets:insert(T, {"ejection", 4}).
> true
> 6>  ets:insert(T, {"emersion", 5}).
> true
> 7> ets:select(T, [{{'$1', '_'}, [], ['$$']}]).
> [["erring"],
>  ["emersion"],
>  ["ericsson"],
>  ["erlang"],
>  ["ejection"]]
> 8> ets:select(T, [{{'$1', '_'}, [{'==', '$1', "er"++'_'}], ['$$']}]).
> []
> 9> ets:select(T, [{{'$1', '_'}, [{'=:=', '$1', "er"++'_'}], ['$$']}]).
> []
> 10> ets:select(T, [{{'$1', '_'}, [{'=', '$1', "er"++'_'}], ['$$']}]).
> ** exception error: bad argument
>      in function  ets:select/2
>         called as ets:select(16400,
>
> [{{'$1','_'},[{'=','$1',[101,114|'_']}],['$$']}])
> 11>

One approach:

1> ets:select(T, [{{"er"++'_','_'}, [], ['$_']}]).
[{"erring",3},{"ericsson",2},{"erlang",1}]

But note this returns entire objects, not just keys. Still, I think
that's what Martin might have wanted, since it matches what his
original SQL select example would do.

Another approach, fetching just the keys:

2> MS = ets:fun2ms(fun({K,_}) when is_list(K), hd(K) =:= $e, hd(tl(K))
=:= $r -> K end).
[{{'$1','_'},
  [{is_list,'$1'},
   {'=:=',{hd,'$1'},101},
   {'=:=',{hd,{tl,'$1'}},114}],
  ['$1']}]
3> ets:select(T, MS).
["erring","ericsson","erlang"]

This approach can work OK if you're matching a prefix of just 2 or 3
characters, but could get tedious beyond that.

--steve



More information about the erlang-questions mailing list