@yaks/fts 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/compile.ts ADDED
@@ -0,0 +1,453 @@
1
+ // The query half: a bare word in a query compiles to an FTS5 match.
2
+ //
3
+ // A query mixes words and filters — `hobbit .book.price<20` — and @yaks/query parses
4
+ // each bare word as a `text` clause. @yaks/sql compiles every clause except
5
+ // that one; this module is the @yaks/sql extension that compiles it, registered
6
+ // through `compile(ast, vocab, { extend: [search(fields)] })`.
7
+ //
8
+ // One clause is one word, or one run somebody quoted (@yaks/query splits on
9
+ // whitespace), so `term` converts it — a word matches as a prefix, a quoted run
10
+ // stays a phrase — and several words are ANDed together the way every other
11
+ // clause is.
12
+ //
13
+ // The generated condition is one `in` subquery per indexed component, ORed
14
+ // together: an index's rowid is the entity's integer id in the `entity` table,
15
+ // so a match yields ids the surrounding statement already uses, and no join is
16
+ // needed. The AND between words comes from how @yaks/sql combines clauses, not
17
+ // from this file.
18
+ //
19
+ // `.order=search` ranks what the words selected by relevance, closest first
20
+ // (`.order=-search` the weakest first). bm25 can only be read in a statement
21
+ // that matches the index, and an ORDER BY term re-matching per row costs a
22
+ // whole search per row, so the ranking runs once, through the server's own
23
+ // connection, among the rows the rest of the query admits (./search.ts). The
24
+ // order is then each entity's place in it, spelled over integer ids: the one
25
+ // value an ORDER BY here can carry. A window of a query with words that states
26
+ // no order is ranked the same way (`ranks`): a page of a search is its best
27
+ // rows, as a search box's are, never its newest. Its first page ranks only as
28
+ // many as it shows and reads only those (`reach`), so a broad word costs a
29
+ // page, not every match. A search composed without a connection selects but
30
+ // does not rank.
31
+
32
+ import {
33
+ among,
34
+ and,
35
+ as,
36
+ col,
37
+ type Compound,
38
+ count,
39
+ type Driver,
40
+ eq,
41
+ type Extension,
42
+ FALSE,
43
+ from,
44
+ lit,
45
+ lookup,
46
+ not,
47
+ op,
48
+ or,
49
+ type Query,
50
+ type Raw,
51
+ type Screen,
52
+ type Select,
53
+ select,
54
+ type Selection,
55
+ type Site,
56
+ type Source,
57
+ table,
58
+ unionAll,
59
+ Unsupported,
60
+ val,
61
+ } from '@yaks/sql'
62
+ import {
63
+ FEW,
64
+ permitted,
65
+ ranked,
66
+ screens,
67
+ unworn,
68
+ withinOwners,
69
+ } from './search.js'
70
+ import { type Field, indexes, tableOf, tailOf, trim, worded } from './fields.js'
71
+ import { grammed, named, phrased, term } from './term.js'
72
+ import { DONE, type Filler, PAST, PIECES, SPAN } from './ddl.js'
73
+ import { type And, type Clause, map, words as wordsIn } from '@yaks/query/core'
74
+
75
+ // The ranking `.order=` names.
76
+ export let SEARCH = 'search'
77
+
78
+ // How many of the best matches `.order=search` puts in order; any past them
79
+ // follow, newest first.
80
+ export let RANKED = 1000
81
+
82
+ let mandatory = (c: Clause): number =>
83
+ c.kind == 'and'
84
+ ? c.clauses.reduce((n, child) => n + mandatory(child), 0)
85
+ : Number(c.kind == 'text')
86
+
87
+ // How many of a query's best rows its answer reaches, when those are all it
88
+ // reaches: the first page (no `.after`) of a window of at most `RANKED` rows
89
+ // ordered by search, whose words are all mandatory clauses of its own. A word
90
+ // under OR or a child filter selects rows an all-word ranking never sees.
91
+ ///
92
+ /// let { parse } = await import('@yaks/query')
93
+ /// reach(parse('dragon .limit=5 .order=search')) -> 5
94
+ /// reach(parse('dragon .limit=5 .order=-search')) -> null
95
+ /// reach(parse('dragon .limit=5 .order=search .after=7')) -> null
96
+ /// reach(parse('(dragon|scale) .limit=5 .order=search')) -> null
97
+ /// reach(parse('dragon (scale) .limit=5 .order=search')) -> 5
98
+ /// reach(parse('dragon .limit=5000 .order=search')) -> null
99
+ export let reach = (q: And): number | null => {
100
+ let limit = q.clauses.find((c) => c.kind == 'limit')
101
+ let orders = q.clauses.filter((c) => c.kind == 'order')
102
+ if (
103
+ !limit || limit.n < 1 || limit.n > RANKED ||
104
+ orders.length != 1 || orders[0].value != SEARCH ||
105
+ q.clauses.some((c) => c.kind == 'after')
106
+ ) return null
107
+ let all = 0
108
+ map(q, (c) => {
109
+ if (c.kind == 'text') all++
110
+ return c
111
+ })
112
+ let own = mandatory(q)
113
+ return all == own ? limit.n : null
114
+ }
115
+
116
+ // How many rows a substring index may find for a `~=` needle for a read to
117
+ // be driven from them, each read and tested. Past it the needle is common, and
118
+ // a read in its own order stops at its page sooner. On the box's 700,000
119
+ // transcript texts the two cost the same near 4,000: a page of 25 of a needle
120
+ // that many hold is found within about 4,400 texts in order.
121
+ export let FEW_TEXTS = 4000
122
+
123
+ // Try the indexed screen first for a filtered ranking. Keep only a bounded
124
+ // set in the compiler, falling back to keyed probes for a wide screen.
125
+ let SCREEN = 4096
126
+
127
+ let candidates = (db: Driver, screen: Selection): number[] | undefined => {
128
+ let seek = screen.seek?.()
129
+ if (!seek) return
130
+ let ids = db.query(select({
131
+ cols: [col('id')],
132
+ from: from(seek),
133
+ limit: lit(SCREEN + 1),
134
+ })).map((r) => Number(r.id))
135
+ return ids.length <= SCREEN ? ids : undefined
136
+ }
137
+
138
+ // The @yaks/sql extension that resolves bare words against the search indexes.
139
+ // It handles the `text` clause, covering every indexed field, and orders by
140
+ // relevance to those words. Without this extension @yaks/sql rejects bare
141
+ // words rather than assuming an index exists. It also answers which owners a
142
+ // `~=` test of a substring-indexed property can hold (`contains`), sized
143
+ // through `db`; `fill` says which index is still being filled, and holds only
144
+ // the rows its cursor has passed until it is, so it answers nothing.
145
+ export let search = (
146
+ fields: Field[],
147
+ db?: Driver,
148
+ fill?: Pick<Filler, 'pending'>,
149
+ ): Extension => {
150
+ // Whether the file holds a substring index, asked once a read.
151
+ let standing = new Map<string, boolean>()
152
+ let stands = (fts: string): boolean => {
153
+ let is = standing.get(fts)
154
+ if (is == null) {
155
+ standing.set(
156
+ fts,
157
+ is = !!db!.query(select({
158
+ cols: [lit(1)],
159
+ from: table('sqlite_schema'),
160
+ where: eq(col('name'), val(fts)),
161
+ })).length,
162
+ )
163
+ }
164
+ return is
165
+ }
166
+ // What each needle's index found this query, by index and needle: one
167
+ // read asks again for each plan it weighs.
168
+ let found = new Map<string, { owners: Query; few: boolean }>()
169
+ // The words this query searched for (as terms, and as typed), and what the
170
+ // rest of it selects, remembered for its `.order=search`.
171
+ let words: string[] = []
172
+ let said: string[] = []
173
+ let asked: Screen | null = null
174
+ // The owners in relevance order, resolved once a query.
175
+ let held: number[] | null = null
176
+ let scoped: number[] | undefined
177
+ let sources: ReturnType<typeof screens> = {}
178
+ let membership = new Map<Screen, Raw | null>()
179
+ let shared = new Map<Screen, Source>()
180
+ // How many of the best rows this query's answer reaches, when that is all
181
+ // it reaches (`reach`), and whether the ranking is being read.
182
+ let page: number | null = null
183
+ let ranking = false
184
+ let aspects: ReturnType<typeof screens> = {}
185
+ // The fields whose index stands: one over a component no table stands for
186
+ // yet (@yaks/sql `Site.absent`) holds nothing, and has no index to ask, and
187
+ // nobody wears such a component to be left out by it.
188
+ let live = fields
189
+ let seen = (site: Site) => {
190
+ let gone = new Set(site.absent)
191
+ live = gone.size
192
+ ? fields.filter((f) => !gone.has(f.comp) && !(f.on && gone.has(f.on)))
193
+ .map((f) => trim(f, (comp) => !gone.has(comp)))
194
+ : fields
195
+ aspects = screens(live, site.vocab, {
196
+ visibility: { components: site.visibility?.components },
197
+ absent: site.absent,
198
+ })
199
+ }
200
+ let rank = (): number[] => {
201
+ if (held) return held
202
+ let screen = asked?.() ?? undefined
203
+ ranking = true
204
+ try {
205
+ // A session's indexed entries can be read once before MATCH. Probing
206
+ // the full screen per posting seeks dates and transcript text for hits
207
+ // from unrelated sessions, long before LIMIT can take effect.
208
+ scoped = screen && db!.file ? candidates(db!, screen) : undefined
209
+ held = ranked(db!, live, words.join(' '), {
210
+ screen,
211
+ owners: scoped,
212
+ // The query's screen already admits the owner through entity visibility.
213
+ // Repeating it for each text source multiplies the ranking's VM program.
214
+ screens: screen ? aspects : sources,
215
+ limit: page ?? RANKED,
216
+ plan: db!.file ? 'sort' : 'index',
217
+ name: named(said.join(' ')),
218
+ })
219
+ } finally {
220
+ ranking = false
221
+ }
222
+ return held
223
+ }
224
+ return {
225
+ name: 'fts',
226
+ // A ranked page's words select its best rows, `page` owners at most.
227
+ few: (q) => db && reach(q) != null ? ['text'] : [],
228
+ begin: (screen, q) => {
229
+ found.clear()
230
+ standing.clear()
231
+ asked = screen
232
+ held = null
233
+ scoped = undefined
234
+ sources = {}
235
+ membership.clear()
236
+ shared.clear()
237
+ page = db ? reach(q) : null
238
+ // A page's words are all the query's own, so they are known now.
239
+ words = []
240
+ said = []
241
+ for (let w of page == null ? [] : wordsIn(q)) {
242
+ let t = term(w)
243
+ if (t && !words.includes(t)) {
244
+ words.push(t)
245
+ said.push(w)
246
+ }
247
+ }
248
+ },
249
+ compile: {
250
+ text: (clause, site) => {
251
+ if (clause.kind != 'text') return null
252
+ let t = term(clause.value)
253
+ seen(site)
254
+ // A search containing no word matches nothing. Compiling it to a
255
+ // constant false keeps the query away from the index rather than
256
+ // widening the result set. Nor does one with no index to search.
257
+ if (!t || !live.length) return FALSE
258
+ // A first page of a search is its best rows and no others, so when the
259
+ // ranking fills it, its words select just those, ranked once among
260
+ // what the rest of the query admits, rather than every match. A page
261
+ // the ranking leaves short reads every match: words found in different
262
+ // indexes match where no one index ranks them, and follow the ranked.
263
+ if (page != null && !ranking) {
264
+ sources = screens(live, site.vocab, {
265
+ visibility: site.visibility,
266
+ absent: site.absent,
267
+ })
268
+ let ids = rank()
269
+ if (ids.length == page) {
270
+ return among(site.owner, ids.map((id) => lit(id)))
271
+ }
272
+ }
273
+ // A screen compiled for another extension reads this clause again.
274
+ if (!words.includes(t)) {
275
+ words.push(t)
276
+ said.push(clause.value)
277
+ }
278
+ sources = screens(live, site.vocab, {
279
+ visibility: site.visibility,
280
+ absent: site.absent,
281
+ })
282
+ let screen = site.screen
283
+ let allowed: Source | undefined
284
+ let scope = page != null && !ranking ? scoped : undefined
285
+ if (!scope && screen?.maximum != null && screen.maximum <= FEW) {
286
+ if (!membership.has(screen)) membership.set(screen, screen())
287
+ let within = membership.get(screen)
288
+ if (within) {
289
+ allowed = shared.get(screen)
290
+ if (!allowed) shared.set(screen, allowed = site.share(within))
291
+ }
292
+ }
293
+ // The owner is a row the query already admits through entity
294
+ // visibility, so a posting is asked only what its component's own
295
+ // visibility says. Asking each posting the entity's too sought the
296
+ // entity table once for every row holding the word: `task` beside a
297
+ // project's tasks read millions of transcript rows' entities cold.
298
+ return or(
299
+ ...indexes(worded(live), db?.stored?.v ?? site.vocab).map((ix) => {
300
+ let { name, not } = ix, fts = tableOf(ix)
301
+ return among(
302
+ site.owner,
303
+ select({
304
+ cols: [col('rowid')],
305
+ from: table(fts),
306
+ where: and(
307
+ op('match', col(fts), val(t)),
308
+ permitted(name, col('rowid', fts), aspects),
309
+ ...unworn(not, col('rowid', fts)),
310
+ ...scope ? [withinOwners(col('rowid', fts), scope)] : [],
311
+ ...allowed
312
+ ? [among(
313
+ col('rowid', fts),
314
+ select({ cols: [col('id')], from: allowed }),
315
+ )]
316
+ : [],
317
+ ),
318
+ }),
319
+ )
320
+ }),
321
+ )
322
+ },
323
+ },
324
+ // The texts a property's substring index finds holding all of a needle's
325
+ // trigrams, in their first CUT or a piece of their tail past it, and the
326
+ // ones longer than CUT whose pieces are still owed (`PAST` without
327
+ // `DONE`), and whether there are at most FEW_TEXTS of them. A needle's
328
+ // first SPAN characters lie whole in the first CUT or in one piece, so
329
+ // its trigrams are those characters'. Until the tail index stands,
330
+ // the marker alone identifies every longer text.
331
+ //
332
+ // More than FEW_TEXTS of them, the texts a word index finds holding the
333
+ // needle's whole words in order (`phrased`) take their place where those
334
+ // are few: one that covers the property for every owner the read keeps,
335
+ // its text's own or one of a component the read requires (`within`). A
336
+ // phrase of common words is in every long text's trigrams, and few of
337
+ // their words: `.entry & .content.body~="apps shows the new button"`
338
+ // found 18,841 texts holding 1.1 GB, and walked the box's every entity
339
+ // to test them, 11 s (bug 14fa2b99); "shows the new" is in 117, and
340
+ // "shows the new button" * fewer still.
341
+ contains: (comp, prop, needle, within = []) => {
342
+ // SQLite's trigram tokenizer and Unicode lowercasing can disagree.
343
+ // Only use its candidates for the ASCII LIKE path.
344
+ if (/\P{ASCII}/u.test(needle)) return null
345
+ let ix = indexes(fields, db?.stored?.v).find((ix) =>
346
+ ix.trigram && ix.comp == comp && ix.props.includes(prop)
347
+ )
348
+ let m = ix && grammed([...needle].slice(0, SPAN).join(''))
349
+ if (!ix || !m) return null
350
+ let fts = tableOf(ix), tail = tailOf(ix)
351
+ let match = (t: string, q: string) => op('match', col(t), val(q))
352
+ let owners: Query = db && stands(tail)
353
+ ? unionAll(
354
+ select({
355
+ cols: [col('rowid')],
356
+ from: table(fts),
357
+ where: match(fts, m),
358
+ }),
359
+ select({
360
+ cols: [op('/', col('rowid'), lit(PIECES))],
361
+ from: table(tail),
362
+ where: match(tail, m),
363
+ }),
364
+ select({
365
+ cols: [col('rowid')],
366
+ from: table(fts),
367
+ where: and(
368
+ match(fts, `"${PAST}"`),
369
+ not(among(
370
+ op('*', col('rowid'), lit(PIECES)),
371
+ select({
372
+ cols: [col('rowid')],
373
+ from: table(tail),
374
+ where: match(tail, `"${DONE}"`),
375
+ }),
376
+ )),
377
+ ),
378
+ }),
379
+ )
380
+ : select({
381
+ cols: [col('rowid')],
382
+ from: table(fts),
383
+ where: match(fts, `(${m}) OR "${PAST}"`),
384
+ })
385
+ // An index this file does not hold yet (its writer has not opened it
386
+ // with this vocabulary), or holds while still filling it, finds too
387
+ // few: the read goes in its own order and tests every text, and,
388
+ // answered rather than declined, is built again next time rather than
389
+ // kept (@yaks/sql kept.ts).
390
+ if (!db || !stands(fts) || fill?.pending(fts)) return { few: false }
391
+ let phrase = phrased(needle)
392
+ let words = phrase
393
+ ? indexes(worded(fields), db.stored?.v).find((w) =>
394
+ w.comp == comp && w.props.includes(prop) &&
395
+ (!w.on || within.includes(w.on)) && stands(tableOf(w)) &&
396
+ !fill?.pending(tableOf(w))
397
+ )
398
+ : undefined
399
+ let key = `${fts}\0${m}\0${words ? tableOf(words) : ''}`
400
+ let known = found.get(key)
401
+ if (known) return known
402
+ // Only a caller's read begins, so a compile that never does (a rule's
403
+ // patterns) keeps no more than a few.
404
+ if (found.size >= 64) found.clear()
405
+ let few = (q: Select | Compound) =>
406
+ Number(
407
+ db.query(select({
408
+ cols: [as(count(), 'n')],
409
+ from: from({ ...q, limit: lit(FEW_TEXTS + 1) }, 'r'),
410
+ }))[0].n,
411
+ ) <= FEW_TEXTS
412
+ let said = words && select({
413
+ cols: [col('rowid')],
414
+ from: table(tableOf(words)),
415
+ where: match(tableOf(words), phrase!),
416
+ })
417
+ let answer = few(owners)
418
+ ? { owners, few: true }
419
+ : said && few(said)
420
+ ? { owners: said, few: true }
421
+ : { owners, few: false }
422
+ found.set(key, answer)
423
+ return answer
424
+ },
425
+
426
+ // A window of a query with words in it is a search's best rows unless it
427
+ // says otherwise, where there is a connection to rank through.
428
+ ranks: (q) => db && wordsIn(q).some((w) => !!term(w)) ? SEARCH : null,
429
+ order: (value, site) => {
430
+ if (value != SEARCH) return null
431
+ seen(site)
432
+ if (!words.length || !db) {
433
+ throw new Unsupported(
434
+ `.order=${SEARCH}`,
435
+ db
436
+ ? 'nothing to rank by — it orders the words of a text search'
437
+ : 'a search composed without a connection does not rank',
438
+ '@yaks/fts',
439
+ )
440
+ }
441
+ let ids = rank()
442
+ // No match selects no rows, so there is nothing to put in order.
443
+ if (!ids.length) return lit(null)
444
+ // Site.owner is this row's stable integer id, including cursor anchors.
445
+ return lookup(
446
+ site.owner,
447
+ ids.map((id, i) => [id, lit(i)]),
448
+ { stable: true },
449
+ lit(ids.length),
450
+ )
451
+ },
452
+ }
453
+ }