Elixir ETS Table Types
An ETS table type is the rule that decides how many rows one key may hold. The type is chosen when the table is created.
A set table keeps one row per key
Insert two rows with the same key and check the size and the lookup.
table = :ets.new(:store, [:set, :public])
:ets.insert(table, {"a", 1})
:ets.insert(table, {"a", 2})
IO.inspect(:ets.info(table, :size))
IO.inspect(:ets.lookup(table, "a"))An ordered set table keeps rows sorted by key
Insert keys out of order and list the whole table.
table = :ets.new(:store, [:ordered_set, :public])
:ets.insert(table, {"b", 2})
:ets.insert(table, {"a", 1})
:ets.insert(table, {"c", 3})
IO.inspect(:ets.tab2list(table))A bag drops a duplicate row, a duplicate bag keeps it
Insert the same three rows into a bag table and into a duplicate bag table, then compare their sizes.
bag = :ets.new(:bag_store, [:bag, :public])
:ets.insert(bag, {"a", 1})
:ets.insert(bag, {"a", 2})
:ets.insert(bag, {"a", 1})
dup = :ets.new(:dup_store, [:duplicate_bag, :public])
:ets.insert(dup, {"a", 1})
:ets.insert(dup, {"a", 2})
:ets.insert(dup, {"a", 1})
IO.puts("bag: #{:ets.info(bag, :size)}")
IO.puts("duplicate_bag: #{:ets.info(dup, :size)}")Example
table = :ets.new(:tags, [:bag, :public])
:ets.insert(table, {"ana", "elixir"})
:ets.insert(table, {"ana", "otp"})
:ets.insert(table, {"ana", "elixir"})
IO.inspect(Enum.sort(:ets.lookup(table, "ana")))
IO.inspect(:ets.info(table, :size))Key points
- Set table: A set table holds at most one row per key.
- Ordered set table: An ordered set table holds at most one row per key and keeps rows sorted by key.
- Bag table: A bag table holds many rows per key but never stores the same row twice.
- Duplicate bag table: A duplicate bag table holds many rows per key and allows the same row twice.
- Choose a type: Use a set table for one value per key and a bag table for many values per key.
In this example, a bag table stores tags for one user. The same tag is inserted twice, but the sorted lookup shows it only once. The size stays 2, which proves the bag dropped the duplicate row.
Note
The type is fixed when the table is created, so a different type needs a new table.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which table type allows the same row to appear twice?