Qqwy

Qqwy

TypeCheck Core Team

How to partially match a string in ETS' match specs?

I am working on a small hobby project which uses ETS/(Am)nesia to learn more about how these systems work.

One thing I am struggling with, is the following:

A user might want to look up records by entering a postal code. Here in the Netherlands, postal codes have the format 1234AB that is, four (base-10) digits followed by two (always capital) letters. However, I want to allow users to be able to find all records having the postal code “1234AB”, “1234AC”, “1234DH”, etc… if they only enter “1234”. In more formal terms: I want users to find all postal codes that contain the prefix they entered.

In SQL this can be done by using a LIKE operation: SELECT * from `myTable` where `postalcode` LIKE '1234%'.
I was wondering if (how) something like this can be done using ETS’ Match Specs.

Any help would be greatly appreciated :blush:

Most Liked

sasajuric

sasajuric

Author of Elixir In Action

AFAIK, matching a binary prefix is not supported with matchspecs. A couple of options I see:

  1. Consider splitting postal code into two fields - the integer part and the letter suffiix. Then you could match on the exact integer part, since matching the exact binary value is supported with matchspecs.
  2. Use charlists instead for the postal code, because you can match the head of a charlist, which allows you to select arbitrary prefix.
  3. You could hack with comparison operators >= and < to test whether a value is greater than or equal to “12345” and less than “12346”. As far as I can tell, that might work.
  4. Iterate through table records, fetch the postal code for each record, then if the code matches the required prefix fetch the desired fields.

To test what can work with matchspecs and what isn’t supported, you can play with :ets.fun2ms from the iex shell:

iex(1)> :ets.fun2ms(fn({key, "12345"} = el) -> key end)
[{{:"$1", "12345"}, [], [:"$1"]}]

iex(2)> :ets.fun2ms(fn({key, "12345" <> _} = el) -> key end)
Error: fun head contains bit syntax matching of variable '_', which cannot be translated into match_spec
saleyn

saleyn

A bit late with this answer, but I ran into the same problem and came up with the following solution:

defmodule Matcher do
  def match_prefix(table, part) when is_binary(part) do
    prefix = String.downcase(part) |> String.to_charlist() |> to_improper_list()
    :ets.select(table, [{{prefix, :_}, [], [:"$_"]}])
  end

  defp to_improper_list([]), do: :_   # <--- this is the main trick that causes partial matching
  defp to_improper_list([h|t]), do: [h|to_improper_list(t)]
end

1> :ets.new(:t, [:public, :named_table, :ordered_set])
2> :ets.insert(:t, [{~c"1234AB", 1}, {~c"1234AC", 2}, {~c"2345BB", 3}])
true
3> Matcher.match_prefix(:t, "1234")
[{~c"1234AB", 1}, {~c"1234AC", 2}]

Where Next?

Popular in Questions Top

LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement