Prev  Next  Up  Contents

Making Indexes



When a database is first created, the index file contains only a physical index. The physical index allows records to be accessed in the physical order in which they are stored in the database. Since the physical index supports only sequential access, we need to create additional indexes if we want to randomly access the database records.

The imkindex function is called to make the additional indexes. It requires three arguments, the database handle, the name of the new index, and the names of the record fields that will comprise the index. The field names must match those passed to the icreate_db function when the database was created. The fields that comprise an index are often called key fields.

The following example program indexes the BOOKS database by the author name and ISBN number. The author index is arbitrarily named "Author_Index". It is comprised of the two record fields, "Author_Last" and "Author_First". The last name field is listed before the first name field so that the records will be sorted first by last name, then by first name. The ISBN index is arbitrarily named "ISBN_Index,U". It is comprised of the single record field named "ISBN". The ",U" appended to "ISBN_Index" identifies this index as being unique. This means that no two records will be allowed to store the same value in the "ISBN" field.

#include 
#include "isam.h"

int main()                      /* index.c */
{
    Db_Obj *db;
    char   *db_name = "BOOKS";
    char   *author_fields[3] = { "Author_Last", "Author_First", NULL };
    char   *isbn_fields[2] = { "ISBN", NULL };

    /* open existing ISAM database */
    db = iopen_db(db_name);
    if (db == NULL) {
        printf("Unable to open database: %s\n", db_name);
        iprterr();
        return -1;
    }

    /* make author index (not unique) */
    if (imkindex(db, "Author_Index", author_fields) == I_ERROR) {
        printf("Unable to create Author_Index\n");
        iprterr();
        return -1;
    }
    printf("Author_Index created\n");

    /* make ISBN index (unique specified by the ",U") */
    if (imkindex(db, "ISBN_Index,U", isbn_fields) == I_ERROR) {
        printf("Unable to create ISBN_Index,U\n");
        iprterr();
        return -1;
    }
    printf("ISBN_Index,U created\n");

    /* close ISAM database */
    iclose_db(db);

    return 0;
}

Notice that the imkindex function returns I_ERROR if an error occurs while attempting to make the new index. A value of I_OK is returned if the index is successfully created.

When a new index is created, the appropriate fields from each existing record are automatically stored in the new index. Likewise, each time a new record is added to the database, the appropriate fields of the new record are automatically stored in each existing index.


Next Page
C/Database Toolchest Description
Product List