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