Elixir ETS Tables
An ETS table is a shared in-memory store that holds rows as tuples. The first item in each row is its key, and a public table can be read and written by other processes.
Create a table and insert a row
Create a set table, insert one row, then look it up.
table = :ets.new(:store, [:set, :public])
:ets.insert(table, {"ana", 31})
IO.inspect(:ets.lookup(table, "ana"))A second insert replaces the row
In a set table, inserting the same key again replaces the old row.
table = :ets.new(:store, [:set, :public])
:ets.insert(table, {"ana", 31})
:ets.insert(table, {"ana", 32})
IO.inspect(:ets.lookup(table, "ana"))Delete a row, then the lookup is empty
Deleting a key removes its row, so a later lookup returns an empty list.
table = :ets.new(:store, [:set, :public])
:ets.insert(table, {"ana", 31})
:ets.delete(table, "ana")
IO.inspect(:ets.lookup(table, "ana"))Example
table = :ets.new(:store, [:set, :public])
:ets.insert(table, {"greeting", "hello"})
reader = Task.async(fn -> :ets.lookup(table, "greeting") end)
IO.inspect(Task.await(reader))
IO.inspect(:ets.lookup(table, "greeting"))Key points
- Create a table: Use :ets.new to create a table and keep the returned table value for later calls.
- Insert a row: Use :ets.insert to add a row, with the first item of the row as its key.
- Look up a row: Use :ets.lookup to fetch the rows for one key as a list.
- Delete a row: Use :ets.delete with a key to remove that key's rows.
- Share a table: A public table lets other processes read and write it.
In this example, a public table is created and a greeting row is inserted. A task running in another process looks the row up and returns the same list. The main process then looks the row up itself and gets the same list, which shows the table is shared.
Note
A table is owned by the process that created it, so each script in this course creates its own table.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does :ets.lookup return when the key is not in the table?