You can use matchspecs and :ets.select
to sort of do this.
For your “string” prefix you need to use charlists
(because they are lists)
defmodule M do
def setup() do
:ets.new(:t, [:public, :named_table])
end
def insert(key, value) do
:ets.insert(:t, {key, value})
end
def prefix_search(prefix) do
:ets.select(:t, [{{prefix, :_}, [], [:"$_"]}])
end
end
M.setup()
M.insert('hello', 'world')
M.insert('hey', 'joe')
M.insert('other', 'key')
IO.inspect(M.prefix_search([?h, ?e, ?l | :_]))
IO.inspect(M.prefix_search([?h, ?e | :_]))
Which gives the result.
$ elixir tst.exs
[{'hello', 'world'}]
[{'hey', 'joe'}, {'hello', 'world'}]
This does not work with elixir strings which are binaries.
The example can be transformed to match your second question:
defmodule M do
def setup() do
:ets.new(:t, [:public, :named_table])
end
def insert(tuple) do
:ets.insert(:t, tuple)
end
def part_search(first_part) do
ms = [{:"$1", [{:"==", first_part, {:element, 1, :"$1"}}, {:">=", {:size, :"$1"}, 2}], [:"$_"]}]
:ets.select(:t, ms)
end
end
M.setup()
M.insert({"part1", "part2", "somevalue"})
M.insert({"part1", "]art2", "part3", "somevalue"})
M.insert({"part4", "]art5", "part6", "somevalue"})
IO.inspect(M.part_search("part1"))
IO.inspect(M.part_search("part4"))
The tricky thing is to write proper matchspecs. Here is the specification: http://erlang.org/doc/apps/erts/match_spec.html