一、表遍历
通过ets:first/1获取表的第一个关键字,表中下一个关键字用ets:next/2得到,直到ets:next/2返回'$end_of_table'
当多几个进程并发访问ets表时,可以使用ets:safe_fixtable/2函数来保证,每个元素只被访问一次。
-module(traversal_ets).
-export([traversal_ets/1]).
traversal_ets(Tab) ->
traversal_ets(Tab, ets:first(Tab), []).
traversal_ets(_,'$end_of_table',Acc) ->
Acc;
traversal_ets(Tab, Prv, Acc) ->
traversal_ets(Tab, ets:next(Tab,Prv), [Prv|Acc]).
二、提取表信息,匹配match和match_object
24> ets:new(countries, [bag,named_table]).
countries
25> ets:insert(countries,{yves,france,cook}).
true
26> ets:insert(countries,{marcoitaly,cook}).
true
27> ets:insert(countries,{sean,ireland,bartender}).
true
28> ets:insert(countries,{chris,ireland,tester}).
true
1、match指定匹配输出
9> ets:match(countries,{'$1',ireland,'_'}).
[[sean],[chris]]
10> ets:match(countries,{'$1','$0',cook}).
[[italy,marco],[france,yves]]
11> ets:match(countries,{'$2',ireland,'_'}).
[[sean],[chris]]
12> ets:match(countries,{'$2',cook,'_'}).
[]
2、matc_object全部匹配模式元祖
13> ets:match_object(countries,{'_',ireland,'_'}).
[{sean,ireland,bartender},{chris,ireland,tester}]
3、match_delete 删除匹配输出
14> NewTab = ets:match_delete(countries,{'_',ireland,'_'}).
true
三、提取表信息筛选
ets:select
1、用匹配规约做参数
ets:select(countries,[{{'$1','$2','$3'},[{'/=','$3',cook}],[['$2','$1']]}]).
{'$1','$2','$3'} 模式
{'/=','$3',cook}保护元
['$2','$1'] 返回表达式
2、用ets:fun2ms返回匹配规约
30> MS = ets:fun2ms(fun({Name, Country,Job}) when Job /= cook ->
30> [Country,Name] end).
[{{'$1','$2','$3'},[{'/=','$3',cook}],[['$2','$1']]}]
31> ets:select(countries, MS).
[[ireland,sean],[ireland,chris]]