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)
namestring
The index's name, starting with a capital letter, like a luna type's.
stringoptions.fromSource[]
What fills it: table changes and events, each mapped to the index's fields.
Source[]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.
stringoptions.columns?Record<string, Ty>
The index's columns, when its sources' field types cannot tell them, and otherwise each source's fields, nullable.
Record<string, Ty>options.indexes?{ columns: string[] }[]
Extra indexes on its rows, to make reads by those columns faster.
{ columns: string[] }[]options.search?{ columns, tokenizer?, keepText? }
A full-text index over some columns, for `search`.
{ columns, tokenizer?, keepText? }options.onBeforeConnect?(ctx, request, partition) => unknown
Lets apps read a partition as a live query, and decides who may.
(ctx, request, partition) => unknownoptions.idleTimeout?string | number
How long a partition stays awake after its last batch or read.
string | number"5s"search takes these fields.
columnsstring[]
The columns whose words are searched.
string[]tokenizer?"unicode61" | "porter" | "trigram"
How text is split into words.
"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.
boolean | string[]truedefineIndex 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.
partition?string | number
The partition to read, and when left out, every partition is read and the results merged.
string | numberafter?Bookmark
Waits until the writes the bookmark names are in the index.
Bookmarktimeout?number
How many milliseconds to wait for `after` before the read fails with `Behind`.
number5000IndexQuery
find(opts?) => Promise<Row[]>
Rows that match `where`, in `orderBy` order, with `limit` and `offset`.
(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.
(opts?) => Promise<{ rows: Row[]; cursor: unknown[] | null }>count(opts?) => Promise<number>
How many rows match `where`.
(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.
(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`.
(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.
(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.
source{ type: string; key: Record<string, unknown> }
The luna that wrote.
{ 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.
{ 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
partitionlists every partition and reads each. Name the partition when you know it. - A write before an
awaitcommits there. So a handler can write, then read the index withafter: ctx.bookmark(). - A read that waits longer than
timeoutforafterthrows aLunaCallErrorwhosecodeisBehind. - A deploy that changes an index’s columns,
searchorpartitionfills 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’sauth, and atagslist 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.