Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Indices

Indices can be used to speed up query operations by pre-computing orderings on entity fields, and can optionally impose a uniqueness constraint. The #[key] attribute is a shortcut to define a single unique index on a table, but sometimes more indices are needed.

Unlike with the key index, in microrm other indicies are declared externally to the entity type; instead, they are defined in the schema. The relevant types are SearchIndex and UniqueIndex; these each take two generic type parameters: the first is the entity to declare a search index over, and the second is the list of fields that make up the search index.

Due to limitations of the Rust type system1, specifying the fields for the index must be done via the index_cols! proc macro, leading to definitions such as the following:

#[derive(Clone, Entity)]
struct IndexedExample {
    #[key]
    pub main_key: String,
    pub secondary_key: String,
    pub data: String,
    // ...
}

#[derive(Schema)]
struct Schema {
    // normal accessor
    example_entities: microrm::Table<IndexExample>,
    // secondary search key
    supplementary_index: microrm::SearchIndex<
        IndexedExample,
        // note use of index_cols! and the automatically-defined SecondaryKey constant
        index_cols![IndexedExample::SecondaryKey]
    >,
}

Actually making use of the defined index requires no special effort; any query against the entity using the exact same set of columns as is specified in the index will make use of the index internally.


  1. Specifically, the lack of inherent associated types.