Skip to content

Instantly share code, notes, and snippets.

@wang-zhijun
Last active April 27, 2016 08:10
Show Gist options
  • Save wang-zhijun/f6db2070c88abaa7e068991316d7abb5 to your computer and use it in GitHub Desktop.
Save wang-zhijun/f6db2070c88abaa7e068991316d7abb5 to your computer and use it in GitHub Desktop.
ErlangのDETSテーブル

DETSのto_ets関数を使う前にまず既存のETSテーブルをが必要

iex(1)> :dets.open_file(:dets_table, [{:file,  "/tmp/dets_table"}, {:type, :set}])  # DETSテーブルを作成
{:ok, :dets_table}

iex(2)> :dets.insert(:dets_table, {:a, 1})  # データをinsert
:ok

iex(3)> :dets.insert(:dets_table, {:b, 2})
:ok

iex(4)> :ets.new(:ets_table, [:named_table, :set])  # DETSのto_etsを使う前にETSが必要
:ets_table

iex(5)> :dets.to_ets(:dets_table, :ets_table) # to_etsを実行
:ets_table

iex(6)> :ets.tab2list(:ets_table)  # これでETSも使えるようになった
[b: 2, a: 1]

iex(7)> :dets.lookup(:dets_table, :a)   # DETSの簡単なlookup
[a: 1]

iex(8)> :dets.lookup(:dets_table, :b)
[b: 2]

DETSテーブルのtraverse関数を使ってテーブルのすべてのレコードをリスト, 参照リンク

iterator = fn(rec) -> {:continue, rec} end
res = :dets.traverse(ref, iterator)

DETSテーブルのmatch関数で一部のレコードを取得

{:ok, ref} = :dets.open_file(:dets_table, [{:file,  "/tmp/dets_table"}, {:type, :bag}])

> :dets.insert(ref, {"bucket01", "api-key01", {{2016, 4, 1}, {1, 1, 1}}})
:ok

> :dets.insert(ref, {"bucket02", "api-key01", {{2016, 4, 1}, {10, 1, 1}}})
:ok

> :dets.insert(ref, {"bucket03", "api-key02", {{2016, 4, 2}, {1, 1, 1}}})
:ok

> :dets.insert(ref, {"bucket04", "api-key02", {{2016, 4, 2}, {10, 1, 1}}})
:ok

> :dets.match(ref, {:'$1', :'$2', {{2016, 4, 1}, {:'_', :'_', :'_'}}}) # 4月1日のデータを取得
[["bucket01", "api-key01"], ["bucket02", "api-key01"]]

> :dets.match(ref, {:'$1', :'$2', {{2016, 4, 1}, :'_'}}) # 4月1日のデータを取得
[["bucket01", "api-key01"], ["bucket02", "api-key01"]]

> :dets.match(ref, {:'$1', :'$2', {{2016, 4, :'_'}, {10, 1, :'_'}}}) # 10時1分のデータを取得
[["bucket02", "api-key01"], ["bucket04", "api-key02"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment