Search code examples
elixirets

Elixir searching an ETS table


I have some tuples stored in an Elixir :ets table with the following format,

{id, "first_name", "last_name"}

I'm looking to search the ETS table on both first and last name given a search term. For example if someone's first name was Alice, the search would return this tuple for "Al", "Ali", "Alic", etc.

So far I've tried:

:ets.match_object(table_name, {:_, :_, "last_name"})

which works when it matches exactly on "last_name" but if I have "last" or some shorter permutation in the search string it does not return a result.

I have also looked at search vectors, ets.match, ets.lookup and a few other ways to perform the search. Is there some built in, or other Elixiry way to do this type of string searching?


Solution

  • One might use a Swiss knife of ets lookups, :ets.foldl/3.

    :ets.foldl(fn
      {_, "Al" <> _, _} = y, acc -> [y | acc] # firstname
      {_, _, "Al" <> _} = y, acc -> [y | acc] # lastname
      _, acc -> acc                           # no match
    end, [], table)
    

    Please note, this is less efficient, compared to the solution proposed by @MikhailAksenov because the search is done in the calling process and hence all the data has to be transferred there, instead of being filtered “inside” the ets.