---
title: defineIndex
description: Declare an index whose rows Luna keeps from many lunas' tables and events, and read it with ctx.index.
related:
  - /data/query-across-lunas
  - /sdk/define-event
  - /sdk/index-handle
---

`defineIndex` declares an index: rows that Luna fills from the table changes and events of many lunas, split into partitions, and that handlers read with `ctx.index`.

```ts luna/lunas/board-notes.ts
import { defineIndex } from "luna";
import { Card } from "./card.ts";

export const BoardNotes = defineIndex("BoardNotes", {
  partition: "board",
  search: { columns: ["text"] },
  from: [
    Card.changes.notes.map((n, from) => ({ id: n.id, text: n.text, done: n.done, board: from.board, card: from.card })),
  ],
});
```

## Reference

### defineIndex(name, options)

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The index's name, starting with a capital letter, like a luna type's. |
| `options.from` | `Source[]` | - | What fills it: table changes and events, each mapped to the index's fields. |
| `options.partition?` | `string` | - | The field each partition holds one value of, and when left out, rows go to 16 partitions by a hash of the emitting luna's key. |
| `options.columns?` | `Record<string, Ty>` | - | The index's columns, when its sources' field types cannot tell them, and otherwise each source's fields, nullable. |
| `options.indexes?` | `{ columns: string[] }[]` | - | Extra indexes on its rows, to make reads by those columns faster. |
| `options.search?` | `{ columns, tokenizer?, keepText? }` | - | A full-text index over some columns, for `search`. |
| `options.onBeforeConnect?` | `(ctx, request, partition) => unknown` | - | Lets apps read a partition as a live query, and decides who may. |
| `options.idleTimeout?` | `string \| number` | `"5s"` | How long a partition stays awake after its last batch or read. |

`search` takes these fields.

| Prop | Type | Default | Description |
| - | - | - | - |
| `columns` | `string[]` | - | The columns whose words are searched. |
| `tokenizer?` | `"unicode61" \| "porter" \| "trigram"` | - | How text is split into words. |
| `keepText?` | `boolean \| string[]` | `true` | With `false` the columns keep only their words and reads give `null` for them, and a list keeps the text of those columns only. |

`defineIndex` returns an `Index`, a luna type that holds one luna per partition. Export it from your app's entry module, like your luna types.

### ctx.index(index)

Returns an `IndexQuery` for the index. Every method takes these read options beside its own.

| Prop | Type | Default | Description |
| - | - | - | - |
| `partition?` | `string \| number` | - | The partition to read, and when left out, every partition is read and the results merged. |
| `after?` | `Bookmark` | - | Waits until the writes the bookmark names are in the index. |
| `timeout?` | `number` | `5000` | How many milliseconds to wait for `after` before the read fails with `Behind`. |

### IndexQuery

| Prop | Type | Default | Description |
| - | - | - | - |
| `find` | `(opts?) => Promise<Row[]>` | - | Rows that match `where`, in `orderBy` order, with `limit` and `offset`. |
| `page` | `(opts?) => Promise<{ rows: Row[]; cursor: unknown[] \| null }>` | - | One page of rows, `limit` rows long and 100 by default, and a `cursor` for the next page or `null` on the last. |
| `count` | `(opts?) => Promise<number>` | - | How many rows match `where`. |
| `groupBy` | `(by: string[], opts?) => Promise<GroupRow[]>` | - | Rows per group with `count` and the `sum`, `min` and `max` of the columns named, largest groups first. |
| `search` | `(text: string, opts?) => Promise<{ row: Row; score: number }[]>` | - | Full-text search, best matches first, for an index with `search`. |
| `nearest` | `(column: string, to: Float32Array \| number[], opts?) => Promise<{ row: Row; distance: number }[]>` | - | The `k` rows nearest a vector, 10 by default, by a vector column. |

`where`, `orderBy`, `limit` and `offset` work as in [ctx.db](/sdk/db). `search` also takes `match` (`"all"`, `"any"`, `"phrase"` or `"raw"`) and `prefix`. `nearest` also takes `k` and `where`.

### ctx.bookmark() and Bookmark

`ctx.bookmark()` returns where the handler's writes and events will stand in the indexes they fill once it commits. Pass it as `after` to read them.

| Prop | Type | Default | Description |
| - | - | - | - |
| `source` | `{ type: string; key: Record<string, unknown> }` | - | The luna that wrote. |
| `at` | `{ listen: string; to: string; key: Record<string, unknown>; seq: number }[]` | - | For each listen and listening luna, the last change noted for it. |

A bookmark is plain JSON. A handler can return it, and another luna can pass it on.

## Good to know

- An index is read only. Its rows change only through its sources.
- A read without `partition` lists every partition and reads each. Name the partition when you know it.
- A write before an `await` commits there. So a handler can write, then read the index with `after: ctx.bookmark()`.
- A read that waits longer than `timeout` for `after` throws a `LunaCallError` whose `code` is `Behind`.
- A deploy that changes an index's columns, `search` or `partition` fills it anew from its sources.
- Column names cannot start with `_`.
- Two sources that give one field different types need `columns`.
- Without `onBeforeConnect`, apps cannot read the index. Its return value is the connection's `auth`, and a `tags` list in it tags the connection.
- To close a partition's app connections that carry a tag, send `closeConnections({ tag, code, reason })` to that partition: `ctx.send(Index, { p: partition })`.
- A luna type that fills an index and also reads it refers to it through a function typed `AnyIndex`. TypeScript cannot infer the two from each other.

## Examples

### Search one partition

```ts luna/lunas/board-search.ts
import { defineLuna, t } from "luna";
import { BoardNotes } from "./board-notes.ts";

export const BoardSearch = defineLuna({
  name: "BoardSearch",
  key: { id: t.string() },
  handlers: (h) => ({
    search: h({ args: { q: t.string() } }, async (ctx, { q }) => {
      const hits = await ctx.index(BoardNotes).search(q, { partition: ctx.key.id, limit: 20 });
      return hits.map((hit) => ({ card: hit.row.card, text: hit.row.text, score: hit.score }));
    }),
  }),
});
```

### Read your own write

The card's handler returns `ctx.bookmark()`. The caller passes it as `after`.

```ts luna/lunas/card.ts
add: h({ args: { text: t.string() } }, (ctx, { text }) => {
  ctx.db.notes.insert({ text });
  return ctx.bookmark();
}),
```

```ts luna/lunas/board-search.ts
addNote: h({ args: { card: t.int(), text: t.string() } }, async (ctx, { card, text }) => {
  const after = await ctx.call(Card, { board: ctx.key.id, card }).add({ text });
  return ctx.index(BoardNotes).find({ partition: ctx.key.id, where: { card }, after });
}),
```

### Count and group

```ts luna/lunas/board-search.ts
stats: h({}, async (ctx) => ({
  open: await ctx.index(BoardNotes).count({ partition: ctx.key.id, where: { done: false } }),
  perCard: await ctx.index(BoardNotes).groupBy(["card"], { partition: ctx.key.id, limit: 10 }),
})),
```

### Read every row a page at a time

```ts luna/lunas/board-search.ts
all: h({}, async (ctx) => {
  const notes = ctx.index(BoardNotes);
  let page = await notes.page({ partition: ctx.key.id, orderBy: "id", limit: 100 });
  const rows = [...page.rows];
  while (page.cursor) {
    page = await notes.page({ partition: ctx.key.id, orderBy: "id", limit: 100, cursor: page.cursor });
    rows.push(...page.rows);
  }
  return rows;
}),
```

Keep the same `where`, `orderBy` and `partition` for every page.

### Fill an index from an event

With no `partition`, rows go to 16 partitions, and reads merge them.

```ts luna/lunas/finished.ts
import { defineIndex } from "luna";
import { CardDone } from "./events.ts";

export const Finished = defineIndex("Finished", {
  from: [CardDone.map((e, from) => ({ card: e.card, owner: e.owner, board: from.board }))],
});
```

### Let apps read a partition

```ts luna/lunas/board-feed.ts
import { defineIndex, t } from "luna";
import { bearer, jwks, verifyJwt } from "luna/auth";
import { Card } from "./card.ts";

const keys = jwks("https://auth.example.com/.well-known/jwks.json");

export const BoardFeed = defineIndex("BoardFeed", {
  partition: "board",
  columns: { board: t.string(), text: t.string(), done: t.bool() },
  indexes: [{ columns: ["done"] }],
  from: [Card.changes.notes.map((n, from) => ({ board: from.board, text: n.text, done: n.done }))],
  onBeforeConnect: async (ctx, request, partition) => {
    const claims = await verifyJwt(bearer(request.headers.authorization) ?? "", { jwks: keys });
    if (!(claims.boards as string[]).includes(partition)) ctx.fail("Forbidden");
    return { user: claims.sub, tags: [`user:${claims.sub}`] };
  },
});
```

Apps read it with `client.index("BoardFeed", partition)`. See [IndexHandle](/sdk/index-handle).

### Close a removed member's connections

```ts luna/lunas/board-search.ts
removeMember: h({ args: { board: t.string(), user: t.string() } }, (ctx, { board, user }) => {
  ctx.send(BoardFeed, { p: board }).closeConnections({ tag: `user:${user}`, code: 4001, reason: "removed" });
}),
```

The code defaults to `4000` and the reason to an empty string.
