1ets(3) Erlang Module Definition ets(3)
2
3
4
6 ets - Built-in term storage.
7
9 This module is an interface to the Erlang built-in term storage BIFs.
10 These provide the ability to store very large quantities of data in an
11 Erlang runtime system, and to have constant access time to the data.
12 (In the case of ordered_set, see below, access time is proportional to
13 the logarithm of the number of stored objects.)
14
15 Data is organized as a set of dynamic tables, which can store tuples.
16 Each table is created by a process. When the process terminates, the
17 table is automatically destroyed. Every table has access rights set at
18 creation.
19
20 Tables are divided into four different types, set, ordered_set, bag,
21 and duplicate_bag. A set or ordered_set table can only have one object
22 associated with each key. A bag or duplicate_bag table can have many
23 objects associated with each key.
24
25 Note:
26 The number of tables stored at one Erlang node used to be limited. This
27 is no longer the case (except by memory usage). The previous default
28 limit was about 1400 tables and could be increased by setting the envi‐
29 ronment variable ERL_MAX_ETS_TABLES or the command line option +e be‐
30 fore starting the Erlang runtime system. This hard limit has been re‐
31 moved, but it is currently useful to set the ERL_MAX_ETS_TABLES anyway.
32 It should be set to an approximate of the maximum amount of tables used
33 since an internal table for named tables is sized using this value. If
34 large amounts of named tables are used and ERL_MAX_ETS_TABLES hasn't
35 been increased, the performance of named table lookup will degrade.
36
37
38 Notice that there is no automatic garbage collection for tables. Even
39 if there are no references to a table from any process, it is not auto‐
40 matically destroyed unless the owner process terminates. To destroy a
41 table explicitly, use function delete/1. The default owner is the
42 process that created the table. To transfer table ownership at process
43 termination, use option heir or call give_away/3.
44
45 Some implementation details:
46
47 * In the current implementation, every object insert and look-up op‐
48 eration results in a copy of the object.
49
50 * '$end_of_table' is not to be used as a key, as this atom is used to
51 mark the end of the table when using functions first/1 and next/2.
52
53 Notice the subtle difference between matching and comparing equal,
54 which is demonstrated by table types set and ordered_set:
55
56 * Two Erlang terms match if they are of the same type and have the
57 same value, so that 1 matches 1, but not 1.0 (as 1.0 is a float()
58 and not an integer()).
59
60 * Two Erlang terms compare equal if they either are of the same type
61 and value, or if both are numeric types and extend to the same
62 value, so that 1 compares equal to both 1 and 1.0.
63
64 * The ordered_set works on the Erlang term order and no defined order
65 exists between an integer() and a float() that extends to the same
66 value. Hence the key 1 and the key 1.0 are regarded as equal in an
67 ordered_set table.
68
70 Functions in this module fail by raising an error exception with error
71 reason:
72
73 badarg:
74 If any argument has the wrong format.
75
76 badarg:
77 If the table identifier is invalid.
78
79 badarg:
80 If the operation is denied because of table access rights (pro‐
81 tected or private).
82
83 system_limit:
84 Modification of a value causes it to not be representable inter‐
85 nally in the VM. For example, incrementation of a counter past the
86 largest integer representable.
87
88 system_limit:
89 If a match specification passed as argument has excessive nesting
90 which causes scheduler stack exhaustion for the scheduler that the
91 calling process is executing on. Scheduler stack size can be con‐
92 figured when starting the runtime system.
93
95 This module provides some limited support for concurrent access. All
96 updates to single objects are guaranteed to be both atomic and iso‐
97 lated. This means that an updating operation to a single object either
98 succeeds or fails completely without any effect (atomicity) and that no
99 intermediate results of the update can be seen by other processes (iso‐
100 lation). Some functions that update many objects state that they even
101 guarantee atomicity and isolation for the entire operation. In database
102 terms the isolation level can be seen as "serializable", as if all iso‐
103 lated operations are carried out serially, one after the other in a
104 strict order.
105
107 There are different ways to traverse through the objects of a table.
108
109 * Single-step traversal one key at at time, using first/1, next/2,
110 last/1 and prev/2.
111
112 * Search with simple match patterns, using match/1/2/3,
113 match_delete/2 and match_object/1/2/3.
114
115 * Search with more powerful match specifications, using select/1/2/3,
116 select_count/2, select_delete/2, select_replace/2 and select_re‐
117 verse/1/2/3.
118
119 * Table conversions, using tab2file/2/3 and tab2list/1.
120
121 No table traversal will guarantee a consistent snapshot of the entire
122 table if the table is also updated by concurrent processes during the
123 traversal. The result of each concurrently updated object may be seen
124 (or not) depending on if it has happened when the traversal visits that
125 part of the table. The only way to guarantee a full consistent table
126 snapshot (if you really need that) is to disallow concurrent updates
127 during the entire traversal.
128
129 Moreover, traversals not done in a safe way, on tables where keys are
130 inserted or deleted during the traversal, may yield the following unde‐
131 sired effects:
132
133 * Any key may be missed.
134
135 * Any key may be found more than once.
136
137 * The traversal may fail with badarg exception if keys are deleted.
138
139 A table traversal is safe if either
140
141 * the table is of type ordered_set.
142
143 * the entire table traversal is done within one ETS function call.
144
145 * function safe_fixtable/2 is used to keep the table fixated during
146 the entire traversal.
147
148 Note:
149 Even though the access of a single object is always guaranteed to be
150 atomic and isolated, each traversal through a table to find the next
151 key is not done with such guarantees. This is often not a problem, but
152 may cause rare subtle "unexpected" effects if a concurrent process in‐
153 serts objects during a traversal. For example, consider one process do‐
154 ing
155
156 ets:new(t, [ordered_set, named_table]),
157 ets:insert(t, {1}),
158 ets:insert(t, {2}),
159 ets:insert(t, {3}),
160
161
162 A concurrent call to ets:first(t), done by another process, may then in
163 rare cases return 2 even though 2 has never existed in the table or‐
164 dered as the first key. In the same way, a concurrent call to
165 ets:next(t, 1) may return 3 even though 3 never existed in the table
166 ordered directly after 1.
167
168 Effects like this are improbable but possible. The probability will
169 further be reduced (if not vanish) if table option write_concurrency is
170 not enabled. This can also only be a potential concern for ordered_set
171 where the traversal order is defined.
172
173
174 Traversals using match and select functions may not need to scan the
175 entire table depending on how the key is specified. A match pattern
176 with a fully bound key (without any match variables) will optimize the
177 operation to a single key lookup without any table traversal at all.
178 For ordered_set a partially bound key will limit the traversal to only
179 scan a subset of the table based on term order. A partially bound key
180 is either a list or a tuple with a prefix that is fully bound. Example:
181
182 1> T = ets:new(t,[ordered_set]), ets:insert(T, {"555-1234", "John Smith"}).
183 true
184 2> %% Efficient search of all with area code 555
185 2> ets:match(T,{[$5,$5,$5,$- |'$1'],'$2'}).
186 [["1234","John Smith"]]
187
188
190 Some of the functions use a match specification, match_spec. For a
191 brief explanation, see select/2. For a detailed description, see sec‐
192 tion Match Specifications in Erlang in ERTS User's Guide.
193
194 A match specifications with excessive nesting will cause a system_limit
195 error exception to be raised.
196
198 access() = public | protected | private
199
200 continuation()
201
202 Opaque continuation used by select/1,3, select_reverse/1,3,
203 match/1,3, and match_object/1,3.
204
205 match_spec() = [{match_pattern(), [term()], [term()]}]
206
207 A match specification, see above.
208
209 comp_match_spec()
210
211 A compiled match specification.
212
213 match_pattern() = atom() | tuple()
214
215 tab() = atom() | tid()
216
217 tid()
218
219 A table identifier, as returned by new/2.
220
221 type() = set | ordered_set | bag | duplicate_bag
222
224 all() -> [Tab]
225
226 Types:
227
228 Tab = tab()
229
230 Returns a list of all tables at the node. Named tables are spec‐
231 ified by their names, unnamed tables are specified by their ta‐
232 ble identifiers.
233
234 There is no guarantee of consistency in the returned list. Ta‐
235 bles created or deleted by other processes "during" the
236 ets:all() call either are or are not included in the list. Only
237 tables created/deleted before ets:all() is called are guaranteed
238 to be included/excluded.
239
240 delete(Tab) -> true
241
242 Types:
243
244 Tab = tab()
245
246 Deletes the entire table Tab.
247
248 delete(Tab, Key) -> true
249
250 Types:
251
252 Tab = tab()
253 Key = term()
254
255 Deletes all objects with key Key from table Tab.
256
257 delete_all_objects(Tab) -> true
258
259 Types:
260
261 Tab = tab()
262
263 Delete all objects in the ETS table Tab. The operation is guar‐
264 anteed to be atomic and isolated.
265
266 delete_object(Tab, Object) -> true
267
268 Types:
269
270 Tab = tab()
271 Object = tuple()
272
273 Delete the exact object Object from the ETS table, leaving ob‐
274 jects with the same key but other differences (useful for type
275 bag). In a duplicate_bag table, all instances of the object are
276 deleted.
277
278 file2tab(Filename) -> {ok, Tab} | {error, Reason}
279
280 Types:
281
282 Filename = file:name()
283 Tab = tab()
284 Reason = term()
285
286 Reads a file produced by tab2file/2 or tab2file/3 and creates
287 the corresponding table Tab.
288
289 Equivalent to file2tab(Filename, []).
290
291 file2tab(Filename, Options) -> {ok, Tab} | {error, Reason}
292
293 Types:
294
295 Filename = file:name()
296 Tab = tab()
297 Options = [Option]
298 Option = {verify, boolean()}
299 Reason = term()
300
301 Reads a file produced by tab2file/2 or tab2file/3 and creates
302 the corresponding table Tab.
303
304 The only supported option is {verify,boolean()}. If verification
305 is turned on (by specifying {verify,true}), the function uses
306 whatever information is present in the file to assert that the
307 information is not damaged. How this is done depends on which
308 extended_info was written using tab2file/3.
309
310 If no extended_info is present in the file and {verify,true} is
311 specified, the number of objects written is compared to the size
312 of the original table when the dump was started. This can make
313 verification fail if the table was public and objects were added
314 or removed while the table was dumped to file. To avoid this
315 problem, either do not verify files dumped while updated simul‐
316 taneously or use option {extended_info, [object_count]} to
317 tab2file/3, which extends the information in the file with the
318 number of objects written.
319
320 If verification is turned on and the file was written with op‐
321 tion {extended_info, [md5sum]}, reading the file is slower and
322 consumes radically more CPU time than otherwise.
323
324 {verify,false} is the default.
325
326 first(Tab) -> Key | '$end_of_table'
327
328 Types:
329
330 Tab = tab()
331 Key = term()
332
333 Returns the first key Key in table Tab. For an ordered_set ta‐
334 ble, the first key in Erlang term order is returned. For other
335 table types, the first key according to the internal order of
336 the table is returned. If the table is empty, '$end_of_table' is
337 returned.
338
339 To find subsequent keys in the table, use next/2.
340
341 foldl(Function, Acc0, Tab) -> Acc1
342
343 Types:
344
345 Function = fun((Element :: term(), AccIn) -> AccOut)
346 Tab = tab()
347 Acc0 = Acc1 = AccIn = AccOut = term()
348
349 Acc0 is returned if the table is empty. This function is similar
350 to lists:foldl/3. The table elements are traversed in an unspec‐
351 ified order, except for ordered_set tables, where they are tra‐
352 versed first to last.
353
354 If Function inserts objects into the table, or another process
355 inserts objects into the table, those objects can (depending on
356 key ordering) be included in the traversal.
357
358 foldr(Function, Acc0, Tab) -> Acc1
359
360 Types:
361
362 Function = fun((Element :: term(), AccIn) -> AccOut)
363 Tab = tab()
364 Acc0 = Acc1 = AccIn = AccOut = term()
365
366 Acc0 is returned if the table is empty. This function is similar
367 to lists:foldr/3. The table elements are traversed in an unspec‐
368 ified order, except for ordered_set tables, where they are tra‐
369 versed last to first.
370
371 If Function inserts objects into the table, or another process
372 inserts objects into the table, those objects can (depending on
373 key ordering) be included in the traversal.
374
375 from_dets(Tab, DetsTab) -> true
376
377 Types:
378
379 Tab = tab()
380 DetsTab = dets:tab_name()
381
382 Fills an already created ETS table with the objects in the al‐
383 ready opened Dets table DetsTab. Existing objects in the ETS ta‐
384 ble are kept unless overwritten.
385
386 If any of the tables does not exist or the Dets table is not
387 open, a badarg exception is raised.
388
389 fun2ms(LiteralFun) -> MatchSpec
390
391 Types:
392
393 LiteralFun = function()
394 MatchSpec = match_spec()
395
396 Pseudo function that by a parse_transform translates LiteralFun
397 typed as parameter in the function call to a match specifica‐
398 tion. With "literal" is meant that the fun must textually be
399 written as the parameter of the function, it cannot be held in a
400 variable that in turn is passed to the function.
401
402 The parse transform is provided in the ms_transform module and
403 the source must include file ms_transform.hrl in STDLIB for this
404 pseudo function to work. Failing to include the hrl file in the
405 source results in a runtime error, not a compile time error. The
406 include file is easiest included by adding line -in‐
407 clude_lib("stdlib/include/ms_transform.hrl"). to the source
408 file.
409
410 The fun is very restricted, it can take only a single parameter
411 (the object to match): a sole variable or a tuple. It must use
412 the is_ guard tests. Language constructs that have no represen‐
413 tation in a match specification (if, case, receive, and so on)
414 are not allowed.
415
416 The return value is the resulting match specification.
417
418 Example:
419
420 1> ets:fun2ms(fun({M,N}) when N > 3 -> M end).
421 [{{'$1','$2'},[{'>','$2',3}],['$1']}]
422
423 Variables from the environment can be imported, so that the fol‐
424 lowing works:
425
426 2> X=3.
427 3
428 3> ets:fun2ms(fun({M,N}) when N > X -> M end).
429 [{{'$1','$2'},[{'>','$2',{const,3}}],['$1']}]
430
431 The imported variables are replaced by match specification const
432 expressions, which is consistent with the static scoping for Er‐
433 lang funs. However, local or global function calls cannot be in
434 the guard or body of the fun. Calls to built-in match specifica‐
435 tion functions is of course allowed:
436
437 4> ets:fun2ms(fun({M,N}) when N > X, my_fun(M) -> M end).
438 Error: fun containing local Erlang function calls
439 ('my_fun' called in guard) cannot be translated into match_spec
440 {error,transform_error}
441 5> ets:fun2ms(fun({M,N}) when N > X, is_atom(M) -> M end).
442 [{{'$1','$2'},[{'>','$2',{const,3}},{is_atom,'$1'}],['$1']}]
443
444 As shown by the example, the function can be called from the
445 shell also. The fun must be literally in the call when used from
446 the shell as well.
447
448 Warning:
449 If the parse_transform is not applied to a module that calls
450 this pseudo function, the call fails in runtime (with a badarg).
451 The ets module exports a function with this name, but it is
452 never to be called except when using the function in the shell.
453 If the parse_transform is properly applied by including header
454 file ms_transform.hrl, compiled code never calls the function,
455 but the function call is replaced by a literal match specifica‐
456 tion.
457
458
459 For more information, see ms_transform(3).
460
461 give_away(Tab, Pid, GiftData) -> true
462
463 Types:
464
465 Tab = tab()
466 Pid = pid()
467 GiftData = term()
468
469 Make process Pid the new owner of table Tab. If successful, mes‐
470 sage {'ETS-TRANSFER',Tab,FromPid,GiftData} is sent to the new
471 owner.
472
473 The process Pid must be alive, local, and not already the owner
474 of the table. The calling process must be the table owner.
475
476 Notice that this function does not affect option heir of the ta‐
477 ble. A table owner can, for example, set heir to itself, give
478 the table away, and then get it back if the receiver terminates.
479
480 i() -> ok
481
482 Displays information about all ETS tables on a terminal.
483
484 i(Tab) -> ok
485
486 Types:
487
488 Tab = tab()
489
490 Browses table Tab on a terminal.
491
492 info(Tab) -> InfoList | undefined
493
494 Types:
495
496 Tab = tab()
497 InfoList = [InfoTuple]
498 InfoTuple =
499 {compressed, boolean()} |
500 {decentralized_counters, boolean()} |
501 {heir, pid() | none} |
502 {id, tid()} |
503 {keypos, integer() >= 1} |
504 {memory, integer() >= 0} |
505 {name, atom()} |
506 {named_table, boolean()} |
507 {node, node()} |
508 {owner, pid()} |
509 {protection, access()} |
510 {size, integer() >= 0} |
511 {type, type()} |
512 {write_concurrency, boolean()} |
513 {read_concurrency, boolean()}
514
515 Returns information about table Tab as a list of tuples. If Tab
516 has the correct type for a table identifier, but does not refer
517 to an existing ETS table, undefined is returned. If Tab is not
518 of the correct type, a badarg exception is raised.
519
520 {compressed, boolean()}:
521 Indicates if the table is compressed.
522
523 {decentralized_counters, boolean()}:
524 Indicates whether the table uses decentralized_counters.
525
526 {heir, pid() | none}:
527 The pid of the heir of the table, or none if no heir is set.
528
529 {id,tid()}:
530 The table identifier.
531
532 {keypos, integer() >= 1}:
533 The key position.
534
535 {memory, integer() >= 0:
536 The number of words allocated to the table.
537
538 {name, atom()}:
539 The table name.
540
541 {named_table, boolean()}:
542 Indicates if the table is named.
543
544 {node, node()}:
545 The node where the table is stored. This field is no longer
546 meaningful, as tables cannot be accessed from other nodes.
547
548 {owner, pid()}:
549 The pid of the owner of the table.
550
551 {protection,access()}:
552 The table access rights.
553
554 {size, integer() >= 0:
555 The number of objects inserted in the table.
556
557 {type,type()}:
558 The table type.
559
560 {read_concurrency, boolean()}:
561 Indicates whether the table uses read_concurrency or not.
562
563 {write_concurrency, boolean()}:
564 Indicates whether the table uses write_concurrency.
565
566 Note:
567 The execution time of this function is affected by the decen‐
568 tralized_counters table option. The execution time is much
569 longer when the decentralized_counters option is set to true
570 than when the decentralized_counters option is set to false.
571
572
573 info(Tab, Item) -> Value | undefined
574
575 Types:
576
577 Tab = tab()
578 Item =
579 binary | compressed | decentralized_counters | fixed |
580 heir |
581 id | keypos | memory | name | named_table | node | owner
582 |
583 protection | safe_fixed | safe_fixed_monotonic_time |
584 size |
585 stats | type | write_concurrency | read_concurrency
586 Value = term()
587
588 Returns the information associated with Item for table Tab, or
589 returns undefined if Tab does not refer an existing ETS table.
590 If Tab is not of the correct type, or if Item is not one of the
591 allowed values, a badarg exception is raised.
592
593 In addition to the {Item,Value} pairs defined for info/1, the
594 following items are allowed:
595
596 * Item=binary, Value=BinInfo
597
598 BinInfo is a list containing miscellaneous information about
599 binaries kept by the table. This Item can be changed or re‐
600 moved without prior notice. In the current implementation
601 BinInfo is a list of tuples {BinaryId,BinarySize,BinaryRefc‐
602 Count}.
603
604 * Item=fixed, Value=boolean()
605
606 Indicates if the table is fixed by any process.
607
608 *
609
610
611 Item=safe_fixed|safe_fixed_monotonic_time, Value={Fixation‐
612 Time,Info}|false
613
614 If the table is fixed using safe_fixtable/2, the call re‐
615 turns a tuple where FixationTime is the last time when the
616 table changed from unfixed to fixed.
617
618 The format and value of FixationTime depends on Item:
619
620 safe_fixed:
621 FixationTime corresponds to the result returned by er‐
622 lang:timestamp/0 at the time of fixation. Notice that when
623 the system uses single or multi time warp modes this can
624 produce strange results, as the use of safe_fixed is not
625 time warp safe. Time warp safe code must use
626 safe_fixed_monotonic_time instead.
627
628 safe_fixed_monotonic_time:
629 FixationTime corresponds to the result returned by er‐
630 lang:monotonic_time/0 at the time of fixation. The use of
631 safe_fixed_monotonic_time is time warp safe.
632
633 Info is a possibly empty lists of tuples {Pid,RefCount}, one
634 tuple for every process the table is fixed by now. RefCount
635 is the value of the reference counter and it keeps track of
636 how many times the table has been fixed by the process.
637
638 Table fixations are not limited to safe_fixtable/2. Tempo‐
639 rary fixations may also be done by for example traversing
640 functions like select and match. Such table fixations are
641 automatically released before the corresponding functions
642 returns, but they may be seen by a concurrent call to
643 ets:info(T,safe_fixed|safe_fixed_monotonic_time).
644
645 If the table is not fixed at all, the call returns false.
646
647 * Item=stats, Value=tuple()
648
649 Returns internal statistics about tables on an internal for‐
650 mat used by OTP test suites. Not for production use.
651
652 Note:
653 The execution time of this function is affected by the decen‐
654 tralized_counters table option when the second argument of the
655 function is size or memory. The execution time is much longer
656 when the decentralized_counters option is set to true than when
657 the decentralized_counters option is set to false.
658
659
660 init_table(Tab, InitFun) -> true
661
662 Types:
663
664 Tab = tab()
665 InitFun = fun((Arg) -> Res)
666 Arg = read | close
667 Res = end_of_input | {Objects :: [term()], InitFun} | term()
668
669 Replaces the existing objects of table Tab with objects created
670 by calling the input function InitFun, see below. This function
671 is provided for compatibility with the dets module, it is not
672 more efficient than filling a table by using insert/2.
673
674 When called with argument read, the function InitFun is assumed
675 to return end_of_input when there is no more input, or {Objects,
676 Fun}, where Objects is a list of objects and Fun is a new input
677 function. Any other value Value is returned as an error {error,
678 {init_fun, Value}}. Each input function is called exactly once,
679 and if an error occur, the last function is called with argument
680 close, the reply of which is ignored.
681
682 If the table type is set and more than one object exists with a
683 given key, one of the objects is chosen. This is not necessarily
684 the last object with the given key in the sequence of objects
685 returned by the input functions. This holds also for duplicated
686 objects stored in tables of type bag.
687
688 insert(Tab, ObjectOrObjects) -> true
689
690 Types:
691
692 Tab = tab()
693 ObjectOrObjects = tuple() | [tuple()]
694
695 Inserts the object or all of the objects in list ObjectOrObjects
696 into table Tab.
697
698 * If the table type is set and the key of the inserted objects
699 matches the key of any object in the table, the old object
700 is replaced.
701
702 * If the table type is ordered_set and the key of the inserted
703 object compares equal to the key of any object in the table,
704 the old object is replaced.
705
706 * If the list contains more than one object with matching keys
707 and the table type is set, one is inserted, which one is not
708 defined. The same holds for table type ordered_set if the
709 keys compare equal.
710
711 The entire operation is guaranteed to be atomic and isolated,
712 even when a list of objects is inserted.
713
714 insert_new(Tab, ObjectOrObjects) -> boolean()
715
716 Types:
717
718 Tab = tab()
719 ObjectOrObjects = tuple() | [tuple()]
720
721 Same as insert/2 except that instead of overwriting objects with
722 the same key (for set or ordered_set) or adding more objects
723 with keys already existing in the table (for bag and dupli‐
724 cate_bag), false is returned.
725
726 If ObjectOrObjects is a list, the function checks every key be‐
727 fore inserting anything. Nothing is inserted unless all keys
728 present in the list are absent from the table. Like insert/2,
729 the entire operation is guaranteed to be atomic and isolated.
730
731 is_compiled_ms(Term) -> boolean()
732
733 Types:
734
735 Term = term()
736
737 Checks if a term represent a valid compiled match specification.
738 A compiled match specifications is only valid on the Erlang node
739 where it was compiled by calling match_spec_compile/1.
740
741 Note:
742 Before STDLIB 3.4 (OTP 20.0) compiled match specifications did
743 not have an external representation. If passed through bi‐
744 nary_to_term(term_to_binary(CMS)) or sent to another node and
745 back, the result was always an empty binary <<>>.
746
747 After STDLIB 3.4 (OTP 20.0) compiled match specifications have
748 an external representation as a node specific reference to the
749 original compiled match specification. If passed through bi‐
750 nary_to_term(term_to_binary(CMS)) or sent to another node and
751 back, the result may or may not be a valid compiled match speci‐
752 fication depending on if the original compiled match specifica‐
753 tion was still alive.
754
755
756 last(Tab) -> Key | '$end_of_table'
757
758 Types:
759
760 Tab = tab()
761 Key = term()
762
763 Returns the last key Key according to Erlang term order in table
764 Tab of type ordered_set. For other table types, the function is
765 synonymous to first/1. If the table is empty, '$end_of_table' is
766 returned.
767
768 To find preceding keys in the table, use prev/2.
769
770 lookup(Tab, Key) -> [Object]
771
772 Types:
773
774 Tab = tab()
775 Key = term()
776 Object = tuple()
777
778 Returns a list of all objects with key Key in table Tab.
779
780 * For tables of type set, bag, or duplicate_bag, an object is
781 returned only if the specified key matches the key of the
782 object in the table.
783
784 * For tables of type ordered_set, an object is returned if the
785 specified key compares equal to the key of an object in the
786 table.
787
788 The difference is the same as between =:= and ==.
789
790 As an example, one can insert an object with integer() 1 as a
791 key in an ordered_set and get the object returned as a result of
792 doing a lookup/2 with float() 1.0 as the key to search for.
793
794 For tables of type set or ordered_set, the function returns ei‐
795 ther the empty list or a list with one element, as there cannot
796 be more than one object with the same key. For tables of type
797 bag or duplicate_bag, the function returns a list of arbitrary
798 length.
799
800 Notice that the time order of object insertions is preserved;
801 the first object inserted with the specified key is the first in
802 the resulting list, and so on.
803
804 Insert and lookup times in tables of type set, bag, and dupli‐
805 cate_bag are constant, regardless of the table size. For the or‐
806 dered_set datatype, time is proportional to the (binary) loga‐
807 rithm of the number of objects.
808
809 lookup_element(Tab, Key, Pos) -> Elem
810
811 Types:
812
813 Tab = tab()
814 Key = term()
815 Pos = integer() >= 1
816 Elem = term() | [term()]
817
818 For a table Tab of type set or ordered_set, the function returns
819 the Pos:th element of the object with key Key.
820
821 For tables of type bag or duplicate_bag, the functions returns a
822 list with the Pos:th element of every object with key Key.
823
824 If no object with key Key exists, the function exits with reason
825 badarg.
826
827 The difference between set, bag, and duplicate_bag on one hand,
828 and ordered_set on the other, regarding the fact that or‐
829 dered_set view keys as equal when they compare equal whereas the
830 other table types regard them equal only when they match, holds
831 for lookup_element/3.
832
833 match(Continuation) -> {[Match], Continuation} | '$end_of_table'
834
835 Types:
836
837 Match = [term()]
838 Continuation = continuation()
839
840 Continues a match started with match/3. The next chunk of the
841 size specified in the initial match/3 call is returned together
842 with a new Continuation, which can be used in subsequent calls
843 to this function.
844
845 When there are no more objects in the table, '$end_of_table' is
846 returned.
847
848 match(Tab, Pattern) -> [Match]
849
850 Types:
851
852 Tab = tab()
853 Pattern = match_pattern()
854 Match = [term()]
855
856 Matches the objects in table Tab against pattern Pattern.
857
858 A pattern is a term that can contain:
859
860 * Bound parts (Erlang terms)
861
862 * '_' that matches any Erlang term
863
864 * Pattern variables '$N', where N=0,1,...
865
866 The function returns a list with one element for each matching
867 object, where each element is an ordered list of pattern vari‐
868 able bindings, for example:
869
870 6> ets:match(T, '$1'). % Matches every object in table
871 [[{rufsen,dog,7}],[{brunte,horse,5}],[{ludde,dog,5}]]
872 7> ets:match(T, {'_',dog,'$1'}).
873 [[7],[5]]
874 8> ets:match(T, {'_',cow,'$1'}).
875 []
876
877 If the key is specified in the pattern, the match is very effi‐
878 cient. If the key is not specified, that is, if it is a variable
879 or an underscore, the entire table must be searched. The search
880 time can be substantial if the table is very large.
881
882 For tables of type ordered_set, the result is in the same order
883 as in a first/next traversal.
884
885 match(Tab, Pattern, Limit) ->
886 {[Match], Continuation} | '$end_of_table'
887
888 Types:
889
890 Tab = tab()
891 Pattern = match_pattern()
892 Limit = integer() >= 1
893 Match = [term()]
894 Continuation = continuation()
895
896 Works like match/2, but returns only a limited (Limit) number of
897 matching objects. Term Continuation can then be used in subse‐
898 quent calls to match/1 to get the next chunk of matching ob‐
899 jects. This is a space-efficient way to work on objects in a ta‐
900 ble, which is faster than traversing the table object by object
901 using first/1 and next/2.
902
903 If the table is empty, '$end_of_table' is returned.
904
905 Use safe_fixtable/2 to guarantee safe traversal for subsequent
906 calls to match/1.
907
908 match_delete(Tab, Pattern) -> true
909
910 Types:
911
912 Tab = tab()
913 Pattern = match_pattern()
914
915 Deletes all objects that match pattern Pattern from table Tab.
916 For a description of patterns, see match/2.
917
918 match_object(Continuation) ->
919 {[Object], Continuation} | '$end_of_table'
920
921 Types:
922
923 Object = tuple()
924 Continuation = continuation()
925
926 Continues a match started with match_object/3. The next chunk of
927 the size specified in the initial match_object/3 call is re‐
928 turned together with a new Continuation, which can be used in
929 subsequent calls to this function.
930
931 When there are no more objects in the table, '$end_of_table' is
932 returned.
933
934 match_object(Tab, Pattern) -> [Object]
935
936 Types:
937
938 Tab = tab()
939 Pattern = match_pattern()
940 Object = tuple()
941
942 Matches the objects in table Tab against pattern Pattern. For a
943 description of patterns, see match/2. The function returns a
944 list of all objects that match the pattern.
945
946 If the key is specified in the pattern, the match is very effi‐
947 cient. If the key is not specified, that is, if it is a variable
948 or an underscore, the entire table must be searched. The search
949 time can be substantial if the table is very large.
950
951 For tables of type ordered_set, the result is in the same order
952 as in a first/next traversal.
953
954 match_object(Tab, Pattern, Limit) ->
955 {[Object], Continuation} | '$end_of_table'
956
957 Types:
958
959 Tab = tab()
960 Pattern = match_pattern()
961 Limit = integer() >= 1
962 Object = tuple()
963 Continuation = continuation()
964
965 Works like match_object/2, but only returns a limited (Limit)
966 number of matching objects. Term Continuation can then be used
967 in subsequent calls to match_object/1 to get the next chunk of
968 matching objects. This is a space-efficient way to work on ob‐
969 jects in a table, which is faster than traversing the table ob‐
970 ject by object using first/1 and next/2.
971
972 If the table is empty, '$end_of_table' is returned.
973
974 Use safe_fixtable/2 to guarantee safe traversal for subsequent
975 calls to match_object/1.
976
977 match_spec_compile(MatchSpec) -> CompiledMatchSpec
978
979 Types:
980
981 MatchSpec = match_spec()
982 CompiledMatchSpec = comp_match_spec()
983
984 Transforms a match specification into an internal representation
985 that can be used in subsequent calls to match_spec_run/2. The
986 internal representation is opaque. To check the validity of a
987 compiled match specification, use is_compiled_ms/1.
988
989 If term MatchSpec does not represent a valid match specifica‐
990 tion, a badarg exception is raised.
991
992 Note:
993 This function has limited use in normal code. It is used by the
994 dets module to perform the dets:select() operations.
995
996
997 match_spec_run(List, CompiledMatchSpec) -> list()
998
999 Types:
1000
1001 List = [term()]
1002 CompiledMatchSpec = comp_match_spec()
1003
1004 Executes the matching specified in a compiled match specifica‐
1005 tion on a list of terms. Term CompiledMatchSpec is to be the re‐
1006 sult of a call to match_spec_compile/1 and is hence the internal
1007 representation of the match specification one wants to use.
1008
1009 The matching is executed on each element in List and the func‐
1010 tion returns a list containing all results. If an element in
1011 List does not match, nothing is returned for that element. The
1012 length of the result list is therefore equal or less than the
1013 length of parameter List.
1014
1015 Example:
1016
1017 The following two calls give the same result (but certainly not
1018 the same execution time):
1019
1020 Table = ets:new...
1021 MatchSpec = ...
1022 % The following call...
1023 ets:match_spec_run(ets:tab2list(Table),
1024 ets:match_spec_compile(MatchSpec)),
1025 % ...gives the same result as the more common (and more efficient)
1026 ets:select(Table, MatchSpec),
1027
1028 Note:
1029 This function has limited use in normal code. It is used by the
1030 dets module to perform the dets:select() operations and by Mne‐
1031 sia during transactions.
1032
1033
1034 member(Tab, Key) -> boolean()
1035
1036 Types:
1037
1038 Tab = tab()
1039 Key = term()
1040
1041 Works like lookup/2, but does not return the objects. Returns
1042 true if one or more elements in the table has key Key, otherwise
1043 false.
1044
1045 new(Name, Options) -> tid() | atom()
1046
1047 Types:
1048
1049 Name = atom()
1050 Options = [Option]
1051 Option =
1052 Type | Access | named_table |
1053 {keypos, Pos} |
1054 {heir, Pid :: pid(), HeirData} |
1055 {heir, none} |
1056 Tweaks
1057 Type = type()
1058 Access = access()
1059 Tweaks =
1060 {write_concurrency, boolean()} |
1061 {read_concurrency, boolean()} |
1062 {decentralized_counters, boolean()} |
1063 compressed
1064 Pos = integer() >= 1
1065 HeirData = term()
1066
1067 Creates a new table and returns a table identifier that can be
1068 used in subsequent operations. The table identifier can be sent
1069 to other processes so that a table can be shared between differ‐
1070 ent processes within a node.
1071
1072 Parameter Options is a list of options that specifies table
1073 type, access rights, key position, and whether the table is
1074 named. Default values are used for omitted options. This means
1075 that not specifying any options ([]) is the same as specifying
1076 [set, protected, {keypos,1}, {heir,none}, {write_concur‐
1077 rency,false}, {read_concurrency,false}, {decentralized_coun‐
1078 ters,false}].
1079
1080 set:
1081 The table is a set table: one key, one object, no order
1082 among objects. This is the default table type.
1083
1084 ordered_set:
1085 The table is a ordered_set table: one key, one object, or‐
1086 dered in Erlang term order, which is the order implied by
1087 the < and > operators. Tables of this type have a somewhat
1088 different behavior in some situations than tables of other
1089 types. Most notably, the ordered_set tables regard keys as
1090 equal when they compare equal, not only when they match.
1091 This means that to an ordered_set table, integer() 1 and
1092 float() 1.0 are regarded as equal. This also means that the
1093 key used to lookup an element not necessarily matches the
1094 key in the returned elements, if float()'s and integer()'s
1095 are mixed in keys of a table.
1096
1097 bag:
1098 The table is a bag table, which can have many objects, but
1099 only one instance of each object, per key.
1100
1101 duplicate_bag:
1102 The table is a duplicate_bag table, which can have many ob‐
1103 jects, including multiple copies of the same object, per
1104 key.
1105
1106 public:
1107 Any process can read or write to the table.
1108
1109 protected:
1110 The owner process can read and write to the table. Other
1111 processes can only read the table. This is the default set‐
1112 ting for the access rights.
1113
1114 private:
1115 Only the owner process can read or write to the table.
1116
1117 named_table:
1118 If this option is present, the table is registered under its
1119 Name which can then be used instead of the table identifier
1120 in subsequent operations.
1121
1122 The function will also return the Name instead of the table
1123 identifier. To get the table identifier of a named table,
1124 use whereis/1.
1125
1126 {keypos,Pos}:
1127 Specifies which element in the stored tuples to use as key.
1128 By default, it is the first element, that is, Pos=1. How‐
1129 ever, this is not always appropriate. In particular, we do
1130 not want the first element to be the key if we want to store
1131 Erlang records in a table.
1132
1133 Notice that any tuple stored in the table must have at least
1134 Pos number of elements.
1135
1136 {heir,Pid,HeirData} | {heir,none}:
1137 Set a process as heir. The heir inherits the table if the
1138 owner terminates. Message {'ETS-TRANS‐
1139 FER',tid(),FromPid,HeirData} is sent to the heir when that
1140 occurs. The heir must be a local process. Default heir is
1141 none, which destroys the table when the owner terminates.
1142
1143 {write_concurrency,boolean()}:
1144 Performance tuning. Defaults to false, in which case an op‐
1145 eration that mutates (writes to) the table obtains exclusive
1146 access, blocking any concurrent access of the same table un‐
1147 til finished. If set to true, the table is optimized to con‐
1148 current write access. Different objects of the same table
1149 can be mutated (and read) by concurrent processes. This is
1150 achieved to some degree at the expense of memory consumption
1151 and the performance of sequential access and concurrent
1152 reading.
1153
1154 The write_concurrency option can be combined with the op‐
1155 tions read_concurrency and decentralized_counters. You typi‐
1156 cally want to combine write_concurrency with read_concur‐
1157 rency when large concurrent read bursts and large concurrent
1158 write bursts are common; for more information, see option
1159 read_concurrency. The decentralized_counters option is
1160 turned on by default for tables of type ordered_set with the
1161 write_concurrency option enabled, and the decentral‐
1162 ized_counters option is turned off by default for all other
1163 table types. For more information, see the documentation for
1164 the decentralized_counters option.
1165
1166 Notice that this option does not change any guarantees about
1167 atomicity and isolation. Functions that makes such promises
1168 over many objects (like insert/2) gain less (or nothing)
1169 from this option.
1170
1171 The memory consumption inflicted by both write_concurrency
1172 and read_concurrency is a constant overhead per table for
1173 set, bag and duplicate_bag. For ordered_set the memory over‐
1174 head depends on the number of inserted objects and the
1175 amount of actual detected concurrency in runtime. The memory
1176 overhead can be especially large when both options are com‐
1177 bined.
1178
1179 Note:
1180 Prior to stdlib-3.7 (OTP-22.0) write_concurrency had no effect
1181 on ordered_set.
1182
1183
1184 {read_concurrency,boolean()}:
1185 Performance tuning. Defaults to false. When set to true, the
1186 table is optimized for concurrent read operations. When this
1187 option is enabled read operations become much cheaper; espe‐
1188 cially on systems with multiple physical processors. How‐
1189 ever, switching between read and write operations becomes
1190 more expensive.
1191
1192 You typically want to enable this option when concurrent
1193 read operations are much more frequent than write opera‐
1194 tions, or when concurrent reads and writes comes in large
1195 read and write bursts (that is, many reads not interrupted
1196 by writes, and many writes not interrupted by reads).
1197
1198 You typically do not want to enable this option when the
1199 common access pattern is a few read operations interleaved
1200 with a few write operations repeatedly. In this case, you
1201 would get a performance degradation by enabling this option.
1202
1203 Option read_concurrency can be combined with option
1204 write_concurrency. You typically want to combine these when
1205 large concurrent read bursts and large concurrent write
1206 bursts are common.
1207
1208 {decentralized_counters,boolean()}:
1209 Performance tuning. Defaults to true for tables of type or‐
1210 dered_set with the write_concurrency option enabled, and de‐
1211 faults to false for all other table types. This option has
1212 no effect if the write_concurrency option is set to false.
1213
1214 When this option is set to true, the table is optimized for
1215 frequent concurrent calls to operations that modify the ta‐
1216 bles size and/or its memory consumption (e.g., insert/2 and
1217 delete/2). The drawback is that calls to info/1 and info/2
1218 with size or memory as the second argument can get much
1219 slower when the decentralized_counters option is turned on.
1220
1221 When this option is enabled the counters for the table size
1222 and memory consumption are distributed over several cache
1223 lines and the scheduling threads are mapped to one of those
1224 cache lines. The erl option +dcg can be used to control the
1225 number of cache lines that the counters are distributed
1226 over.
1227
1228 compressed:
1229 If this option is present, the table data is stored in a
1230 more compact format to consume less memory. However, it will
1231 make table operations slower. Especially operations that
1232 need to inspect entire objects, such as match and select,
1233 get much slower. The key element is not compressed.
1234
1235 next(Tab, Key1) -> Key2 | '$end_of_table'
1236
1237 Types:
1238
1239 Tab = tab()
1240 Key1 = Key2 = term()
1241
1242 Returns the next key Key2, following key Key1 in table Tab. For
1243 table type ordered_set, the next key in Erlang term order is re‐
1244 turned. For other table types, the next key according to the in‐
1245 ternal order of the table is returned. If no next key exists,
1246 '$end_of_table' is returned.
1247
1248 To find the first key in the table, use first/1.
1249
1250 Unless a table of type set, bag, or duplicate_bag is fixated us‐
1251 ing safe_fixtable/2, a call to next/2 will fail if Key1 no
1252 longer exists in the table. For table type ordered_set, the
1253 function always returns the next key after Key1 in term order,
1254 regardless whether Key1 ever existed in the table.
1255
1256 prev(Tab, Key1) -> Key2 | '$end_of_table'
1257
1258 Types:
1259
1260 Tab = tab()
1261 Key1 = Key2 = term()
1262
1263 Returns the previous key Key2, preceding key Key1 according to
1264 Erlang term order in table Tab of type ordered_set. For other
1265 table types, the function is synonymous to next/2. If no previ‐
1266 ous key exists, '$end_of_table' is returned.
1267
1268 To find the last key in an ordered_set table, use last/1.
1269
1270 rename(Tab, Name) -> Name
1271
1272 Types:
1273
1274 Tab = tab()
1275 Name = atom()
1276
1277 Renames the named table Tab to the new name Name. Afterwards,
1278 the old name cannot be used to access the table. Renaming an un‐
1279 named table has no effect.
1280
1281 repair_continuation(Continuation, MatchSpec) -> Continuation
1282
1283 Types:
1284
1285 Continuation = continuation()
1286 MatchSpec = match_spec()
1287
1288 Restores an opaque continuation returned by select/3 or select/1
1289 if the continuation has passed through external term format
1290 (been sent between nodes or stored on disk).
1291
1292 The reason for this function is that continuation terms contain
1293 compiled match specifications and may therefore be invalidated
1294 if converted to external term format. Given that the original
1295 match specification is kept intact, the continuation can be re‐
1296 stored, meaning it can once again be used in subsequent select/1
1297 calls even though it has been stored on disk or on another node.
1298
1299 Examples:
1300
1301 The following sequence of calls may fail:
1302
1303 T=ets:new(x,[]),
1304 MS = ets:fun2ms(fun({N,_}=A) when (N rem 10) =:= 0 -> A end),
1305 {_,C} = ets:select(T, MS, 10),
1306 MaybeBroken = binary_to_term(term_to_binary(C)),
1307 ets:select(MaybeBroken).
1308
1309 The following sequence works, as the call to repair_continua‐
1310 tion/2 reestablishes the MaybeBroken continuation.
1311
1312 T=ets:new(x,[]),
1313 MS = ets:fun2ms(fun({N,_}=A) when (N rem 10) =:= 0 -> A end),
1314 {_,C} = ets:select(T,MS,10),
1315 MaybeBroken = binary_to_term(term_to_binary(C)),
1316 ets:select(ets:repair_continuation(MaybeBroken,MS)).
1317
1318 Note:
1319 This function is rarely needed in application code. It is used
1320 by Mnesia to provide distributed select/3 and select/1 se‐
1321 quences. A normal application would either use Mnesia or keep
1322 the continuation from being converted to external format.
1323
1324 The actual behavior of compiled match specifications when recre‐
1325 ated from external format has changed and may change in future
1326 releases, but this interface remains for backward compatibility.
1327 See is_compiled_ms/1.
1328
1329
1330 safe_fixtable(Tab, Fix) -> true
1331
1332 Types:
1333
1334 Tab = tab()
1335 Fix = boolean()
1336
1337 Fixes a table of type set, bag, or duplicate_bag for safe tra‐
1338 versal using first/1 & next/2, match/3 & match/1, match_object/3
1339 & match_object/1, or select/3 & select/1.
1340
1341 A process fixes a table by calling safe_fixtable(Tab, true). The
1342 table remains fixed until the process releases it by calling
1343 safe_fixtable(Tab, false), or until the process terminates.
1344
1345 If many processes fix a table, the table remains fixed until all
1346 processes have released it (or terminated). A reference counter
1347 is kept on a per process basis, and N consecutive fixes requires
1348 N releases to release the table.
1349
1350 When a table is fixed, a sequence of first/1 and next/2 calls
1351 are guaranteed to succeed even if keys are removed during the
1352 traversal. The keys for objects inserted or deleted during a
1353 traversal may or may not be returned by next/2 depending on the
1354 ordering of keys within the table and if the key exists at the
1355 time next/2 is called.
1356
1357 Example:
1358
1359 clean_all_with_value(Tab,X) ->
1360 safe_fixtable(Tab,true),
1361 clean_all_with_value(Tab,X,ets:first(Tab)),
1362 safe_fixtable(Tab,false).
1363
1364 clean_all_with_value(Tab,X,'$end_of_table') ->
1365 true;
1366 clean_all_with_value(Tab,X,Key) ->
1367 case ets:lookup(Tab,Key) of
1368 [{Key,X}] ->
1369 ets:delete(Tab,Key);
1370 _ ->
1371 true
1372 end,
1373 clean_all_with_value(Tab,X,ets:next(Tab,Key)).
1374
1375 Notice that deleted objects are not freed from a fixed table un‐
1376 til it has been released. If a process fixes a table but never
1377 releases it, the memory used by the deleted objects is never
1378 freed. The performance of operations on the table also degrades
1379 significantly.
1380
1381 To retrieve information about which processes have fixed which
1382 tables, use info(Tab, safe_fixed_monotonic_time). A system with
1383 many processes fixing tables can need a monitor that sends
1384 alarms when tables have been fixed for too long.
1385
1386 Notice that safe_fixtable/2 is not necessary for table type or‐
1387 dered_set and for traversals done by a single ETS function call,
1388 like select/2.
1389
1390 select(Continuation) -> {[Match], Continuation} | '$end_of_table'
1391
1392 Types:
1393
1394 Match = term()
1395 Continuation = continuation()
1396
1397 Continues a match started with select/3. The next chunk of the
1398 size specified in the initial select/3 call is returned together
1399 with a new Continuation, which can be used in subsequent calls
1400 to this function.
1401
1402 When there are no more objects in the table, '$end_of_table' is
1403 returned.
1404
1405 select(Tab, MatchSpec) -> [Match]
1406
1407 Types:
1408
1409 Tab = tab()
1410 MatchSpec = match_spec()
1411 Match = term()
1412
1413 Matches the objects in table Tab using a match specification.
1414 This is a more general call than match/2 and match_object/2
1415 calls. In its simplest form, the match specification is as fol‐
1416 lows:
1417
1418 MatchSpec = [MatchFunction]
1419 MatchFunction = {MatchHead, [Guard], [Result]}
1420 MatchHead = "Pattern as in ets:match"
1421 Guard = {"Guardtest name", ...}
1422 Result = "Term construct"
1423
1424 This means that the match specification is always a list of one
1425 or more tuples (of arity 3). The first element of the tuple is
1426 to be a pattern as described in match/2. The second element of
1427 the tuple is to be a list of 0 or more guard tests (described
1428 below). The third element of the tuple is to be a list contain‐
1429 ing a description of the value to return. In almost all normal
1430 cases, the list contains exactly one term that fully describes
1431 the value to return for each object.
1432
1433 The return value is constructed using the "match variables"
1434 bound in MatchHead or using the special match variables '$_'
1435 (the whole matching object) and '$$' (all match variables in a
1436 list), so that the following match/2 expression:
1437
1438 ets:match(Tab,{'$1','$2','$3'})
1439
1440 is exactly equivalent to:
1441
1442 ets:select(Tab,[{{'$1','$2','$3'},[],['$$']}])
1443
1444 And that the following match_object/2 call:
1445
1446 ets:match_object(Tab,{'$1','$2','$1'})
1447
1448 is exactly equivalent to
1449
1450 ets:select(Tab,[{{'$1','$2','$1'},[],['$_']}])
1451
1452 Composite terms can be constructed in the Result part either by
1453 simply writing a list, so that the following code:
1454
1455 ets:select(Tab,[{{'$1','$2','$3'},[],['$$']}])
1456
1457 gives the same output as:
1458
1459 ets:select(Tab,[{{'$1','$2','$3'},[],[['$1','$2','$3']]}])
1460
1461 That is, all the bound variables in the match head as a list. If
1462 tuples are to be constructed, one has to write a tuple of arity
1463 1 where the single element in the tuple is the tuple one wants
1464 to construct (as an ordinary tuple can be mistaken for a Guard).
1465
1466 Therefore the following call:
1467
1468 ets:select(Tab,[{{'$1','$2','$1'},[],['$_']}])
1469
1470 gives the same output as:
1471
1472 ets:select(Tab,[{{'$1','$2','$1'},[],[{{'$1','$2','$3'}}]}])
1473
1474 This syntax is equivalent to the syntax used in the trace pat‐
1475 terns (see the dbg(3)) module in Runtime_Tools.
1476
1477 The Guards are constructed as tuples, where the first element is
1478 the test name and the remaining elements are the test parame‐
1479 ters. To check for a specific type (say a list) of the element
1480 bound to the match variable '$1', one would write the test as
1481 {is_list, '$1'}. If the test fails, the object in the table does
1482 not match and the next MatchFunction (if any) is tried. Most
1483 guard tests present in Erlang can be used, but only the new ver‐
1484 sions prefixed is_ are allowed (is_float, is_atom, and so on).
1485
1486 The Guard section can also contain logic and arithmetic opera‐
1487 tions, which are written with the same syntax as the guard tests
1488 (prefix notation), so that the following guard test written in
1489 Erlang:
1490
1491 is_integer(X), is_integer(Y), X + Y < 4711
1492
1493 is expressed as follows (X replaced with '$1' and Y with '$2'):
1494
1495 [{is_integer, '$1'}, {is_integer, '$2'}, {'<', {'+', '$1', '$2'}, 4711}]
1496
1497 For tables of type ordered_set, objects are visited in the same
1498 order as in a first/next traversal. This means that the match
1499 specification is executed against objects with keys in the
1500 first/next order and the corresponding result list is in the or‐
1501 der of that execution.
1502
1503 select(Tab, MatchSpec, Limit) ->
1504 {[Match], Continuation} | '$end_of_table'
1505
1506 Types:
1507
1508 Tab = tab()
1509 MatchSpec = match_spec()
1510 Limit = integer() >= 1
1511 Match = term()
1512 Continuation = continuation()
1513
1514 Works like select/2, but only returns a limited (Limit) number
1515 of matching objects. Term Continuation can then be used in sub‐
1516 sequent calls to select/1 to get the next chunk of matching ob‐
1517 jects. This is a space-efficient way to work on objects in a ta‐
1518 ble, which is still faster than traversing the table object by
1519 object using first/1 and next/2.
1520
1521 If the table is empty, '$end_of_table' is returned.
1522
1523 Use safe_fixtable/2 to guarantee safe traversal for subsequent
1524 calls to select/1.
1525
1526 select_count(Tab, MatchSpec) -> NumMatched
1527
1528 Types:
1529
1530 Tab = tab()
1531 MatchSpec = match_spec()
1532 NumMatched = integer() >= 0
1533
1534 Matches the objects in table Tab using a match specification. If
1535 the match specification returns true for an object, that object
1536 considered a match and is counted. For any other result from the
1537 match specification the object is not considered a match and is
1538 therefore not counted.
1539
1540 This function can be described as a select_delete/2 function
1541 that does not delete any elements, but only counts them.
1542
1543 The function returns the number of objects matched.
1544
1545 select_delete(Tab, MatchSpec) -> NumDeleted
1546
1547 Types:
1548
1549 Tab = tab()
1550 MatchSpec = match_spec()
1551 NumDeleted = integer() >= 0
1552
1553 Matches the objects in table Tab using a match specification. If
1554 the match specification returns true for an object, that object
1555 is removed from the table. For any other result from the match
1556 specification the object is retained. This is a more general
1557 call than the match_delete/2 call.
1558
1559 The function returns the number of objects deleted from the ta‐
1560 ble.
1561
1562 Note:
1563 The match specification has to return the atom true if the ob‐
1564 ject is to be deleted. No other return value gets the object
1565 deleted. So one cannot use the same match specification for
1566 looking up elements as for deleting them.
1567
1568
1569 select_replace(Tab, MatchSpec) -> NumReplaced
1570
1571 Types:
1572
1573 Tab = tab()
1574 MatchSpec = match_spec()
1575 NumReplaced = integer() >= 0
1576
1577 Matches the objects in the table Tab using a match specifica‐
1578 tion. For each matched object, the existing object is replaced
1579 with the match specification result.
1580
1581 The match-and-replace operation for each individual object is
1582 guaranteed to be atomic and isolated. The select_replace table
1583 traversal as a whole, like all other select functions, does not
1584 give such guarantees.
1585
1586 The match specifiction must be guaranteed to retain the key of
1587 any matched object. If not, select_replace will fail with badarg
1588 without updating any objects.
1589
1590 For the moment, due to performance and semantic constraints, ta‐
1591 bles of type bag are not yet supported.
1592
1593 The function returns the total number of replaced objects.
1594
1595 Example
1596
1597 For all 2-tuples with a list in second position, add atom
1598 'marker' first in the list:
1599
1600 1> T = ets:new(x,[]), ets:insert(T, {key, [1, 2, 3]}).
1601 true
1602 2> MS = ets:fun2ms(fun({K, L}) when is_list(L) -> {K, [marker | L]} end).
1603 [{{'$1','$2'},[{is_list,'$2'}],[{{'$1',[marker|'$2']}}]}]
1604 3> ets:select_replace(T, MS).
1605 1
1606 4> ets:tab2list(T).
1607 [{key,[marker,1,2,3]}]
1608
1609
1610 A generic single object compare-and-swap operation:
1611
1612 [Old] = ets:lookup(T, Key),
1613 New = update_object(Old),
1614 Success = (1 =:= ets:select_replace(T, [{Old, [], [{const, New}]}])),
1615
1616
1617 select_reverse(Continuation) ->
1618 {[Match], Continuation} | '$end_of_table'
1619
1620 Types:
1621
1622 Continuation = continuation()
1623 Match = term()
1624
1625 Continues a match started with select_reverse/3. For tables of
1626 type ordered_set, the traversal of the table continues to ob‐
1627 jects with keys earlier in the Erlang term order. The returned
1628 list also contains objects with keys in reverse order. For all
1629 other table types, the behavior is exactly that of select/1.
1630
1631 Example:
1632
1633 1> T = ets:new(x,[ordered_set]).
1634 2> [ ets:insert(T,{N}) || N <- lists:seq(1,10) ].
1635 3> {R0,C0} = ets:select_reverse(T,[{'_',[],['$_']}],4).
1636 4> R0.
1637 [{10},{9},{8},{7}]
1638 5> {R1,C1} = ets:select_reverse(C0).
1639 6> R1.
1640 [{6},{5},{4},{3}]
1641 7> {R2,C2} = ets:select_reverse(C1).
1642 8> R2.
1643 [{2},{1}]
1644 9> '$end_of_table' = ets:select_reverse(C2).
1645
1646 select_reverse(Tab, MatchSpec) -> [Match]
1647
1648 Types:
1649
1650 Tab = tab()
1651 MatchSpec = match_spec()
1652 Match = term()
1653
1654 Works like select/2, but returns the list in reverse order for
1655 table type ordered_set. For all other table types, the return
1656 value is identical to that of select/2.
1657
1658 select_reverse(Tab, MatchSpec, Limit) ->
1659 {[Match], Continuation} | '$end_of_table'
1660
1661 Types:
1662
1663 Tab = tab()
1664 MatchSpec = match_spec()
1665 Limit = integer() >= 1
1666 Match = term()
1667 Continuation = continuation()
1668
1669 Works like select/3, but for table type ordered_set traversing
1670 is done starting at the last object in Erlang term order and
1671 moves to the first. For all other table types, the return value
1672 is identical to that of select/3.
1673
1674 Notice that this is not equivalent to reversing the result list
1675 of a select/3 call, as the result list is not only reversed, but
1676 also contains the last Limit matching objects in the table, not
1677 the first.
1678
1679 setopts(Tab, Opts) -> true
1680
1681 Types:
1682
1683 Tab = tab()
1684 Opts = Opt | [Opt]
1685 Opt = {heir, pid(), HeirData} | {heir, none}
1686 HeirData = term()
1687
1688 Sets table options. The only allowed option to be set after the
1689 table has been created is heir. The calling process must be the
1690 table owner.
1691
1692 slot(Tab, I) -> [Object] | '$end_of_table'
1693
1694 Types:
1695
1696 Tab = tab()
1697 I = integer() >= 0
1698 Object = tuple()
1699
1700 This function is mostly for debugging purposes, Normally
1701 first/next or last/prev are to be used instead.
1702
1703 Returns all objects in slot I of table Tab. A table can be tra‐
1704 versed by repeatedly calling the function, starting with the
1705 first slot I=0 and ending when '$end_of_table' is returned. If
1706 argument I is out of range, the function fails with reason
1707 badarg.
1708
1709 Unless a table of type set, bag, or duplicate_bag is protected
1710 using safe_fixtable/2, a traversal can fail if concurrent up‐
1711 dates are made to the table. For table type ordered_set, the
1712 function returns a list containing object I in Erlang term or‐
1713 der.
1714
1715 tab2file(Tab, Filename) -> ok | {error, Reason}
1716
1717 Types:
1718
1719 Tab = tab()
1720 Filename = file:name()
1721 Reason = term()
1722
1723 Dumps table Tab to file Filename.
1724
1725 Equivalent to tab2file(Tab, Filename,[])
1726
1727 tab2file(Tab, Filename, Options) -> ok | {error, Reason}
1728
1729 Types:
1730
1731 Tab = tab()
1732 Filename = file:name()
1733 Options = [Option]
1734 Option = {extended_info, [ExtInfo]} | {sync, boolean()}
1735 ExtInfo = md5sum | object_count
1736 Reason = term()
1737
1738 Dumps table Tab to file Filename.
1739
1740 When dumping the table, some information about the table is
1741 dumped to a header at the beginning of the dump. This informa‐
1742 tion contains data about the table type, name, protection, size,
1743 version, and if it is a named table. It also contains notes
1744 about what extended information is added to the file, which can
1745 be a count of the objects in the file or a MD5 sum of the header
1746 and records in the file.
1747
1748 The size field in the header might not correspond to the number
1749 of records in the file if the table is public and records are
1750 added or removed from the table during dumping. Public tables
1751 updated during dump, and that one wants to verify when reading,
1752 needs at least one field of extended information for the read
1753 verification process to be reliable later.
1754
1755 Option extended_info specifies what extra information is written
1756 to the table dump:
1757
1758 object_count:
1759 The number of objects written to the file is noted in the
1760 file footer, so file truncation can be verified even if the
1761 file was updated during dump.
1762
1763 md5sum:
1764 The header and objects in the file are checksummed using the
1765 built-in MD5 functions. The MD5 sum of all objects is writ‐
1766 ten in the file footer, so that verification while reading
1767 detects the slightest bitflip in the file data. Using this
1768 costs a fair amount of CPU time.
1769
1770 Whenever option extended_info is used, it results in a file not
1771 readable by versions of ETS before that in STDLIB 1.15.1
1772
1773 If option sync is set to true, it ensures that the content of
1774 the file is written to the disk before tab2file returns. De‐
1775 faults to {sync, false}.
1776
1777 tab2list(Tab) -> [Object]
1778
1779 Types:
1780
1781 Tab = tab()
1782 Object = tuple()
1783
1784 Returns a list of all objects in table Tab.
1785
1786 tabfile_info(Filename) -> {ok, TableInfo} | {error, Reason}
1787
1788 Types:
1789
1790 Filename = file:name()
1791 TableInfo = [InfoItem]
1792 InfoItem =
1793 {name, atom()} |
1794 {type, Type} |
1795 {protection, Protection} |
1796 {named_table, boolean()} |
1797 {keypos, integer() >= 0} |
1798 {size, integer() >= 0} |
1799 {extended_info, [ExtInfo]} |
1800 {version,
1801 {Major :: integer() >= 0, Minor :: integer() >= 0}}
1802 ExtInfo = md5sum | object_count
1803 Type = bag | duplicate_bag | ordered_set | set
1804 Protection = private | protected | public
1805 Reason = term()
1806
1807 Returns information about the table dumped to file by tab2file/2
1808 or tab2file/3.
1809
1810 The following items are returned:
1811
1812 name:
1813 The name of the dumped table. If the table was a named ta‐
1814 ble, a table with the same name cannot exist when the table
1815 is loaded from file with file2tab/2. If the table is not
1816 saved as a named table, this field has no significance when
1817 loading the table from file.
1818
1819 type:
1820 The ETS type of the dumped table (that is, set, bag, dupli‐
1821 cate_bag, or ordered_set). This type is used when loading
1822 the table again.
1823
1824 protection:
1825 The protection of the dumped table (that is, private, pro‐
1826 tected, or public). A table loaded from the file gets the
1827 same protection.
1828
1829 named_table:
1830 true if the table was a named table when dumped to file,
1831 otherwise false. Notice that when a named table is loaded
1832 from a file, there cannot exist a table in the system with
1833 the same name.
1834
1835 keypos:
1836 The keypos of the table dumped to file, which is used when
1837 loading the table again.
1838
1839 size:
1840 The number of objects in the table when the table dump to
1841 file started. For a public table, this number does not need
1842 to correspond to the number of objects saved to the file, as
1843 objects can have been added or deleted by another process
1844 during table dump.
1845
1846 extended_info:
1847 The extended information written in the file footer to allow
1848 stronger verification during table loading from file, as
1849 specified to tab2file/3. Notice that this function only
1850 tells which information is present, not the values in the
1851 file footer. The value is a list containing one or more of
1852 the atoms object_count and md5sum.
1853
1854 version:
1855 A tuple {Major,Minor} containing the major and minor version
1856 of the file format for ETS table dumps. This version field
1857 was added beginning with STDLIB 1.5.1. Files dumped with
1858 older versions return {0,0} in this field.
1859
1860 An error is returned if the file is inaccessible, badly damaged,
1861 or not produced with tab2file/2 or tab2file/3.
1862
1863 table(Tab) -> QueryHandle
1864
1865 table(Tab, Options) -> QueryHandle
1866
1867 Types:
1868
1869 Tab = tab()
1870 QueryHandle = qlc:query_handle()
1871 Options = [Option] | Option
1872 Option = {n_objects, NObjects} | {traverse, TraverseMethod}
1873 NObjects = default | integer() >= 1
1874 TraverseMethod =
1875 first_next | last_prev | select |
1876 {select, MatchSpec :: match_spec()}
1877
1878 Returns a Query List Comprehension (QLC) query handle. The qlc
1879 module provides a query language aimed mainly at Mnesia, but ETS
1880 tables, Dets tables, and lists are also recognized by QLC as
1881 sources of data. Calling table/1,2 is the means to make the ETS
1882 table Tab usable to QLC.
1883
1884 When there are only simple restrictions on the key position, QLC
1885 uses lookup/2 to look up the keys. When that is not possible,
1886 the whole table is traversed. Option traverse determines how
1887 this is done:
1888
1889 first_next:
1890 The table is traversed one key at a time by calling first/1
1891 and next/2.
1892
1893 last_prev:
1894 The table is traversed one key at a time by calling last/1
1895 and prev/2.
1896
1897 select:
1898 The table is traversed by calling select/3 and select/1. Op‐
1899 tion n_objects determines the number of objects returned
1900 (the third argument of select/3); the default is to return
1901 100 objects at a time. The match specification (the second
1902 argument of select/3) is assembled by QLC: simple filters
1903 are translated into equivalent match specifications while
1904 more complicated filters must be applied to all objects re‐
1905 turned by select/3 given a match specification that matches
1906 all objects.
1907
1908 {select, MatchSpec}:
1909 As for select, the table is traversed by calling select/3
1910 and select/1. The difference is that the match specification
1911 is explicitly specified. This is how to state match specifi‐
1912 cations that cannot easily be expressed within the syntax
1913 provided by QLC.
1914
1915 Examples:
1916
1917 An explicit match specification is here used to traverse the ta‐
1918 ble:
1919
1920 9> true = ets:insert(Tab = ets:new(t, []), [{1,a},{2,b},{3,c},{4,d}]),
1921 MS = ets:fun2ms(fun({X,Y}) when (X > 1) or (X < 5) -> {Y} end),
1922 QH1 = ets:table(Tab, [{traverse, {select, MS}}]).
1923
1924 An example with an implicit match specification:
1925
1926 10> QH2 = qlc:q([{Y} || {X,Y} <- ets:table(Tab), (X > 1) or (X < 5)]).
1927
1928 The latter example is equivalent to the former, which can be
1929 verified using function qlc:info/1:
1930
1931 11> qlc:info(QH1) =:= qlc:info(QH2).
1932 true
1933
1934 qlc:info/1 returns information about a query handle, and in this
1935 case identical information is returned for the two query han‐
1936 dles.
1937
1938 take(Tab, Key) -> [Object]
1939
1940 Types:
1941
1942 Tab = tab()
1943 Key = term()
1944 Object = tuple()
1945
1946 Returns and removes a list of all objects with key Key in table
1947 Tab.
1948
1949 The specified Key is used to identify the object by either com‐
1950 paring equal the key of an object in an ordered_set table, or
1951 matching in other types of tables (for details on the differ‐
1952 ence, see lookup/2 and new/2).
1953
1954 test_ms(Tuple, MatchSpec) -> {ok, Result} | {error, Errors}
1955
1956 Types:
1957
1958 Tuple = tuple()
1959 MatchSpec = match_spec()
1960 Result = term()
1961 Errors = [{warning | error, string()}]
1962
1963 This function is a utility to test a match specification used in
1964 calls to select/2. The function both tests MatchSpec for "syn‐
1965 tactic" correctness and runs the match specification against ob‐
1966 ject Tuple.
1967
1968 If the match specification is syntactically correct, the func‐
1969 tion either returns {ok,Result}, where Result is what would have
1970 been the result in a real select/2 call, or false if the match
1971 specification does not match object Tuple.
1972
1973 If the match specification contains errors, tuple {error, Er‐
1974 rors} is returned, where Errors is a list of natural language
1975 descriptions of what was wrong with the match specification.
1976
1977 This is a useful debugging and test tool, especially when writ‐
1978 ing complicated select/2 calls.
1979
1980 See also: erlang:match_spec_test/3.
1981
1982 to_dets(Tab, DetsTab) -> DetsTab
1983
1984 Types:
1985
1986 Tab = tab()
1987 DetsTab = dets:tab_name()
1988
1989 Fills an already created/opened Dets table with the objects in
1990 the already opened ETS table named Tab. The Dets table is emp‐
1991 tied before the objects are inserted.
1992
1993 update_counter(Tab, Key, UpdateOp) -> Result
1994
1995 update_counter(Tab, Key, UpdateOp, Default) -> Result
1996
1997 update_counter(Tab, Key, X3 :: [UpdateOp]) -> [Result]
1998
1999 update_counter(Tab, Key, X3 :: [UpdateOp], Default) -> [Result]
2000
2001 update_counter(Tab, Key, Incr) -> Result
2002
2003 update_counter(Tab, Key, Incr, Default) -> Result
2004
2005 Types:
2006
2007 Tab = tab()
2008 Key = term()
2009 UpdateOp = {Pos, Incr} | {Pos, Incr, Threshold, SetValue}
2010 Pos = Incr = Threshold = SetValue = Result = integer()
2011 Default = tuple()
2012
2013 This function provides an efficient way to update one or more
2014 counters, without the trouble of having to look up an object,
2015 update the object by incrementing an element, and insert the re‐
2016 sulting object into the table again. The operation is guaranteed
2017 to be atomic and isolated.
2018
2019 This function destructively update the object with key Key in
2020 table Tab by adding Incr to the element at position Pos. The new
2021 counter value is returned. If no position is specified, the ele‐
2022 ment directly following key (<keypos>+1) is updated.
2023
2024 If a Threshold is specified, the counter is reset to value Set‐
2025 Value if the following conditions occur:
2026
2027 * Incr is not negative (>= 0) and the result would be greater
2028 than (>) Threshold.
2029
2030 * Incr is negative (< 0) and the result would be less than (<)
2031 Threshold.
2032
2033 A list of UpdateOp can be supplied to do many update operations
2034 within the object. The operations are carried out in the order
2035 specified in the list. If the same counter position occurs more
2036 than once in the list, the corresponding counter is thus updated
2037 many times, each time based on the previous result. The return
2038 value is a list of the new counter values from each update oper‐
2039 ation in the same order as in the operation list. If an empty
2040 list is specified, nothing is updated and an empty list is re‐
2041 turned. If the function fails, no updates are done.
2042
2043 The specified Key is used to identify the object by either
2044 matching the key of an object in a set table, or compare equal
2045 to the key of an object in an ordered_set table (for details on
2046 the difference, see lookup/2 and new/2).
2047
2048 If a default object Default is specified, it is used as the ob‐
2049 ject to be updated if the key is missing from the table. The
2050 value in place of the key is ignored and replaced by the proper
2051 key value. The return value is as if the default object had not
2052 been used, that is, a single updated element or a list of them.
2053
2054 The function fails with reason badarg in the following situa‐
2055 tions:
2056
2057 * The table type is not set or ordered_set.
2058
2059 * No object with the correct key exists and no default object
2060 was supplied.
2061
2062 * The object has the wrong arity.
2063
2064 * The default object arity is smaller than <keypos>.
2065
2066 * Any field from the default object that is updated is not an
2067 integer.
2068
2069 * The element to update is not an integer.
2070
2071 * The element to update is also the key.
2072
2073 * Any of Pos, Incr, Threshold, or SetValue is not an integer.
2074
2075 update_element(Tab, Key, ElementSpec :: {Pos, Value}) -> boolean()
2076
2077 update_element(Tab, Key, ElementSpec :: [{Pos, Value}]) ->
2078 boolean()
2079
2080 Types:
2081
2082 Tab = tab()
2083 Key = term()
2084 Value = term()
2085 Pos = integer() >= 1
2086
2087 This function provides an efficient way to update one or more
2088 elements within an object, without the trouble of having to look
2089 up, update, and write back the entire object.
2090
2091 This function destructively updates the object with key Key in
2092 table Tab. The element at position Pos is given the value Value.
2093
2094 A list of {Pos,Value} can be supplied to update many elements
2095 within the same object. If the same position occurs more than
2096 once in the list, the last value in the list is written. If the
2097 list is empty or the function fails, no updates are done. The
2098 function is also atomic in the sense that other processes can
2099 never see any intermediate results.
2100
2101 Returns true if an object with key Key is found, otherwise
2102 false.
2103
2104 The specified Key is used to identify the object by either
2105 matching the key of an object in a set table, or compare equal
2106 to the key of an object in an ordered_set table (for details on
2107 the difference, see lookup/2 and new/2).
2108
2109 The function fails with reason badarg in the following situa‐
2110 tions:
2111
2112 * The table type is not set or ordered_set.
2113
2114 * Pos < 1.
2115
2116 * Pos > object arity.
2117
2118 * The element to update is also the key.
2119
2120 whereis(TableName) -> tid() | undefined
2121
2122 Types:
2123
2124 TableName = atom()
2125
2126 This function returns the tid() of the named table identified by
2127 TableName, or undefined if no such table exists. The tid() can
2128 be used in place of the table name in all operations, which is
2129 slightly faster since the name does not have to be resolved on
2130 each call.
2131
2132 If the table is deleted, the tid() will be invalid even if an‐
2133 other named table is created with the same name.
2134
2135
2136
2137Ericsson AB stdlib 3.16.1 ets(3)