Skip to main content

Indexing API

Create fast lookup indexes in a datastore. Combined with streaming queries, indexing can be a big improvement for your application performance.

Without an index, a query has to scan every document in the collection. With an index on the queried field, the database jumps straight to the matching documents. The difference grows with the size of the collection.

API quick overview

How indexes work​

An index is a sorted lookup table for one field, or for a fixed combination of fields (a compound index). Once an index exists, it is kept up to date automatically every time you insert, update, replace or remove a document. You don't need to rebuild it.

Queries that use an index

The database uses an index when the query filters on an indexed field with one of these operators:

QueryUses an index
{ status: 'active' }✅ equality
{ price: { $gt: 100 } }, and $gte, $lt, $lte✅ range
{ status: { $in: ['active', 'trial'] } }✅
{ $or: [{ status: 'active' }, { plan: 'pro' }] }✅ only if every branch can use an index, otherwise a full scan
{ status: { $ne: 'active' } }, $nin❌ full scan
{ status: { $exists: true } }❌ full scan
{ status: { $not: ... } }❌ full scan
{ name: { $regex: '^Jo' } }❌ full scan

One index per query

When a query filters on several indexed fields, the database picks one index to scan and checks the remaining conditions on each matching document. It prefers the index with the most distinct values, because that one narrows the results the most. To serve a common multi-field equality query with a single index, create a compound index.

Sorting

A query with no filter and a sort on an indexed field reads documents straight from the index, already in order. Without an index on the sort field, the database has to read and sort the whole collection first.

// Fast with an index on 'name'
const cursor = conn.getMany('users', {}, { sort: { name: 1 }, limit: 50 });

What gets indexed

  • Strings, numbers and booleans are indexed by value. Numbers are stored so that range queries and sorting follow numeric order (2 comes before 10).
  • Nested fields can be indexed with dot notation, for example 'address.city'.
  • Missing and null values are left out of the index. A query that uses the index never returns documents where the field is missing.
  • Objects and arrays can't be looked up by their contents through an index. Index a scalar field instead if you need fast lookups.
  • Field names that start with $ can't be indexed.

Compound indexes​

A compound index covers an ordered combination of fields, such as tenant + status. It serves queries that match on all of those fields in a single, selective scan, instead of scanning one single-field index and checking the other field on every hit.

To create one, put the fields in a nested array. Each inner array is one compound index; plain strings are still single-field indexes:

const conn = await Datastore.open();

// One compound index on (tenant, status)
await conn.createIndex('orders', [['tenant', 'status']]);

// A compound index on (tenant, status) plus a single-field index on createdAt
await conn.createIndex('orders', [['tenant', 'status'], 'createdAt']);
Nested array, not a flat one

['tenant', 'status'] creates two separate single-field indexes. [['tenant', 'status']] creates one compound index.

With the CLI, join the fields with +:

coho createindex --collection orders --index 'tenant+status'

The index name is the fields joined with +, for example tenant+status. Use that name to remove it:

await conn.removeIndex('orders', 'tenant+status');

When a compound index is used

A compound index is used only when the query has a plain equality match on every field in the index:

QueryUses compound index tenant+status
{ tenant: 'acme', status: 'open' }✅
{ tenant: 'acme', status: 'open', total: { $gt: 100 } }✅ (total is checked on each hit)
{ tenant: 'acme' }❌ not all fields are matched
{ tenant: 'acme', status: { $in: ['open', 'paid'] } }❌ status isn't a plain equality
{ tenant: 'acme', status: { $gt: 'a' } }❌ range on a field

A compound index is preferred over single-field indexes when both could serve the query. Keep single-field indexes too if you also query on one of the fields alone.

Rules and limits

  • A compound index needs at least two fields.
  • Field names in a compound index can't contain +.
  • A document is left out of a compound index if any of its fields is missing, null, an object or an array. It can still be found through other indexes or a full scan.
  • Compound indexes are sorted ascending only.

Datastore.open()​

Datastore.open() opens a connection to a datastore in the active project space.

import {Datastore} from 'codehooks-js'

async function myfunc() {
const conn = await Datastore.open();
// use conn to call API functions
...
}

Returns Promise / Datastore connection

createIndex(collection, indexes)​

Create index(es) on a collection in the current Datastore. Each string in indexes gets its own single-field index, and each nested array becomes one compound index.

Parameters

  • collection: collection string
  • indexes: A field name, or an array of field names and nested field arrays, to index. Use dot notation for nested fields ('address.city').

Returns Promise. It resolves when the index build has started, not when it's finished.

Code example

const conn = await Datastore.open();
await conn.createIndex('stocks', ['Name', 'Volume']);

// A single field works too
await conn.createIndex('customers', 'address.city');

Index building runs in the background

On a collection that already has data, the database builds the index by reading every document. This runs in the background, one index at a time, so createIndex returns before the index is ready. Until the build is done, queries on that field can return incomplete results. Wait for the build to finish before relying on queries against a newly indexed field.

The CLI waits for the build and shows progress, which makes it the easiest way to index a big collection:

coho createindex --collection stocks --index Name --index Volume
warning

Index creation can take a long time on big collections. It's better to create indexes before adding data.

Create indexes once, when your app is deployed

Calling createIndex on a field that is already indexed re-reads every document in the collection to rebuild that index. So don't call it in a route handler, worker or job that runs over and over.

The best place for it in your app code is the startup function you pass to app.init(). Codehooks runs this function once each time you deploy, before your app serves requests:

import { app, Datastore } from 'codehooks-js';

app.get('/orders/:tenant/open', async (req, res) => {
const conn = await Datastore.open();
// Served by the compound index on (tenant, status)
conn.getMany('orders', { tenant: req.params.tenant, status: 'open' }).json(res);
});

// Runs once on every deploy
export default app.init(async () => {
const conn = await Datastore.open();
await conn.createIndex('orders', [['tenant', 'status'], 'createdAt']);
await conn.createIndex('customers', 'email');
});

This keeps your indexes in your code next to the queries that need them, so a new space or a fresh project gets the same indexes on its first deploy.

note

The startup function runs on every deploy, so each deploy rebuilds these indexes in the background. That's fine for small and medium collections. For very large collections, create the index once with the CLI instead and leave it out of app.init().

An error thrown in the startup function is logged, but it doesn't stop the deploy. Check the logs (coho log) after your first deploy.

removeIndex(collection, indexes)​

Remove index(es) on a collection in the current Datastore. Your documents are not changed, only the index is removed. If an index on that field is still being built, the build is stopped.

Parameters

  • collection: collection string
  • indexes: A field name, or an array of field names, to remove from the index. For a compound index, use its name, such as 'tenant+status'.

Returns Promise

Code example

const conn = await Datastore.open();
await conn.removeIndex('stocks', ['Name', 'Volume']);
tip

You can also use the CLI to manage indexes, with coho createindex and coho dropindex.

Choosing what to index​

  • Index the fields you filter on most often with equality or range queries, such as status, customerId or createdAt.
  • Index the fields you sort large result sets by.
  • If you often match on the same set of fields together, like { tenant, status }, create a compound index on them.
  • Skip fields you never filter or sort on. Every index adds a small cost to every write.
  • Skip fields you only query with $ne, $not or $regex, because those queries can't use an index.