Query across lunas
Keep an index of rows from many lunas' tables or events with defineIndex, read it from handlers and apps, and read your own writes with a bookmark.
One luna cannot query another luna’s tables. A Board that wants every task assigned to Ann would have to call each of its Card lunas and merge their answers, on every read.
Define an index
An index is a table of rows that Luna keeps for you, filled from the tables or events of many lunas. Each Card keeps its own tasks.
import { defineLuna, t, table } from "luna";
export const Card = defineLuna({
name: "Card",
key: { board: t.string(), card: t.int() },
schema: {
tasks: table({ id: t.id(), text: t.string(), assignee: t.string() }),
},
handlers: (h) => ({
addTask: h(
{ args: { text: t.string(), assignee: t.string() } },
(ctx, { text, assignee }) => {
ctx.db.tasks.insert({ text, assignee });
return ctx.bookmark();
},
),
}),
});
defineIndex names the index and says what fills it. Here every Card’s task rows go into BoardTasks, with the board and card from the card’s key.
import { defineIndex } from "luna";
import { Card } from "./card.ts";
export const BoardTasks = defineIndex("BoardTasks", {
partition: "board",
from: [
Card.changes.tasks.map((task, card) => ({
text: task.text,
assignee: task.assignee,
board: card.board,
card: card.card,
})),
],
});
Export the index from the module your luna.config.ts names, as you do a luna type. The name starts with a capital letter.
Read an index from a handler
ctx.index reads the index from any handler, with find, count and the other reads below.
import { defineLuna, t } from "luna";
import { BoardTasks } from "./tasks.ts";
export const Board = defineLuna({
name: "Board",
key: { id: t.string() },
handlers: (h) => ({
assigned: h({ args: { user: t.string() } }, async (ctx, { user }) => {
const rows = await ctx.index(BoardTasks).find({
partition: ctx.key.id,
where: { assignee: user },
orderBy: "card",
});
return rows.map((r) => `${r.card}: ${r.text}`);
}),
}),
});
Reads are asynchronous, since the index is kept apart from the luna that reads it. Every column of an index row may be null.
Know what an index holds
An index holds rows, and only its sources write them. An upsert in a source table replaces that row in the index, and a delete removes it. When a source luna is destroyed, its rows leave the index.
The rows arrive after the source’s handler commits, so a read straight after a write may not see it yet. Read your own write shows how to wait for it.
Sources are table changes, as above, or events. React to table changes covers changes, map and where, and Emit events covers events.
Split an index into partitions
partition names a column whose value splits the index into parts kept apart, one for each board here. A read that passes partition reads only that part.
A read without partition reads every part and merges the answers. An index without the partition option has 16 parts, chosen by the source luna’s key.
Read your own write
ctx.bookmark() marks where the handler’s writes will stand in the indexes they fill. Pass it as after, and the read waits until those writes are in. This handler of Board takes one as an argument, typed with Bookmark from luna.
assignedAfter: h(
{ args: { user: t.string(), after: t.json<Bookmark>().optional() } },
async (ctx, { user, after }) =>
ctx.index(BoardTasks).find({
partition: ctx.key.id,
where: { assignee: user },
after: after ?? undefined,
}),
),
Card.addTask returns its bookmark, and the app passes it on to Board.assignedAfter. A read waits up to 5 seconds, or timeout in milliseconds, then fails with the error Behind.
A handler can also write, then read the index after its own write, in one call. Pass after: ctx.bookmark() to the read, whose await stores the writes made before it.
Choose a read
IndexQuery has a method for each kind of read. Each takes partition, after and timeout.
| Method | Returns |
|---|---|
find |
Rows, with where, orderBy, limit and offset |
page |
One page of rows and a cursor for the next |
count |
How many rows match |
groupBy |
Rows per group, with sum, min and max |
search |
Full-text hits, when the index has search |
nearest |
The rows nearest a vector |
The index’s own options add to what it can do.
| Option | Does |
|---|---|
columns |
Gives the columns’ types, when they cannot be read from the sources |
indexes |
Adds indexes on its rows, as a table’s indexes do |
search |
Keeps a full-text index, as Search text describes. keepText: false keeps only the words |
idleTimeout |
How long a partition stays awake after its last batch or read, "5s" by default |
onBeforeConnect |
Lets apps read a partition directly |
Read an index from an app
An app reads one partition of an index directly, and live, with client.index(name, partition). The index decides who may, with onBeforeConnect(ctx, request, partition). Without that hook, apps cannot read it. Call lunas from TypeScript shows the app side.
To look at an index’s rows yourself, run luna indexes.
Next steps
- React to table changes explains the sources an index is filled from.
- Call lunas from TypeScript reads an index from an app.
- defineIndex lists every option and read.