Skip to main content

Indexes

Indexes enable efficient querying of table data. SpacetimeDB supports B-Tree indexes on single or multiple columns.

Single-Column Indexes

const user = table(
  { name: 'user', public: true },
  {
    id: t.u32().primaryKey(),
    name: t.string().index('btree'),
  }
);

// Query using the index
for (const user of ctx.db.user.name.filter('Alice')) {
  // users with name = 'Alice'
}

Multi-Column Indexes

const score = table(
  {
    name: 'score',
    public: true,
    indexes: [
      {
        name: 'byPlayerAndLevel',
        algorithm: 'btree',
        columns: ['player_id', 'level'],
      },
    ],
  },
  {
    player_id: t.u32(),
    level: t.u32(),
    points: t.i64(),
  }
);

// Query with prefix match
for (const score of ctx.db.score.byPlayerAndLevel.filter(123)) {
  // scores with player_id = 123
}

// Query with range
for (const score of ctx.db.score.byPlayerAndLevel.filter([123, [1, 10]])) {
  // player_id = 123, 1 <= level <= 10
}