This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Erlang ETS (Erlang Term Storage) Cheat Sheet

A quick reference guide for Erlang ETS in Elixir/Erlang: table initialization, access controls (public/protected/private), table types (set/ordered_set/bag), and lookup.

· Published

ETS (Erlang Term Storage) is a robust, in-memory key-value database built directly into the Erlang/OTP runtime (BEAM), accessible natively in both Erlang and Elixir.

🔗 Related: Elixir Programming Language Cheat Sheet

Table Initialization & Basic Operations

# Create a new named table
table = :ets.new(:user_cache, [:set, :public, :named_table])

# Insert tuples into table
:ets.insert(:user_cache, {:user_1, "Alice", 30})
:ets.insert(:user_cache, {:user_2, "Bob", 25})

# Lookup records by key
result = :ets.lookup(:user_cache, {:user_1})
# => [{:user_1, "Alice", 30}]

# Delete a record or clear table
:ets.delete(:user_cache, :user_1)
:ets.delete_all_objects(:user_cache)

# Destroy table completely
:ets.delete(:user_cache)

Table Types

Configure table semantics via creation options:

Type Duplicate Keys Allowed Ordering Notes
:set No Unordered Default table type; key is the first element
:ordered_set No Ordered Keys sorted in Erlang term order; O(log N) lookup
:bag Multiple identical keys allowed Unordered Disallows exact duplicate tuples
:duplicate_bag Multiple identical keys allowed Unordered Allows fully duplicate tuples

Access Controls

  • :protected: All processes can read; only the owner process can write (Default).
  • :public: Any process can read and write concurrently.
  • :private: Only the owner process can read and write.

Traversal on :ordered_set

# Navigation functions
first_key = :ets.first(:user_cache)
next_key  = :ets.next(:user_cache, first_key)
prev_key  = :ets.prev(:user_cache, next_key)
last_key  = :ets.last(:user_cache)

Related topics