ETS
Introduction
Erlang ETS in-memory tables: creation, insert and lookup, match patterns, table types, and ordered traversal.
- Erlang ets documentation (erlang.org)
- Match specifications (erlang.org)
Create a table
table = :ets.new(:my_table, [])
Defaults to a :set with :protected access and the key at position 1. The table is owned by the calling process, which deletes it on exit.
See: new/2
Insert and look up
:ets.insert(table, {:fruit, "Apple"})
:ets.insert(table, {:veg, "Leek"})
:ets.lookup(table, :fruit) # => [fruit: "Apple"]
Insert takes a tuple or a list of tuples; the key is element 1 unless :keypos says otherwise.
See: insert/2
Query with patterns
Match objects
:ets.match_object(table, {:_, "Apple"})
# => [fruit: "Apple"]
All objects
:ets.tab2list(table)
# => [veg: "Leek", fruit: "Apple"]
:_ matches any value, so the first pattern scans the whole table. Order is unspecified for :set and :bag tables.
See: match_object/2
Delete
:ets.delete(table, :fruit) # one key
:ets.delete(table) # the whole table
:ets.delete_all_objects(table) empties a table but keeps it alive.
See: delete/1
Table types
table = :ets.new(:cache, [:named_table, :ordered_set])
# => :cache
Options
| Option | Description |
|---|---|
:set | One object per key (default) |
:ordered_set | One object per key, sorted by term order |
:bag | Many objects per key, no duplicates |
:duplicate_bag | Many objects per key, duplicates allowed |
:protected | Owner writes, others read (default) |
:public | Any process reads and writes |
:private | Only the owner reads and writes |
:named_table | Register the table under its name |
{keypos, 1} | Element of the tuple to use as key |
{read_concurrency, true} | Tune for concurrent reads |
{write_concurrency, :auto} | Tune for concurrent writes |
A named table is addressed by its atom, and new/2 returns that name instead of a tid.
See: table_type()
Traverse an ordered set
:ets.new(:sorted, [:named_table, :ordered_set])
:ets.insert(:sorted, [{2, :b}, {1, :a}])
:ets.first(:sorted) # => 1
:ets.last(:sorted) # => 2
:ets.next(:sorted, 1) # => 2
:ets.prev(:sorted, 2) # => 1
Past the last key these return :"$end_of_table".
See: Table traversal
0 Comments for this cheatsheet. Write yours!