Skip to main content

Secondary Indexes

Tigris supports adding secondary indexes for collections. See indexing concepts for the full details.

Creating an Index

To add an index to a field in a collection, add index: true to the field. Below is an example of adding indexing to two fields for a User collection.

@TigrisCollection("user")
export class User {
@PrimaryKey(TigrisDataTypes.STRING, { order: 1, autoGenerate: false })
@Field({ index: true })
email: string;

@Field({ index: true })
name: string;
}

await tigrisClient.registerSchemas([User]);

If you are adding an index to an existing collection, you will need to log into the Tigris web console to initiate a build of the indexes for that collection.

Getting the state of an index

An index can be in INDEX ACTIVE state which means the index is being used for queries or in INDEX WRITE MODE where the index is still being built.

The method describe() will return back the status of each index in the collection.

const userColl = db.getCollection<User>(User);
const describe = await userColl.describe();
console.log(describe.indexDescriptions());

// returns:
[
{
name: "_tigris_created_at",
state: "INDEX ACTIVE",
fieldsList: [],
},
{
name: "_tigris_updated_at",
state: "INDEX ACTIVE",
fieldsList: [],
},
{ name: "email", state: "INDEX WRITE MODE", fieldsList: ["email"] },
{ name: "name", state: "INDEX ACTIVE", fieldsList: ["name"] },
];

Query

When running a findOne or findMany, Tigris will automatically look to see if a secondary index can be used to satisfy the query.

const cursor = await userColl.findMany({ filter: { name: "bob" } });

Sort

An index can be used to set the sort order for the documents returned. This can be done by using a single index in the sort.

const cursor = await userColl.findMany({
filter: { name: "bob" },
sort: { order: "$desc", field: "name" },
});

Explain

Tigris has an explain method to show how the Tigris query planner would run for a query. For example:

const explain = await userColl.explain({
filter: { name: "bob" },
sort: { order: "$desc", field: "name" },
});
console.log(explain);
// will return:
{
collection: 'user',
readType: 'secondary index',
filter: '{"name":"bob"}',
keyRangeList: [ "bob" ],
field: 'name'
}