Search code examples
erlangerlang-shell

mnesia - creating index on a field after the table is created


I created a table using

mafiapp_friends = [aaa, expertise, xxx, yyy]

Note expertise is at position 2 in record

mnesia:create_table(mafiapp_friends,
[{attributes, record_info(fields, mafiapp_friends)},
{disc_copies, Nodes}]).

I forgot to add an index statement in it

{index, [#mafiapp_friends.expertise]},

Now I need to create this index. However I do not want to delete the table and re-create the table as I have data in it.

I executed following statement:

mnesia:add_table_index(mafiapp_friends, expertise)

And then I did

mnesia:schema(mafiapp_friends).

In the output I see,

index -> [3]

{index,3} -> {mafiapp_friends,index,3}

Can you tell me what [3] means here?


Solution

  • So, 3 is position of indexed field in the table, i.e.

    #mafiapp_friends.expertise
    

    See an example:

    2> rd(mafiapp_friends, {aaa, expertise, xxx, yyy}).
    mafiapp_friends
    3> #mafiapp_friends.expertise.
    3
    4> record_info(fields, mafiapp_friends).
    [aaa,expertise,xxx,yyy]
    5> 
    

    Note that records in erlang are just tuples with the first element being record name, that's why indexing looks a bit strange on the first sight

    5> X = #mafiapp_friends{expertise = hello}.
    #mafiapp_friends{aaa = undefined,expertise = hello,
                     xxx = undefined,yyy = undefined}
    6> element(3, X).
    hello
    7>