Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create complex queries with elixir ets

Tags:

I have cached a bunch of postcode and lat-long values using erlangs ets functionality.

Picture the following...

iex()> :ets.new(:postcode_cache, [:named_table])
:postcode_cache
iex()> :ets.insert(:postcode_cache, [{"OX495NU", "latlongvalue"},{"M320JG", "latlongvalue"}])
true

This is similar to the ets table I have created in my application. I want to create a function that only selects entries from the cache where the postcode contains a substring of what a user has entered. Is there any way to do this, and if so, how would I implement this functionality?

(In the future I may like to only select values that are within a certain distance using the lat-long value but that is beyond the scope of this question).

Just for clarity, the table is similar to the following elixir list...

iex()> postcode_list = [{"OX495NU","latlong"}, {"M320JG", "latlong"}]

The functionality that I would like to replicate with ets is something like this...

iex()> Enum.filter(list, fn({postcode, _}) -> if String.contains?(postcode, "OX49") end)
[{"OX495NU", "latlong"}]
like image 650
RobStallion Avatar asked Jan 17 '19 15:01

RobStallion


1 Answers

One cannot invoke arbitrary functions in matches, but here you have a match on hand that can be used with :ets.foldl/3:

:ets.foldl(fn
  {<<"0X49", _ :: binary>>, "latlong"} = n, acc -> [n | acc]
  _, acc -> acc
end, [], :named_table)
like image 108
Aleksei Matiushkin Avatar answered Sep 28 '22 18:09

Aleksei Matiushkin