Erlang Term Storage
Erlang Term Storage, commonly referred to as ETS, is a powerful storage engine built into OTP. Every entry in an ETS table is a tuple (or corresponding record), and one piece of the tuple is designated the key.
ETS can hold four kinds of collections (Laurent 2017, 141):
- Sets (
set
): Can contain only one entry with a given key. - Ordered Sets (
ordered_set
): Same as a set, but also maintains a traversal order based on the keys. Great for anything you want to keep in alphabetic or numeric order. - Bags (
bag
): Lets you store more than one entry with a given key. However, if you have multiple entries that have identical values, they get combined into a single entry. - Duplicate Bags (
duplicate_bag
): Not only lets you store more than one entry with a given key, but also lets you store multiple entries with identical values.
Creating and populating a table
- The
ets:new/2
function lets you create a table. - If you do specify
named_table
, processes can reach the table as long as they know the name, without needing access to that return value. Using the
keypos
tuple lets you specify which record value should be the key.rd(food, {name, calories, price, group}). ets:new(food, [ordered_set, {keypos,#food.name}, named_table]). %% or dets:open_file, if you want to use dts
To dispose of a table:
ets:delete(TableId) % or dets:close(TableId)
Simple Queries
ets:lookup/2
: Which is defined for both ETS and DTS.