1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This document was generated using DocBuilder 3.3.3 -->
<HTML>
<HEAD>
<TITLE>Tables and databases</TITLE>
<SCRIPT type="text/javascript" src="../../doc/erlresolvelinks.js">
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#FF00FF"
ALINK="#FF0000">
<CENTER>
<A HREF="http://www.erlang.se"><IMG BORDER=0 ALT="[Ericsson AB]" SRC="min_head.gif"></A>
</CENTER>
<A NAME="4"><!-- Empty --></A>
<H2>4 Tables and databases</H2>
<A NAME="4.1"><!-- Empty --></A>
<H3>4.1 Ets, Dets and Mnesia</H3>
<P> All examples using Ets has an corresponding example in
Mnesia. In general all Ets examples also applies to Dets tabels.<A NAME="4.1.1"><!-- Empty --></A>
<H4>4.1.1 Select/Match operations</H4>
<P>Select/Match operations on Ets and Mnesia tables can become
very expensive operations. They will have to scan the whole
table that may be very large. You should try to structure your
data so that you minimize the need for select/match
operations. However if you need a select/match operation this
will be more efficient than traversing the whole table using
other means such as <CODE>tab2list</CODE> and <CODE>mnemosyne</CODE>. Examples of this
and also of ways to avoid select/match will be provided in
some of the following sections. From R8 the functions
<CODE>ets:select/2</CODE> and <CODE>mnesia:select/3</CODE> should be preferred over
<CODE>ets:match/2</CODE>,<CODE>ets:match_object/2</CODE> and <CODE>mnesia:match_object/3</CODE>.
<P>
<TABLE CELLPADDING=4>
<TR>
<TD VALIGN=TOP><IMG ALT="Note!" SRC="note.gif"></TD>
<TD>
<P> There are exceptions when the whole table is not
scanned. This is when the key part is bound, the key part is
partially bound in an <CODE>orded_set</CODE> table, or if it is a mnesia
table and there is a secondary index on the field that is
selected/matched. Of course if the key is fully bound there will be
no point in doing a select/match, unless you have a bag table and
you are only interested in a sub-set of the elements with
the specific key.
</TD>
</TR>
</TABLE>
<P> When creating a record to be used in a select/match operation you
want most of the fields to have the value '_'. To avoid having to
explicitly set all of these fields people have created
functions that takes advantage of the fact that records are
implemented as tuples. This is not such a good idea, that is why you
from R8 can do the following
<PRE>
#person{age = 42, _ = '_'}.
</PRE>
<P> This will set the age attribute to 42 and all other attributes to '_'.
This is more efficient then creating a tuple with '_' values, that then is used as
a record. It is also much better code as it does not
violate the record abstraction.
<A NAME="4.1.2"><!-- Empty --></A>
<H4>4.1.2 Deleting an element</H4>
<P>As in the case of lists, the delete operation is considered
successful if the element was not present in the table. Hence
all attempts to check that the element is present in the
Ets/Mnesia table before deletion are unnecessary. Here follows
an example for Ets tables.
<P><STRONG>DO</STRONG>
<PRE>
...
ets:delete(Tab, Key),
...
</PRE>
<P><STRONG>DO NOT</STRONG>
<PRE>
...
case ets:lookup(Tab, Key) of
[] ->
ok;
[_|_] ->
ets:delete(Tab, Key)
end,
...
</PRE>
<A NAME="4.1.3"><!-- Empty --></A>
<H4>4.1.3 Data fetching</H4>
<P>Do not fetch data that you already have! Consider that you
have a module that handles the abstract data type Person. You
export the interface function <CODE>print_person/1</CODE> that uses the internal functions
<CODE>print_name/1</CODE>, <CODE>print_age/1</CODE>, <CODE>print_occupation/1</CODE>.
<P>
<TABLE CELLPADDING=4>
<TR>
<TD VALIGN=TOP><IMG ALT="Note!" SRC="note.gif"></TD>
<TD>
<P>If the functions <CODE>print_name/1</CODE> etc. had been interface
functions the matter comes in to a whole new light. As you
do not want the user of the interface to know about the
internal data representation. </TD>
</TR>
</TABLE>
<P><STRONG>DO</STRONG>
<PRE>
%%% Interface function
print_person(PersonId) ->
%% Look up the person in the named table person,
case ets:lookup(person, PersonId) of
[Person] ->
print_name(Person),
print_age(Person),
print_occupation(Person);
[] ->
io:format("No person with ID = ~p~n", [PersonID])
end.
%%% Interanal functions
print_name(Person) ->
io:format("No person ~p~n", [Person#person.name]).
print_age(Person) ->
io:format("No person ~p~n", [Person#person.age]).
print_occupation(Person) ->
io:format("No person ~p~n", [Person#person.occupation]).
</PRE>
<P><STRONG>DO NOT</STRONG>
<PRE>
%%% Interface function
print_person(PersonId) ->
%% Look up the person in the named table person,
case ets:lookup(person, PersonId) of
[Person] ->
print_name(PersonID),
print_age(PersonID),
print_occupation(PersonID);
[] ->
io:format("No person with ID = ~p~n", [PersonID])
end.
%%% Interanal functions
print_name(PersonID) ->
[Person] = ets:lookup(person, PersonId),
io:format("No person ~p~n", [Person#person.name]).
print_age(PersonID) ->
[Person] = ets:lookup(person, PersonId),
io:format("No person ~p~n", [Person#person.age]).
print_occupation(PersonID) ->
[Person] = ets:lookup(person, PersonId),
io:format("No person ~p~n", [Person#person.occupation]).
</PRE>
<A NAME="4.1.4"><!-- Empty --></A>
<H4>4.1.4 Non persistent data storage </H4>
<P>For non persistent database storage, prefer Ets tables before
Mnesia local_content tables. Even the cheapest Mnesia
operations, <CODE>dirty_write</CODE> operations, carry a fixed overhead
compared to Ets writes. Mnesia must check if the table is
replicated or has indices, this involves at least one Ets
lookup for each <CODE>dirty_write</CODE>. Thus, Ets writes will always be
faster than Mnesia writes.<A NAME="4.1.5"><!-- Empty --></A>
<H4>4.1.5 tab2list</H4>
<P>Assume we have an Ets-table, which uses <CODE>idno</CODE> as key,
and contains:
<PRE>
[#person{idno = 1, name = "Adam", age = 31, occupation = "mailman"},
#person{idno = 2, name = "Bryan", age = 31, occupation = "cashier"},
#person{idno = 3, name = "Bryan", age = 35, occupation = "banker"},
#person{idno = 4, name = "Carl", age = 25, occupation = "mailman"}]
</PRE>
<P>If we <STRONG>must</STRONG> return all data stored in the Ets-table we
can use <CODE>ets:tab2list/1</CODE>. However, usually we are only
interested in a subset of the information in which case
<CODE>ets:tab2list/1</CODE> is expensive. If we only want to extract
one field from each record, e.g., the age of every person, we
should use:
<P><STRONG>DO</STRONG>
<PRE>
...
ets:select(Tab,[{ #person{idno='_',
name='_',
age='$1',
occupation = '_'},
[],
['$1']}]),
...
</PRE>
<P><STRONG>DO NOT</STRONG>
<PRE>
...
TabList = ets:tab2list(Tab),
lists:map(fun(X) -> X#person.age end, TabList),
...
</PRE>
<P>If we are only interested in the age of all persons named
Bryan, we should:
<P><STRONG>DO</STRONG>
<PRE>
...
ets:select(Tab,[{ #person{idno='_',
name="Bryan",
age='$1',
occupation = '_'},
[],
['$1']}]),
...
</PRE>
<P><STRONG>DO NOT</STRONG>
<PRE>
...
TabList = ets:tab2list(Tab),
lists:foldl(fun(X, Acc) -> case X#person.name of
"Bryan" ->
[X#person.age|Acc];
_ ->
Acc
end
end, [], TabList),
...
</PRE>
<P><STRONG>REALLY DO NOT</STRONG>
<PRE>
...
TabList = ets:tab2list(Tab),
BryanList = lists:filter(fun(X) -> X#person.name == "Bryan" end,
TabList),
lists:map(fun(X) -> X#person.age end, BryanList),
...
</PRE>
<P>If we need all information stored in the ets table about
persons named Bryan we should:
<P><STRONG>DO</STRONG>
<PRE>
...
ets:select(Tab, [{#person{idno='_',
name="Bryan",
age='_',
occupation = '_'}, [], ['$_']}]),
...
</PRE>
<P><STRONG>DO NOT</STRONG>
<PRE>
...
TabList = ets:tab2list(Tab),
lists:filter(fun(X) -> X#person.name == "Bryan" end, TabList),
...
</PRE>
<A NAME="4.1.6"><!-- Empty --></A>
<H4>4.1.6 Ordered_set tables</H4>
<P>If the data in the table should be accessed so that the order
of the keys in the table is significant, the table type
<CODE>ordered_set</CODE> could be used instead of the more usual
<CODE>set</CODE> table type. An <CODE>ordered_set</CODE> is always
traversed in Erlang term order with regards to the key field
so that return values from functions such as <CODE>select </CODE>,
<CODE>match_object</CODE> and <CODE>foldl</CODE> are ordered by the key
values. Traversing an <CODE>ordered_set</CODE> with the first and
next operations also returns the keys ordered.
<P>
<TABLE CELLPADDING=4>
<TR>
<TD VALIGN=TOP><IMG ALT="Note!" SRC="note.gif"></TD>
<TD>
<P>An <CODE>ordered_set</CODE> only guarantees that
objects are processed in <STRONG>key</STRONG> order. Results from functions as
<CODE>ets:select/2</CODE> appear in the <STRONG>key</STRONG> order even if
the key is not included in the result. </TD>
</TR>
</TABLE>
<A NAME="4.2"><!-- Empty --></A>
<H3>4.2 Ets specific</H3>
<A NAME="4.2.1"><!-- Empty --></A>
<H4>4.2.1 Utilizing the keys of the Ets table</H4>
<P> An Ets table is a singel key table (either a hash table or a
tree orded by the key) and should be used as one. In other
words, always use the key to look up things when possible. A
lookup by a known key in a set Ets table is constant and for a
orded_set Ets table it is O(logN). A key lookup is always
preferable to a call where the whole table has to be
scanned. In the examples above, the field <CODE>idno</CODE> is the
key of the table and all lookups where only the name is known
will result in a complete scan of the (possibly large) table
for a matching result.
<P>A simple solution would be to use the <CODE>name</CODE> field as
the key instead of the <CODE>idno</CODE> field, but that would cause
problems if the names were not unique. A more general solution
would be create a second table with name as key and idno as
data, i.e. to index (invert) the table with regards to the
<CODE>name</CODE> field. The second table would of course have to be
kept consistent with the master table. Mnesia could do this
for you, but a home brew index table could be very efficient
compared to the overhead involved in using mnesia.
<P>An index table for the table in the previous examples would
have to be a bag (as keys would appear more than once) and could
have the following contents:
<PRE>
[#index_entry{name="Adam", idno=1},
#index_entry{name="Bryan", idno=2},
#index_entry{name="Bryan", idno=3},
#index_entry{name="Carl", idno=4}]
</PRE>
<P>Given this index table a lookup of the <CODE>age</CODE> fields for
all persons named "Bryan" could be done like this:
<PRE>
...
MatchingIDs = ets:lookup(IndexTable,"Bryan"),
lists:map(fun(#index_entry{idno = ID}) ->
[#person{age = Age}] = ets:lookup(PersonTable, ID),
Age
end,
MatchingIDs),
...
</PRE>
<P>Note that the code above never uses <CODE>ets:match/2</CODE> but
instead utilizes the <CODE>ets:lookup/2</CODE> call. The
<CODE>lists:map</CODE> call is only used to traverse the <CODE>idno</CODE>'s
matching the name "Bryan" in the table, why the number of lookups
in the master table is minimized.
<P>Keeping an index table of course introduces some overhead when
inserting records in the table, why the number of operations
gaining from the table has to be weighted against the number of
operations inserting objects in the table. However that the gain when
the key can be used to lookup elements is significant.<A NAME="4.3"><!-- Empty --></A>
<H3>4.3 Mnesia specific</H3>
<A NAME="4.3.1"><!-- Empty --></A>
<H4>4.3.1 Secondary index</H4>
<P>If you frequently do a lookup on a field that is not the
key of the table, you will lose performance using
"mnesia:select/match_object" as this function will traverse the
whole table. You may create a secondary index instead and
use "mnesia:index_read" to get faster access, however this
will require more memory. Example:
<PRE>
-record(person, {idno, name, age, occupation}).
...
{atomic, ok} =
mnesia:create_table(person, [{index,[#person.age]},
{attributes,
record_info(fields, person)}]),
{atomic, ok} = mnesia:add_table_index(person, age),
...
PersonsAge42 =
mnesia:dirty_index_read(person, 42, #person.age),
...
</PRE>
<A NAME="4.3.2"><!-- Empty --></A>
<H4>4.3.2 Transactions </H4>
<P>Transactions is a way to guarantee that the distributed
mnesia database remains consistent, even when many different
processes updates it in parallel. However if you have
real time requirements it is recommended to use dirty
operations instead of transactions. When using the dirty
operations you lose the consistency guarantee, this is usually
solved by only letting one process update the table. Other
processes have to send update requests to that process.
<PRE>
...
% Using transaction
Fun = fun() ->
[mnesia:read({Table, Key}),
mnesia:read({Table2, Key2})]
end,
{atomic, [Result1, Result2]} = mnesia:transaction(Fun),
...
% Same thing using dirty operations
...
Result1 = mnesia:dirty_read({Table, Key}),
Result2 = mnesia:dirty_read({Table2, Key2}),
...
</PRE>
<A NAME="4.3.3"><!-- Empty --></A>
<H4>4.3.3 Mnemosyne </H4>
<P>Mnesia supports complex queries through the query language
Mnemosyne. This makes it possible to perform queries of any
complexity on Mnesia tables. However for simple queries
Mnemosyne is usually much more expensive than sensible
handwritten functions doing the same thing.
<P>
<TABLE CELLPADDING=4>
<TR>
<TD VALIGN=TOP><IMG ALT="Warning!" SRC="warning.gif"></TD>
<TD>
<P>The use of
mnemosyne queries in embedded real time systems is strongly
discouraged. </TD>
</TR>
</TABLE>
<P>Assume we have an mnesia-table, which uses <CODE>idno</CODE> as
key, and contains:
<PRE>
[#person{idno=1, name="Adam", age=31, occupation="mailman"},
#person{idno=2, name="Bryan", age=31, occupation="cashier"},
#person{idno=3, name="Bryan", age=35, occupation="banker"},
#person{idno=4, name="Carl", age=25, occupation="mailman"}]
</PRE>
<P>If we need to find all persons named Bryan we should:
<P><STRONG>DO </STRONG>
<PRE>
...
Select = fun() ->
mnesia:select(person,
[{#person{name ="Bryan", _ = '_'}, [], ['$_']}],
read)
end,
{atomic, Result} = mnesia:transaction(Select),
...
</PRE>
<P><STRONG>DO NOT</STRONG>
<PRE>
...
Handle = query
[ Person || Person <- table(person),
Person.name = "Bryan"]
end,
{atomic, Result} = mnesia:transaction(fun() -> mnemosyne:eval(Handle) end),
...
</PRE>
<A NAME="4.4"><!-- Empty --></A>
<H3>4.4 Older versions of Erlang/OTP</H3>
<P>If you have a an older version than R8 of Erlang/OTP you would
have to use match and match_object instead of select. The select
call is introduced in R8 and is not present in earlier releases.
Then the code would look as follows.
<P> Selecting the age field:
<PRE>
...
lists:append(ets:match(Ets, #person{idno='_',
name='_',
age='$1',
occupation = '_'})),
...
</PRE>
<P>The <CODE>lists:append/1</CODE> call above transforms the list of
lists returned by <CODE>ets:match/2</CODE> into a flat list containing
the values of the field <CODE>age</CODE> in the table.
<P> Selecting people called Bryan:
<PRE>
...
ets:match_object(Ets, #person{idno='_',
name="Bryan",
age='_',
occupation = '_'}),
...
</PRE>
<PRE>
...
Match = fun() ->
% Create record instance with '_' as values of the fileds
Person = mnesia_table_info(person, wild_pattern),
mnesia:match_object(person,
Person#person{name ="Bryan"},
read)
end,
{atomic, Result} = mnesia:transaction(Match),
...
</PRE>
<CENTER>
<HR>
<SMALL>
Copyright © 1991-2006
<A HREF="http://www.erlang.se">Ericsson AB</A><BR>
</SMALL>
</CENTER>
</BODY>
</HTML>
|