Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

defineIndex

Declare an index whose rows Luna keeps from many lunas' tables and events, and read it with ctx.index.

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.

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)

PropType
namestring

The index's name, starting with a capital letter, like a luna type's.

Typestring
options.fromSource[]

What fills it: table changes and events, each mapped to the index's fields.

TypeSource[]
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.

Typestring
options.columns?Record<string, Ty>

The index's columns, when its sources' field types cannot tell them, and otherwise each source's fields, nullable.

TypeRecord<string, Ty>
options.indexes?{ columns: string[] }[]

Extra indexes on its rows, to make reads by those columns faster.

Type{ columns: string[] }[]
options.search?{ columns, tokenizer?, keepText? }

A full-text index over some columns, for `search`.

Type{ columns, tokenizer?, keepText? }
options.onBeforeConnect?(ctx, request, partition) => unknown

Lets apps read a partition as a live query, and decides who may.

Type(ctx, request, partition) => unknown
options.idleTimeout?string | number

How long a partition stays awake after its last batch or read.

Typestring | number
Default"5s"

search takes these fields.

PropType
columnsstring[]

The columns whose words are searched.

Typestring[]
tokenizer?"unicode61" | "porter" | "trigram"

How text is split into words.

Type"unicode61" | "porter" | "trigram"
keepText?boolean | string[]

With `false` the columns keep only their words and reads give `null` for them, and a list keeps the text of those columns only.

Typeboolean | string[]
Defaulttrue

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.

PropType
partition?string | number

The partition to read, and when left out, every partition is read and the results merged.

Typestring | number
after?Bookmark

Waits until the writes the bookmark names are in the index.

TypeBookmark
timeout?number

How many milliseconds to wait for `after` before the read fails with `Behind`.

Typenumber
Default5000

IndexQuery

PropType
find(opts?) => Promise<Row[]>

Rows that match `where`, in `orderBy` order, with `limit` and `offset`.

Type(opts?) => Promise<Row[]>
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.

Type(opts?) => Promise<{ rows: Row[]; cursor: unknown[] | null }>
count(opts?) => Promise<number>

How many rows match `where`.

Type(opts?) => Promise<number>
groupBy(by: string[], opts?) => Promise<GroupRow[]>

Rows per group with `count` and the `sum`, `min` and `max` of the columns named, largest groups first.

Type(by: string[], opts?) => Promise<GroupRow[]>
search(text: string, opts?) => Promise<{ row: Row; score: number }[]>

Full-text search, best matches first, for an index with `search`.

Type(text: string, opts?) => Promise<{ row: Row; score: number }[]>
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.

Type(column: string, to: Float32Array | number[], opts?) => Promise<{ row: Row; distance: number }[]>

where, orderBy, limit and offset work as in ctx.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.

PropType
source{ type: string; key: Record<string, unknown> }

The luna that wrote.

Type{ type: string; key: Record<string, unknown> }
at{ listen: string; to: string; key: Record<string, unknown>; seq: number }[]

For each listen and listening luna, the last change noted for it.

Type{ listen: string; to: string; key: Record<string, unknown>; seq: number }[]

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

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.

add: h({ args: { text: t.string() } }, (ctx, { text }) => {
  ctx.db.notes.insert({ text });
  return ctx.bookmark();
}),
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

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

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.

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

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.

Close a removed member’s connections

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.

Was this page helpful?