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