Sophie

Sophie

distrib > Fedora > 17 > i386 > by-pkgid > 675c8c8167236dfcf8d66da674f931e8 > files > 54

erlang-doc-R15B-03.3.fc17.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns:fn="http://www.w3.org/2005/02/xpath-functions">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../otp_doc.css" type="text/css">
<title>Erlang -- Tables and databases</title>
</head>
<body bgcolor="white" text="#000000" link="#0000ff" vlink="#ff00ff" alink="#ff0000"><div id="container">
<script id="js" type="text/javascript" language="JavaScript" src="../js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../js/erlresolvelinks.js"></script><script language="JavaScript" type="text/javascript">
            <!--
              function getWinHeight() {
                var myHeight = 0;
                if( typeof( window.innerHeight ) == 'number' ) {
                  //Non-IE
                  myHeight = window.innerHeight;
                } else if( document.documentElement && ( document.documentElement.clientWidth ||
                                                         document.documentElement.clientHeight ) ) {
                  //IE 6+ in 'standards compliant mode'
                  myHeight = document.documentElement.clientHeight;
                } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                  //IE 4 compatible
                  myHeight = document.body.clientHeight;
                }
                return myHeight;
              }

              function setscrollpos() {
                var objf=document.getElementById('loadscrollpos');
                 document.getElementById("leftnav").scrollTop = objf.offsetTop - getWinHeight()/2;
              }

              function addEvent(obj, evType, fn){
                if (obj.addEventListener){
                obj.addEventListener(evType, fn, true);
                return true;
              } else if (obj.attachEvent){
                var r = obj.attachEvent("on"+evType, fn);
                return r;
              } else {
                return false;
              }
             }

             addEvent(window, 'load', setscrollpos);

             //--></script><div id="leftnav"><div class="innertube">
<img alt="Erlang logo" src="../erlang-logo.png"><br><small><a href="users_guide.html">User's Guide</a><br><a href="../pdf/otp-system-documentation-5.9.3.1.pdf">PDF</a><br><a href="../index.html">Top</a></small><p><strong>Efficiency Guide</strong><br><strong>User's Guide</strong><br><small>Version 5.9.3.1</small></p>
<br><a href="javascript:openAllFlips()">Expand All</a><br><a href="javascript:closeAllFlips()">Contract All</a><p><small><strong>Chapters</strong></small></p>
<ul class="flipMenu" imagepath="../js/flipmenu">
<li id="no" title="Introduction" expanded="false">Introduction<ul>
<li><a href="introduction.html">
              Top of chapter
            </a></li>
<li title="Purpose"><a href="introduction.html#id62954">Purpose</a></li>
<li title="Prerequisites"><a href="introduction.html#id65420">Prerequisites</a></li>
</ul>
</li>
<li id="no" title="The Eight Myths of Erlang Performance" expanded="false">The Eight Myths of Erlang Performance<ul>
<li><a href="myths.html">
              Top of chapter
            </a></li>
<li title="Myth: Funs are slow"><a href="myths.html#id64448">Myth: Funs are slow</a></li>
<li title="Myth: List comprehensions are slow"><a href="myths.html#id61406">Myth: List comprehensions are slow</a></li>
<li title="Myth: Tail-recursive functions are MUCH faster
    than recursive functions"><a href="myths.html#id62291">Myth: Tail-recursive functions are MUCH faster
    than recursive functions</a></li>
<li title="Myth: '++' is always bad"><a href="myths.html#id60058">Myth: '++' is always bad</a></li>
<li title="Myth: Strings are slow"><a href="myths.html#id62534">Myth: Strings are slow</a></li>
<li title="Myth: Repairing a Dets file is very slow"><a href="myths.html#id61135">Myth: Repairing a Dets file is very slow</a></li>
<li title="Myth: BEAM is a stack-based byte-code virtual machine (and therefore slow)"><a href="myths.html#id64006">Myth: BEAM is a stack-based byte-code virtual machine (and therefore slow)</a></li>
<li title="Myth: Use '_' to speed up your program when a variable is not used"><a href="myths.html#id64026">Myth: Use '_' to speed up your program when a variable is not used</a></li>
</ul>
</li>
<li id="no" title="Common Caveats" expanded="false">Common Caveats<ul>
<li><a href="commoncaveats.html">
              Top of chapter
            </a></li>
<li title="The timer module"><a href="commoncaveats.html#id62547">The timer module</a></li>
<li title="list_to_atom/1"><a href="commoncaveats.html#id61885">list_to_atom/1</a></li>
<li title="length/1"><a href="commoncaveats.html#id60806">length/1</a></li>
<li title="setelement/3"><a href="commoncaveats.html#id58300">setelement/3</a></li>
<li title="size/1"><a href="commoncaveats.html#id65402">size/1</a></li>
<li title="split_binary/2"><a href="commoncaveats.html#id60836">split_binary/2</a></li>
<li title="The '--' operator"><a href="commoncaveats.html#id61766">The '--' operator</a></li>
</ul>
</li>
<li id="no" title="Constructing and matching binaries" expanded="false">Constructing and matching binaries<ul>
<li><a href="binaryhandling.html">
              Top of chapter
            </a></li>
<li title="How binaries are implemented"><a href="binaryhandling.html#id62932">How binaries are implemented</a></li>
<li title="Constructing binaries"><a href="binaryhandling.html#id66066">Constructing binaries</a></li>
<li title="Matching binaries"><a href="binaryhandling.html#id63610">Matching binaries</a></li>
</ul>
</li>
<li id="no" title="List handling" expanded="false">List handling<ul>
<li><a href="listHandling.html">
              Top of chapter
            </a></li>
<li title="Creating a list"><a href="listHandling.html#id66709">Creating a list</a></li>
<li title="List comprehensions"><a href="listHandling.html#id66805">List comprehensions</a></li>
<li title="Deep and flat lists"><a href="listHandling.html#id66875">Deep and flat lists</a></li>
<li title="Why you should not worry about recursive lists functions"><a href="listHandling.html#id67017">Why you should not worry about recursive lists functions</a></li>
</ul>
</li>
<li id="no" title="Functions" expanded="false">Functions<ul>
<li><a href="functions.html">
              Top of chapter
            </a></li>
<li title="Pattern matching"><a href="functions.html#id67142">Pattern matching</a></li>
<li title="Function Calls "><a href="functions.html#id67362">Function Calls </a></li>
<li title="Memory usage in recursion"><a href="functions.html#id67506">Memory usage in recursion</a></li>
</ul>
</li>
<li id="loadscrollpos" title="Tables and databases" expanded="true">Tables and databases<ul>
<li><a href="tablesDatabases.html">
              Top of chapter
            </a></li>
<li title="Ets, Dets and Mnesia"><a href="tablesDatabases.html#id67596">Ets, Dets and Mnesia</a></li>
<li title="Ets specific"><a href="tablesDatabases.html#id67983">Ets specific</a></li>
<li title="Mnesia specific"><a href="tablesDatabases.html#id68087">Mnesia specific</a></li>
</ul>
</li>
<li id="no" title="Processes" expanded="false">Processes<ul>
<li><a href="processes.html">
              Top of chapter
            </a></li>
<li title="Creation of an Erlang process"><a href="processes.html#id68191">Creation of an Erlang process</a></li>
<li title="Process messages"><a href="processes.html#id68339">Process messages</a></li>
<li title="The SMP emulator"><a href="processes.html#id68531">The SMP emulator</a></li>
</ul>
</li>
<li id="no" title="Drivers" expanded="false">Drivers<ul>
<li><a href="drivers.html">
              Top of chapter
            </a></li>
<li title="Drivers and concurrency"><a href="drivers.html#id68634">Drivers and concurrency</a></li>
<li title="Avoiding copying of binaries when calling a driver"><a href="drivers.html#id68675">Avoiding copying of binaries when calling a driver</a></li>
<li title="Returning small binaries from a driver"><a href="drivers.html#id68743">Returning small binaries from a driver</a></li>
<li title="Returning big binaries without copying from a driver"><a href="drivers.html#id68777">Returning big binaries without copying from a driver</a></li>
</ul>
</li>
<li id="no" title="Advanced" expanded="false">Advanced<ul>
<li><a href="advanced.html">
              Top of chapter
            </a></li>
<li title="Memory"><a href="advanced.html#id68919">Memory</a></li>
<li title="System limits"><a href="advanced.html#id69276">System limits</a></li>
</ul>
</li>
<li id="no" title="Profiling" expanded="false">Profiling<ul>
<li><a href="profiling.html">
              Top of chapter
            </a></li>
<li title="Do not guess about performance - profile"><a href="profiling.html#id69579">Do not guess about performance - profile</a></li>
<li title="Big systems"><a href="profiling.html#id69661">Big systems</a></li>
<li title="What to look for"><a href="profiling.html#id69681">What to look for</a></li>
<li title="Tools"><a href="profiling.html#id69738">Tools</a></li>
<li title="Benchmarking"><a href="profiling.html#id70245">Benchmarking</a></li>
</ul>
</li>
</ul>
</div></div>
<div id="content">
<div class="innertube">
<h1>7 Tables and databases</h1>
  

  <h3><a name="id67596">7.1 
        Ets, Dets and Mnesia</a></h3>
    
    <p>Every example using Ets has a corresponding example in
      Mnesia. In general all Ets examples also apply to Dets tables.</p>

    <h4>Select/Match operations</h4>
      
      <p>Select/Match operations on Ets and Mnesia tables can become
        very expensive operations. They usually need to scan the complete
        table. You should try to structure your
        data so that you minimize the need for select/match
        operations. However, if you really need a select/match operation,
	it will still be more efficient than using <span class="code">tab2list</span>.
	Examples of this and also of ways to avoid select/match will be provided in
        some of the following sections. The functions
        <span class="code">ets:select/2</span> and <span class="code">mnesia:select/3</span> should be preferred over
        <span class="code">ets:match/2</span>,<span class="code">ets:match_object/2</span>, and <span class="code">mnesia:match_object/3</span>.</p>
      <div class="note">
<div class="label">Note</div>
<div class="content"><p>
        <p>There are exceptions when the complete table is not
          scanned, for instance if part of the key is bound when searching an
	  <span class="code">ordered_set</span> table, or if it is a Mnesia
          table and there is a secondary index on the field that is
          selected/matched. If the key is fully bound there will, of course, 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.</p>
      </p></div>
</div>
      <p>When creating a record to be used in a select/match operation you
        want most of the fields to have the value '_'. The easiest and fastest way
	to do that is as follows:</p>
      <div class="example"><pre>
#person{age = 42, _ = '_'}. </pre></div>
    

    <h4>Deleting an element</h4>
      
      <p>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>
      <p><strong>DO</strong></p>
      <div class="example"><pre>
...
ets:delete(Tab, Key),
...</pre></div>
      <p><strong>DO NOT</strong></p>
      <div class="example"><pre>
...
case ets:lookup(Tab, Key) of
    [] -&gt;
        ok;
    [_|_] -&gt;
        ets:delete(Tab, Key)
end,
...</pre></div>
    

    <h4>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 <span class="code">print_person/1</span> that uses the internal functions
        <span class="code">print_name/1</span>, <span class="code">print_age/1</span>, <span class="code">print_occupation/1</span>.</p>
      <div class="note">
<div class="label">Note</div>
<div class="content"><p>
        <p>If the functions <span class="code">print_name/1</span> and so on, 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. </p>
      </p></div>
</div>
      <p><strong>DO</strong></p>
      <div class="example"><pre>
%%% Interface function
print_person(PersonId) -&gt;
    %% Look up the person in the named table person,
    case ets:lookup(person, PersonId) of
        [Person] -&gt;
            print_name(Person),
            print_age(Person),
            print_occupation(Person);
        [] -&gt;
            io:format("No person with ID = ~p~n", [PersonID])
    end.

%%% Internal functions
print_name(Person) -&gt; 
    io:format("No person ~p~n", [Person#person.name]).
                      
print_age(Person) -&gt; 
    io:format("No person ~p~n", [Person#person.age]).

print_occupation(Person) -&gt; 
    io:format("No person ~p~n", [Person#person.occupation]).</pre></div>
      <p><strong>DO NOT</strong></p>
      <div class="example"><pre>
%%% Interface function
print_person(PersonId) -&gt;
    %% Look up the person in the named table person,
    case ets:lookup(person, PersonId) of
        [Person] -&gt;
            print_name(PersonID),
            print_age(PersonID),
            print_occupation(PersonID);
        [] -&gt;
            io:format("No person with ID = ~p~n", [PersonID])
    end.

%%% Internal functionss
print_name(PersonID) -&gt; 
    [Person] = ets:lookup(person, PersonId),
    io:format("No person ~p~n", [Person#person.name]).

print_age(PersonID) -&gt; 
    [Person] = ets:lookup(person, PersonId),
    io:format("No person ~p~n", [Person#person.age]).

print_occupation(PersonID) -&gt; 
    [Person] = ets:lookup(person, PersonId),
    io:format("No person ~p~n", [Person#person.occupation]).</pre></div>
    

    <h4>Non-persistent data storage </h4>
      
      <p>For non-persistent database storage, prefer Ets tables over
        Mnesia local_content tables. Even the Mnesia <span class="code">dirty_write</span>
        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
        <span class="code">dirty_write</span>. Thus, Ets writes will always be faster than
        Mnesia writes.</p>
    

    <h4>tab2list</h4>
      
      <p>Assume we have an Ets-table, which uses <span class="code">idno</span> as key,
        and contains:</p>
      <div class="example"><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></div>
      <p>If we <strong>must</strong> return all data stored in the Ets-table we
        can use <span class="code">ets:tab2list/1</span>.  However, usually we are only
        interested in a subset of the information in which case
        <span class="code">ets:tab2list/1</span> is expensive. If we only want to extract
        one field from each record, e.g., the age of every person, we
        should use:</p>
      <p><strong>DO</strong></p>
      <div class="example"><pre>
...
ets:select(Tab,[{ #person{idno='_', 
                          name='_', 
                          age='$1', 
                          occupation = '_'},
                [],
                ['$1']}]),
...</pre></div>
      <p><strong>DO NOT</strong></p>
      <div class="example"><pre>
...
TabList = ets:tab2list(Tab),
lists:map(fun(X) -&gt; X#person.age end, TabList),
...</pre></div>
      <p>If we are only interested in the age of all persons named
        Bryan, we should:</p>
      <p><strong>DO</strong></p>
      <div class="example"><pre>
...
ets:select(Tab,[{ #person{idno='_', 
                          name="Bryan", 
                          age='$1', 
                          occupation = '_'},
                [],
                ['$1']}]),
...</pre></div>
      <p><strong>DO NOT</strong></p>
      <div class="example"><pre>
...
TabList = ets:tab2list(Tab),
lists:foldl(fun(X, Acc) -&gt; case X#person.name of
                                "Bryan" -&gt;
                                    [X#person.age|Acc];
                                 _ -&gt;
                                     Acc
                           end
             end, [], TabList),
...</pre></div>
      <p><strong>REALLY DO NOT</strong></p>
      <div class="example"><pre>
...
TabList = ets:tab2list(Tab),
BryanList = lists:filter(fun(X) -&gt; X#person.name == "Bryan" end,
                         TabList),
lists:map(fun(X) -&gt; X#person.age end, BryanList),
...</pre></div>
      <p>If we need all information stored in the Ets table about
        persons named Bryan we should:</p>
      <p><strong>DO</strong></p>
      <div class="example"><pre>
...
ets:select(Tab, [{#person{idno='_', 
                          name="Bryan", 
                          age='_', 
                          occupation = '_'}, [], ['$_']}]),
...</pre></div>
      <p><strong>DO NOT</strong></p>
      <div class="example"><pre>
...
TabList = ets:tab2list(Tab),
lists:filter(fun(X) -&gt; X#person.name == "Bryan" end, TabList),
...</pre></div>
    

    <h4>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
        <span class="code">ordered_set</span> could be used instead of the more usual
        <span class="code">set</span> table type. An <span class="code">ordered_set</span> is always
        traversed in Erlang term order with regard to the key field
        so that return values from functions such as <span class="code">select</span>,
        <span class="code">match_object</span>, and <span class="code">foldl</span> are ordered by the key
        values. Traversing an <span class="code">ordered_set</span> with the <span class="code">first</span> and
        <span class="code">next</span> operations also returns the keys ordered.</p>
      <div class="note">
<div class="label">Note</div>
<div class="content"><p>
        <p>An <span class="code">ordered_set</span> only guarantees that
          objects are processed in <strong>key</strong> order. Results from functions as 
          <span class="code">ets:select/2</span> appear in the <strong>key</strong> order even if
          the key is not included in the result.</p>
      </p></div>
</div>
    
  

  <h3><a name="id67983">7.2 
        Ets specific</a></h3>
    

    <h4>Utilizing the keys of the Ets table</h4>
      
      <p>An Ets table is a single key table (either a hash table or a
        tree ordered by the key) and should be used as one. In other
        words, use the key to look up things whenever possible. A
        lookup by a known key in a set Ets table is constant and for a
        ordered_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 <span class="code">idno</span> 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>
      <p>A simple solution would be to use the <span class="code">name</span> field as
        the key instead of the <span class="code">idno</span> field, but that would cause
        problems if the names were not unique. A more general solution
        would be to create a second table with <span class="code">name</span> as key and
        <span class="code">idno</span> as data, i.e. to index (invert) the table with regards
        to the <span class="code">name</span> 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>
      <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:</p>
      <div class="example"><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></div>
      <p>Given this index table a lookup of the <span class="code">age</span> fields for
        all persons named "Bryan" could be done like this:</p>
      <div class="example"><pre>
...
MatchingIDs = ets:lookup(IndexTable,"Bryan"),
lists:map(fun(#index_entry{idno = ID}) -&gt;
                 [#person{age = Age}] = ets:lookup(PersonTable, ID),
                 Age
          end,
          MatchingIDs),
...</pre></div>
      <p>Note that the code above never uses <span class="code">ets:match/2</span> but
        instead utilizes the <span class="code">ets:lookup/2</span> call. The
        <span class="code">lists:map/2</span> call is only used to traverse the <span class="code">idno</span>s
        matching the name "Bryan" in the table; therefore the number of lookups
        in the master table is minimized.</p>
      <p>Keeping an index table introduces some overhead when
        inserting records in the table, therefore the number of operations
        gained from the table has to be weighted against the number of
        operations inserting objects in the table. However, note that the gain when
        the key can be used to lookup elements is significant.</p>
    
  

  <h3><a name="id68087">7.3 
        Mnesia specific</a></h3>
    

    <h4>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:</p>
      <div class="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></div>
    

    <h4>Transactions </h4>
      
      <p>Transactions is a way to guarantee that the distributed
        Mnesia database remains consistent, even when many different
        processes update 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.</p>
      <div class="example"><pre>
...
% Using transaction

Fun = fun() -&gt;
          [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></div>
    
  
</div>
<div class="footer">
<hr>
<p>Copyright © 2001-2012 Ericsson AB. All Rights Reserved.</p>
</div>
</div>
</div></body>
</html>