Need help creating a mnesia table index

Why the first element of a record can’t be used as table index?

This is not working:

(hlu@192.168.0.40)16> rd(pilot, {id, name, weight, phone}).
pilot
(hlu@192.168.0.40)17> mnesia:create_table(pilot,
(hlu@192.168.0.40)17> [{attributes, record_info(fields, pilot)},
(hlu@192.168.0.40)17> {index, [#pilot.id]},
(hlu@192.168.0.40)17> {disc_copies, Nodes},
(hlu@192.168.0.40)17> {type, set}]).
{aborted,{bad_type,pilot,{index,[{2,ordered}]}}}

This is working:

(hlu@192.168.0.40)18> rf(pilot).                                
ok
(hlu@192.168.0.40)19> rd(pilot, {name, weight, phone, id}).     
pilot
(hlu@192.168.0.40)20> mnesia:create_table(pilot,
(hlu@192.168.0.40)20> [{attributes, record_info(fields, pilot)},
(hlu@192.168.0.40)20> {index, [#pilot.id]},
(hlu@192.168.0.40)20> {disc_copies, Nodes},
(hlu@192.168.0.40)20> {type, set}]).
{atomic,ok}
1 Like

Probably because the 1st field of the record is the primary key and already indexed.
IE no need to create an index for the 1st field in the record definition.

The index property is for secondary indexes.
From the docs:
index. This is a list of attribute names, or integers, which specify the tuple positions on which Mnesia is to build and maintain an extra index table.

and a little further down

For information about the complete set of table properties and their details, see mnesia:create_table/2.

This Reference Manual uses a table of persons to illustrate various examples. The following record definition is assumed:

-record(person, {name,
                 age = 0,
                 address = unknown,
                 salary = 0,
                 children = []}),
The first record attribute is the primary key, or key for short.
2 Likes

Thanks!

Now I’ve found the well hidden statement in the documentation.

The first record attribute is the primary key, or key for short.

1 Like

In your first example, the primary key is id, and you are trying to create an additional index on the id field. Mnesia returns an error because it is unnecessary and redundant.

In your second example, you rearranged the record fields so that id is no longer the primary key. Instead, it becomes an additional field that you can create an index on. That’s why the second example works.

1 Like