@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/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts","testing.ts","cost_testing.ts"]},"name":"@yaks/fts","version":"0.2.36","license":"Apache-2.0","description":"Indexes a graph's text properties with SQLite FTS5 and adds ranked full-text search to queries.","exports":{".":"./mod.ts","./fields":"./fields.ts","./lexicon":"./lexicon.ts","./term":"./term.ts"},"imports":{"@yaks/fts":"./mod.ts","@yaks/fts/fields":"./fields.ts","@yaks/fts/lexicon":"./lexicon.ts","@yaks/fts/term":"./term.ts"}}
package/fields.js ADDED
@@ -0,0 +1,155 @@
1
+ // Which text is searchable. Search is not limited to a single "document"
2
+ // component: a vocabulary declares components, some of their properties hold
3
+ // prose, and any of those can be indexed. This module makes that selection — a
4
+ // `Field` is one `comp.prop` pair, `fields()` reads them off a vocabulary, and
5
+ // a `Pick` narrows the default when an application wants only some of them.
6
+ //
7
+ // The fields are grouped into one index per component (`indexes()`), because an
8
+ // FTS5 external-content index mirrors exactly one table. A field read on behalf
9
+ // of another component (`on`) is grouped under that one: `entry` is found by
10
+ // `content.body`, so `entry_fts` indexes the body of every entity that is an
11
+ // entry, and of no other entity carrying `content`.
12
+ //
13
+ // A component the vocabulary marks `found: false` (a quarantine) keeps its
14
+ // wearers out of every word search: their text stays indexed, so the mark
15
+ // coming off finds them again at once, and each field carries those components
16
+ // as its `not`, which a match tests its owner against.
17
+ //
18
+ // A property can also keep a substring index (`contains: true`): an FTS5
19
+ // trigram index over its text, which a `~=` test reads instead of every value
20
+ // (`grams()`). Its fields are marked `trigram`, and group into indexes of their
21
+ // own beside the word indexes.
22
+ import { field } from "@yaks/sql/core";
23
+ // Stored prose: an index is created from a table, so a computed property has no
24
+ // stored value to index, and a number or an entity reference holds no words.
25
+ let prose = (c)=>!c.computed && c.category == 'scalar' && c.scalar == 'text';
26
+ // A field retains the vocabulary it came from, so a schema prepared before
27
+ // a connection is bound uses the identities of a fresh store. The bound
28
+ // vocabulary can still select the label layout of an existing file.
29
+ let declared = new WeakMap();
30
+ let declaredIn = (v, f)=>{
31
+ declared.set(f, v);
32
+ return f;
33
+ };
34
+ // The default selection: the properties the vocabulary marked searchable with
35
+ // `"search": true` (@yaks/vocab). Deciding which prose is worth finding belongs
36
+ // to the vocabulary, not to this package: a repository path and a provider name
37
+ // are text nobody goes looking for, and indexing them only adds terms a search
38
+ // has to wade through. A vocabulary that marks none has nothing to search.
39
+ export let searched = (c)=>c.search && prose(c);
40
+ // The searchable fields of a vocabulary, by component then declaration order,
41
+ // then the text each component's `search` list says its entities are found by.
42
+ // `pick` narrows the properties; a list is the vocabulary's own statement about
43
+ // its component and is always taken.
44
+ export let fields = (vocab, pick = searched)=>[
45
+ ...vocab.all.flatMap((comp)=>vocab.props(comp).map((prop)=>vocab.prop(comp, prop)).filter(pick).map((c)=>declaredIn(vocab, {
46
+ comp,
47
+ prop: c.prop,
48
+ ...unfound(vocab)
49
+ }))),
50
+ ...vocab.all.flatMap((on)=>(vocab.comp(on)?.search ?? []).map((name)=>{
51
+ let [comp, prop] = name.split('.');
52
+ return declaredIn(vocab, {
53
+ comp,
54
+ prop,
55
+ on,
56
+ ...unfound(vocab)
57
+ });
58
+ }))
59
+ ];
60
+ // What keeps an entity out of a word search: the components the vocabulary
61
+ // marks `found: false`, as the `not` of a field (none, no key).
62
+ export let unfound = (vocab)=>{
63
+ let not = vocab.all.filter((comp)=>vocab.comp(comp)?.found === false);
64
+ return not.length ? {
65
+ not
66
+ } : {};
67
+ };
68
+ // `f` excluding only the components that stand: one no table stands for yet
69
+ // (@yaks/sqlite makes it on its first write) is worn by nobody.
70
+ export let trim = (f, stands)=>!f.not || f.not.every(stands) ? f : {
71
+ ...f,
72
+ not: f.not.filter(stands)
73
+ };
74
+ // The properties that keep a substring index, the vocabulary's `contains`,
75
+ // by component then declaration order. `pick` narrows them.
76
+ export let grams = (vocab, pick = (c)=>!!c.contains)=>vocab.all.flatMap((comp)=>vocab.props(comp).map((prop)=>vocab.prop(comp, prop)).filter((c)=>prose(c) && pick(c)).map((c)=>declaredIn(vocab, {
77
+ comp,
78
+ prop: c.prop,
79
+ trigram: true,
80
+ ...c.contains == 'property' ? {
81
+ separate: true
82
+ } : {}
83
+ })));
84
+ // Every field a vocabulary has indexed: its words and its substrings. What a
85
+ // store keeps indexes for and its `search` extension reads.
86
+ export let indexed = (vocab)=>[
87
+ ...fields(vocab),
88
+ ...grams(vocab)
89
+ ];
90
+ // The fields a bare word searches: all but the substring indexes'.
91
+ export let worded = (fields)=>fields.filter((f)=>!f.trigram);
92
+ // The fields grouped into indexes, one per name, in first-seen order.
93
+ export let indexes = (fields, v)=>{
94
+ let by = new Map();
95
+ for (let f of fields){
96
+ let { comp, prop, on, not, trigram, separate } = f;
97
+ let layout = v ?? declared.get(f);
98
+ let name = on ?? comp;
99
+ let stored = layout?.stored(comp, prop) ?? prop;
100
+ let owner = layout?.stored(name) ?? name;
101
+ let suffix = separate ? `:${stored}` : '';
102
+ let key = trigram ? gramName(name + suffix) : name;
103
+ let ix = by.get(key) ?? {
104
+ name,
105
+ comp,
106
+ props: [],
107
+ ...on ? {
108
+ on
109
+ } : {},
110
+ ...not?.length ? {
111
+ not
112
+ } : {},
113
+ ...trigram && {
114
+ trigram
115
+ }
116
+ };
117
+ ix.props.push(prop);
118
+ let physical = names.get(ix);
119
+ if (!physical) {
120
+ names.set(ix, physical = {
121
+ owner: owner + suffix,
122
+ columns: []
123
+ });
124
+ }
125
+ physical.columns.push(stored == prop ? field(prop) : stored);
126
+ by.set(key, ix);
127
+ }
128
+ return [
129
+ ...by.values()
130
+ ];
131
+ };
132
+ let names = new WeakMap();
133
+ let ownerOf = (ix)=>names.get(ix)?.owner ?? ix.name;
134
+ /** The columns handled by FTS, in the order the index declares them. */ export let columnsOf = (ix)=>names.get(ix)?.columns ?? ix.props.map(field);
135
+ // The name of an index: `book` → `book_fts`.
136
+ export let indexName = (name)=>`${name}_fts`;
137
+ // The name of a substring index: `content` → `content_trigram`.
138
+ export let gramName = (name)=>`${name}_trigram`;
139
+ // The FTS5 table an index is: its word index, or its substring index.
140
+ export let tableOf = (ix)=>ix.trigram ? gramName(ownerOf(ix)) : indexName(ownerOf(ix));
141
+ // The view an index reads its text through, where it needs one (`textName`).
142
+ export let viewOf = (ix)=>textName(ix.trigram ? gramName(ownerOf(ix)) : ownerOf(ix));
143
+ // The substring index of the texts' tails past what a substring index holds,
144
+ // and the table listing the pieces it holds: `content_trigram_tail`,
145
+ // `content_trigram_piece`.
146
+ export let tailOf = (ix)=>`${gramName(ownerOf(ix))}_tail`;
147
+ export let piecesOf = (ix)=>`${gramName(ownerOf(ix))}_piece`;
148
+ // The name of the view that presents an index's columns as text: `doc` →
149
+ // `doc_text`. It is created for an index where at least one column has to be
150
+ // resolved (a `text` expression in the store's @yaks/sql `Derived`: @yaks/blob
151
+ // keeps a body's address, not its prose), and for every index read on behalf
152
+ // of another component, which reads its text through a join; an index whose
153
+ // columns hold their own text mirrors the component table itself.
154
+ export let textName = (name)=>`${name}_text`;
155
+ //# sourceMappingURL=fields.js.map
package/fields.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fields.js","sources":["./fields.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,+EAA+E;AAC/E,+EAA+E;AAC/E,4EAA4E;AAC5E,EAAE;AACF,gFAAgF;AAChF,gFAAgF;AAChF,6EAA6E;AAC7E,6EAA6E;AAC7E,oDAAoD;AACpD,EAAE;AACF,2EAA2E;AAC3E,0EAA0E;AAC1E,+EAA+E;AAC/E,uDAAuD;AACvD,EAAE;AACF,yEAAyE;AACzE,8EAA8E;AAC9E,gFAAgF;AAChF,+BAA+B;AAG/B,SAAS,KAAK,8BAAmC;AAmBjD,gFAAgF;AAChF,6EAA6E;AAC7E,IAAI,QAAc,CAAC,IACjB,CAAC,EAA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O,IAAI,SAAS,CAAC,KAAsB,GAAG,SAAS,QAAQ,KAAK,KAAK,CAAC,CAAA;AAC1E,OAAO,IAAI,WAAW,CAAC,KAAsB,GAAG,SAAS,QAAQ,KAAK,MAAM,CAAC,CAAA;AAE7E,yEAAyE;AACzE,6EAA6E;AAC7E,+EAA+E;AAC/E,6EAA6E;AAC7E,4EAA4E;AAC5E,kEAAkE;AAClE,OAAO,IAAI,WAAW,CAAC,OAAyB,GAAG,KAAK,KAAK,CAAC,CAAA"}
package/fields.ts ADDED
@@ -0,0 +1,207 @@
1
+ // Which text is searchable. Search is not limited to a single "document"
2
+ // component: a vocabulary declares components, some of their properties hold
3
+ // prose, and any of those can be indexed. This module makes that selection — a
4
+ // `Field` is one `comp.prop` pair, `fields()` reads them off a vocabulary, and
5
+ // a `Pick` narrows the default when an application wants only some of them.
6
+ //
7
+ // The fields are grouped into one index per component (`indexes()`), because an
8
+ // FTS5 external-content index mirrors exactly one table. A field read on behalf
9
+ // of another component (`on`) is grouped under that one: `entry` is found by
10
+ // `content.body`, so `entry_fts` indexes the body of every entity that is an
11
+ // entry, and of no other entity carrying `content`.
12
+ //
13
+ // A component the vocabulary marks `found: false` (a quarantine) keeps its
14
+ // wearers out of every word search: their text stays indexed, so the mark
15
+ // coming off finds them again at once, and each field carries those components
16
+ // as its `not`, which a match tests its owner against.
17
+ //
18
+ // A property can also keep a substring index (`contains: true`): an FTS5
19
+ // trigram index over its text, which a `~=` test reads instead of every value
20
+ // (`grams()`). Its fields are marked `trigram`, and group into indexes of their
21
+ // own beside the word indexes.
22
+
23
+ import type { Prop, Vocab } from 'jsr:@yaks/vocab@0.2.36'
24
+ import { field } from '@yaks/sql/core'
25
+
26
+ // A `comp.prop` pair naming one indexed text property — a book's title, a
27
+ // review's prose, a shop's own description — and, for text an entity is found
28
+ // by through another of its components, that component (`on`).
29
+ export type Field = {
30
+ comp: string
31
+ prop: string
32
+ on?: string
33
+ // components whose wearers no word search finds (vocabulary `found: false`)
34
+ not?: string[]
35
+ trigram?: true
36
+ separate?: true
37
+ }
38
+
39
+ // Decides whether a property is indexed. An application passes its own to index
40
+ // less than the vocabulary marked — say, titles only.
41
+ export type Pick = (prop: Prop) => boolean
42
+
43
+ // Stored prose: an index is created from a table, so a computed property has no
44
+ // stored value to index, and a number or an entity reference holds no words.
45
+ let prose: Pick = (c) =>
46
+ !c.computed && c.category == 'scalar' && c.scalar == 'text'
47
+
48
+ // A field retains the vocabulary it came from, so a schema prepared before
49
+ // a connection is bound uses the identities of a fresh store. The bound
50
+ // vocabulary can still select the label layout of an existing file.
51
+ let declared = new WeakMap<Field, Vocab>()
52
+ let declaredIn = (v: Vocab, f: Field): Field => {
53
+ declared.set(f, v)
54
+ return f
55
+ }
56
+
57
+ // The default selection: the properties the vocabulary marked searchable with
58
+ // `"search": true` (@yaks/vocab). Deciding which prose is worth finding belongs
59
+ // to the vocabulary, not to this package: a repository path and a provider name
60
+ // are text nobody goes looking for, and indexing them only adds terms a search
61
+ // has to wade through. A vocabulary that marks none has nothing to search.
62
+ export let searched: Pick = (c) => c.search && prose(c)
63
+
64
+ // The searchable fields of a vocabulary, by component then declaration order,
65
+ // then the text each component's `search` list says its entities are found by.
66
+ // `pick` narrows the properties; a list is the vocabulary's own statement about
67
+ // its component and is always taken.
68
+ export let fields = (vocab: Vocab, pick: Pick = searched): Field[] => [
69
+ ...vocab.all.flatMap((comp) =>
70
+ vocab.props(comp)
71
+ .map((prop) => vocab.prop(comp, prop)!)
72
+ .filter(pick)
73
+ .map((c) => declaredIn(vocab, { comp, prop: c.prop, ...unfound(vocab) }))
74
+ ),
75
+ ...vocab.all.flatMap((on) =>
76
+ (vocab.comp(on)?.search ?? []).map((name) => {
77
+ let [comp, prop] = name.split('.')
78
+ return declaredIn(vocab, { comp, prop, on, ...unfound(vocab) })
79
+ })
80
+ ),
81
+ ]
82
+
83
+ // What keeps an entity out of a word search: the components the vocabulary
84
+ // marks `found: false`, as the `not` of a field (none, no key).
85
+ export let unfound = (vocab: Vocab): { not?: string[] } => {
86
+ let not = vocab.all.filter((comp) => vocab.comp(comp)?.found === false)
87
+ return not.length ? { not } : {}
88
+ }
89
+
90
+ // `f` excluding only the components that stand: one no table stands for yet
91
+ // (@yaks/sqlite makes it on its first write) is worn by nobody.
92
+ export let trim = (f: Field, stands: (comp: string) => boolean): Field =>
93
+ !f.not || f.not.every(stands) ? f : { ...f, not: f.not.filter(stands) }
94
+
95
+ // The properties that keep a substring index, the vocabulary's `contains`,
96
+ // by component then declaration order. `pick` narrows them.
97
+ export let grams = (vocab: Vocab, pick: Pick = (c) => !!c.contains): Field[] =>
98
+ vocab.all.flatMap((comp) =>
99
+ vocab.props(comp)
100
+ .map((prop) => vocab.prop(comp, prop)!)
101
+ .filter((c) => prose(c) && pick(c))
102
+ .map((c) =>
103
+ declaredIn(vocab, {
104
+ comp,
105
+ prop: c.prop,
106
+ trigram: true,
107
+ ...c.contains == 'property' ? { separate: true } : {},
108
+ })
109
+ )
110
+ )
111
+
112
+ // Every field a vocabulary has indexed: its words and its substrings. What a
113
+ // store keeps indexes for and its `search` extension reads.
114
+ export let indexed = (vocab: Vocab): Field[] => [
115
+ ...fields(vocab),
116
+ ...grams(vocab),
117
+ ]
118
+
119
+ // The fields a bare word searches: all but the substring indexes'.
120
+ export let worded = (fields: Field[]): Field[] =>
121
+ fields.filter((f) => !f.trigram)
122
+
123
+ // One search index: its name (the component its entities are found through —
124
+ // `on` where there is one, else the text's own), the component whose table
125
+ // holds the text, and the properties it covers, in the order they are declared
126
+ // to FTS5.
127
+ export type Index = {
128
+ name: string
129
+ comp: string
130
+ props: string[]
131
+ on?: string
132
+ // components whose wearers it never answers a word for (`Field.not`)
133
+ not?: string[]
134
+ trigram?: true
135
+ }
136
+
137
+ // The fields grouped into indexes, one per name, in first-seen order.
138
+ export let indexes = (fields: Field[], v?: Vocab): Index[] => {
139
+ let by = new Map<string, Index>()
140
+ for (let f of fields) {
141
+ let { comp, prop, on, not, trigram, separate } = f
142
+ let layout = v ?? declared.get(f)
143
+ let name = on ?? comp
144
+ let stored = layout?.stored(comp, prop) ?? prop
145
+ let owner = layout?.stored(name) ?? name
146
+ let suffix = separate ? `:${stored}` : ''
147
+ let key = trigram ? gramName(name + suffix) : name
148
+ let ix = by.get(key) ??
149
+ {
150
+ name,
151
+ comp,
152
+ props: [],
153
+ ...on ? { on } : {},
154
+ ...not?.length ? { not } : {},
155
+ ...trigram && { trigram },
156
+ }
157
+ ix.props.push(prop)
158
+ let physical = names.get(ix)
159
+ if (!physical) {
160
+ names.set(
161
+ ix,
162
+ physical = {
163
+ owner: owner + suffix,
164
+ columns: [],
165
+ },
166
+ )
167
+ }
168
+ physical.columns.push(stored == prop ? field(prop) : stored)
169
+ by.set(key, ix)
170
+ }
171
+ return [...by.values()]
172
+ }
173
+
174
+ let names = new WeakMap<Index, { owner: string; columns: string[] }>()
175
+ let ownerOf = (ix: Index) => names.get(ix)?.owner ?? ix.name
176
+
177
+ /** The columns handled by FTS, in the order the index declares them. */
178
+ export let columnsOf = (ix: Index): string[] =>
179
+ names.get(ix)?.columns ?? ix.props.map(field)
180
+
181
+ // The name of an index: `book` → `book_fts`.
182
+ export let indexName = (name: string): string => `${name}_fts`
183
+
184
+ // The name of a substring index: `content` → `content_trigram`.
185
+ export let gramName = (name: string): string => `${name}_trigram`
186
+
187
+ // The FTS5 table an index is: its word index, or its substring index.
188
+ export let tableOf = (ix: Index): string =>
189
+ ix.trigram ? gramName(ownerOf(ix)) : indexName(ownerOf(ix))
190
+
191
+ // The view an index reads its text through, where it needs one (`textName`).
192
+ export let viewOf = (ix: Index): string =>
193
+ textName(ix.trigram ? gramName(ownerOf(ix)) : ownerOf(ix))
194
+
195
+ // The substring index of the texts' tails past what a substring index holds,
196
+ // and the table listing the pieces it holds: `content_trigram_tail`,
197
+ // `content_trigram_piece`.
198
+ export let tailOf = (ix: Index): string => `${gramName(ownerOf(ix))}_tail`
199
+ export let piecesOf = (ix: Index): string => `${gramName(ownerOf(ix))}_piece`
200
+
201
+ // The name of the view that presents an index's columns as text: `doc` →
202
+ // `doc_text`. It is created for an index where at least one column has to be
203
+ // resolved (a `text` expression in the store's @yaks/sql `Derived`: @yaks/blob
204
+ // keeps a body's address, not its prose), and for every index read on behalf
205
+ // of another component, which reads its text through a join; an index whose
206
+ // columns hold their own text mirrors the component table itself.
207
+ export let textName = (name: string): string => `${name}_text`
package/lexicon.js ADDED
@@ -0,0 +1,71 @@
1
+ // Whether a store could match some words, said without asking the store.
2
+ //
3
+ // A search over many stores asks each one, and the asking is most of what it
4
+ // costs: every store wakes, searches and answers, and the slowest answers for
5
+ // all of them. A store's lexicon is what it would need to say "nothing here":
6
+ // the first few letters of every word its indexes hold. A word whose first
7
+ // letters are not in it matches no row there, since a word matches the words
8
+ // it begins (./term.ts), so the store can be left asleep.
9
+ //
10
+ // It is a superset by construction, never exact: a store only ever adds to its
11
+ // lexicon, a deleted row leaves its words behind, and four letters stand for
12
+ // every word they begin. A lexicon that admits too much costs a store asked
13
+ // for nothing; one that admits too little loses a hit, so every rounding here
14
+ // errs towards admitting.
15
+ //
16
+ // Text is folded before it is split, and the same way for what a store holds
17
+ // and what is asked: lower case, marks taken off. That is coarser than FTS5's
18
+ // own folding, so two words FTS5 reads as one are one here too.
19
+ import { split } from "./term.js";
20
+ /** How many letters of a word a lexicon keeps. */ export let PREFIX = 4;
21
+ let TOKEN = /[\p{L}\p{N}\p{Co}]+/gu;
22
+ let folded = (text)=>text.normalize('NFD').replace(/\p{M}+/gu, '').toLowerCase();
23
+ /**
24
+ * The lexicon entries a text adds: each of its words, folded and cut to
25
+ * {@link PREFIX} letters, once each.
26
+ *
27
+ * ```ts
28
+ * import { assertEquals } from '@std/assert'
29
+ * assertEquals(lexemes('Crème brûlée, crème caramel'), ['crem', 'brul', 'cara'])
30
+ * ```
31
+ */ export let lexemes = (text)=>[
32
+ ...new Set(folded(text).match(TOKEN)?.map((t)=>t.slice(0, PREFIX)))
33
+ ];
34
+ /**
35
+ * Two lexicons as one, sorted, which is the order {@link admits} reads.
36
+ *
37
+ * ```ts
38
+ * import { assertEquals } from '@std/assert'
39
+ * assertEquals(joined(['soup'], ['crem', 'soup']), ['crem', 'soup'])
40
+ * ```
41
+ */ export let joined = (a, b)=>[
42
+ ...new Set([
43
+ ...a,
44
+ ...b
45
+ ])
46
+ ].sort();
47
+ // Whether some entry of a sorted lexicon begins with `start`.
48
+ let begins = (lexicon, start)=>{
49
+ let lo = 0, hi = lexicon.length;
50
+ while(lo < hi){
51
+ let mid = lo + hi >> 1;
52
+ if (lexicon[mid] < start) lo = mid + 1;
53
+ else hi = mid;
54
+ }
55
+ return lexicon[lo]?.startsWith(start) ?? false;
56
+ };
57
+ /**
58
+ * Whether a store with this sorted lexicon could match every one of the
59
+ * words, as a search box's words match: each word, or each word of a quoted
60
+ * run, begins some word the store holds. False only when one of them cannot.
61
+ *
62
+ * ```ts
63
+ * import { assertEquals } from '@std/assert'
64
+ * let soups = joined(lexemes('Tomato soup'), [])
65
+ * assertEquals(admits(soups, 'tom'), true)
66
+ * assertEquals(admits(soups, 'tomatoes soup'), true)
67
+ * assertEquals(admits(soups, 'soup bread'), false)
68
+ * assertEquals(admits(soups, '"tomato soup"'), true)
69
+ * ```
70
+ */ export let admits = (lexicon, words)=>split(words).every((word)=>(folded(word).match(TOKEN) ?? []).every((t)=>begins(lexicon, t.slice(0, PREFIX))));
71
+ //# sourceMappingURL=lexicon.js.map
package/lexicon.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lexicon.js","sources":["./lexicon.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,2EAA2E;AAC3E,6EAA6E;AAC7E,0DAA0D;AAC1D,EAAE;AACF,+EAA+E;AAC/E,6EAA6E;AAC7E,4EAA4E;AAC5E,8EAA8E;AAC9E,0BAA0B;AAC1B,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,gEAAgE;AAEhE,SAAS,KAAK,oBAAmB;AAEjC,gDAAgD,GAChD,OAAO,IAAI,SAAS,EAAC;AAErB,IAAI,QAAQ;AAEZ,IAAI,SAAS,CAAC,OACZ,KAAK,SAAS,CAAC,OAAO,OAAO,CAAC,YAAY,IAAI,WAAW;AAE3D;;;;;;;;CAQC,GACD,OAAO,IAAI,UAAU,CAAC,OAA2B;OAC5C,IAAI,IAAI,OAAO,MAAM,KAAK,CAAC,QAAQ,IAAI,CAAC,IAAM,EAAE,KAAK,CAAC,GAAG;GAC7D,CAAA;AAED;;;;;;;CAOC,GACD,OAAO,IAAI,SAAS,CAAC,GAAsB,IACzC;OAAI,IAAI,IAAI;SAAI;SAAM;KAAE;GAAE,CAAC,IAAI,GAAE;AAEnC,8DAA8D;AAC9D,IAAI,SAAS,CAAC,SAA4B;EACxC,IAAI,KAAK,GAAG,KAAK,QAAQ,MAAM;EAC/B,MAAO,KAAK,GAAI;IACd,IAAI,MAAM,AAAC,KAAK,MAAO;IACvB,IAAI,OAAO,CAAC,IAAI,GAAG,OAAO,KAAK,MAAM;SAChC,KAAK;EACZ;EACA,OAAO,OAAO,CAAC,GAAG,EAAE,WAAW,UAAU;AAC3C;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,IAAI,SAAS,CAAC,SAA4B,QAC/C,MAAM,OAAO,KAAK,CAAC,CAAC,OAClB,CAAC,OAAO,MAAM,KAAK,CAAC,UAAU,EAAE,EAAE,KAAK,CAAC,CAAC,IACvC,OAAO,SAAS,EAAE,KAAK,CAAC,GAAG,WAE9B"}
package/lexicon.ts ADDED
@@ -0,0 +1,84 @@
1
+ // Whether a store could match some words, said without asking the store.
2
+ //
3
+ // A search over many stores asks each one, and the asking is most of what it
4
+ // costs: every store wakes, searches and answers, and the slowest answers for
5
+ // all of them. A store's lexicon is what it would need to say "nothing here":
6
+ // the first few letters of every word its indexes hold. A word whose first
7
+ // letters are not in it matches no row there, since a word matches the words
8
+ // it begins (./term.ts), so the store can be left asleep.
9
+ //
10
+ // It is a superset by construction, never exact: a store only ever adds to its
11
+ // lexicon, a deleted row leaves its words behind, and four letters stand for
12
+ // every word they begin. A lexicon that admits too much costs a store asked
13
+ // for nothing; one that admits too little loses a hit, so every rounding here
14
+ // errs towards admitting.
15
+ //
16
+ // Text is folded before it is split, and the same way for what a store holds
17
+ // and what is asked: lower case, marks taken off. That is coarser than FTS5's
18
+ // own folding, so two words FTS5 reads as one are one here too.
19
+
20
+ import { split } from './term.js'
21
+
22
+ /** How many letters of a word a lexicon keeps. */
23
+ export let PREFIX = 4
24
+
25
+ let TOKEN = /[\p{L}\p{N}\p{Co}]+/gu
26
+
27
+ let folded = (text: string) =>
28
+ text.normalize('NFD').replace(/\p{M}+/gu, '').toLowerCase()
29
+
30
+ /**
31
+ * The lexicon entries a text adds: each of its words, folded and cut to
32
+ * {@link PREFIX} letters, once each.
33
+ *
34
+ * ```ts
35
+ * import { assertEquals } from '@std/assert'
36
+ * assertEquals(lexemes('Crème brûlée, crème caramel'), ['crem', 'brul', 'cara'])
37
+ * ```
38
+ */
39
+ export let lexemes = (text: string): string[] => [
40
+ ...new Set(folded(text).match(TOKEN)?.map((t) => t.slice(0, PREFIX))),
41
+ ]
42
+
43
+ /**
44
+ * Two lexicons as one, sorted, which is the order {@link admits} reads.
45
+ *
46
+ * ```ts
47
+ * import { assertEquals } from '@std/assert'
48
+ * assertEquals(joined(['soup'], ['crem', 'soup']), ['crem', 'soup'])
49
+ * ```
50
+ */
51
+ export let joined = (a: readonly string[], b: readonly string[]): string[] =>
52
+ [...new Set([...a, ...b])].sort()
53
+
54
+ // Whether some entry of a sorted lexicon begins with `start`.
55
+ let begins = (lexicon: readonly string[], start: string) => {
56
+ let lo = 0, hi = lexicon.length
57
+ while (lo < hi) {
58
+ let mid = (lo + hi) >> 1
59
+ if (lexicon[mid] < start) lo = mid + 1
60
+ else hi = mid
61
+ }
62
+ return lexicon[lo]?.startsWith(start) ?? false
63
+ }
64
+
65
+ /**
66
+ * Whether a store with this sorted lexicon could match every one of the
67
+ * words, as a search box's words match: each word, or each word of a quoted
68
+ * run, begins some word the store holds. False only when one of them cannot.
69
+ *
70
+ * ```ts
71
+ * import { assertEquals } from '@std/assert'
72
+ * let soups = joined(lexemes('Tomato soup'), [])
73
+ * assertEquals(admits(soups, 'tom'), true)
74
+ * assertEquals(admits(soups, 'tomatoes soup'), true)
75
+ * assertEquals(admits(soups, 'soup bread'), false)
76
+ * assertEquals(admits(soups, '"tomato soup"'), true)
77
+ * ```
78
+ */
79
+ export let admits = (lexicon: readonly string[], words: string): boolean =>
80
+ split(words).every((word) =>
81
+ (folded(word).match(TOKEN) ?? []).every((t) =>
82
+ begins(lexicon, t.slice(0, PREFIX))
83
+ )
84
+ )
package/mod.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @yaks/fts — full-text search over a yaks graph, on any text property.
3
+ *
4
+ * Search is not limited to a single "document" component. A vocabulary declares
5
+ * components, and some of their properties hold prose — a book's title, a
6
+ * review's paragraph, a shop's own description. Each such property is marked
7
+ * `"search": true` in the vocabulary; this package indexes every marked
8
+ * property and searches all of them at once.
9
+ *
10
+ * It is four small pieces, each usable on its own:
11
+ *
12
+ * - {@link fields} reads the searchable properties off a
13
+ * {@link https://jsr.io/@yaks/vocab | @yaks/vocab} schema — the ones marked
14
+ * `"search": true`;
15
+ * - {@link schema} returns the SQL that creates the SQLite FTS5 indexes and the
16
+ * triggers that keep them in step with the component tables;
17
+ * - {@link search} — the {@link https://jsr.io/@yaks/sql | @yaks/sql} extension
18
+ * — makes a bare word in a query compile to an FTS5 `match`, so words and
19
+ * filters mix in one query: `hobbit .book.price<20`;
20
+ * - {@link find} ranks the matches and marks each one for display.
21
+ *
22
+ * ```ts
23
+ * import { loadVocab } from '@yaks/vocab'
24
+ * import { graph } from '@yaks/graph'
25
+ * import { storage } from '@yaks/sqlite'
26
+ * import { open } from '@yaks/sqlite/db'
27
+ * import { fields, find, schema, search } from '@yaks/fts'
28
+ * import { compile } from '@yaks/sql'
29
+ * import { parse } from '@yaks/query'
30
+ *
31
+ * let title = { type: 'string', search: true }
32
+ * let price = { type: 'number' }
33
+ * let shop = loadVocab([{
34
+ * $defs: { book: { component: true, properties: { title, price } } },
35
+ * }])
36
+ * let db = open(':memory:')
37
+ * let store = storage(db, shop)
38
+ * for (let stmt of store.ddl()) db.query(stmt)
39
+ *
40
+ * let text = fields(shop) // the properties the vocabulary marks searchable
41
+ * for (let stmt of schema(text)) db.query(stmt)
42
+ * graph({ storage: store, vocab: shop }).apply([
43
+ * { entity: { eid: 'book-1' }, book: { title: 'The Hobbit', price: 12 } },
44
+ * ])
45
+ *
46
+ * // which books match, with the rest of the query still filtering
47
+ * let matched = db.query(
48
+ * compile(parse('hobbit .book.price<20'), shop, { extend: [search(text)] }),
49
+ * )
50
+ *
51
+ * // and which come first, with a snippet marking each match
52
+ * let ranked = find(db, text, 'hobbit')
53
+ * ```
54
+ *
55
+ * It assumes the storage layout that @yaks/sql's SQLite dialect reads and
56
+ * {@link https://jsr.io/@yaks/sqlite | @yaks/sqlite} creates: an `entity` table
57
+ * of integer ids, one table per component keyed by an `entity` owner column,
58
+ * and a `tombstone` table listing deleted entities. For nearest-meaning results
59
+ * alongside these literal matches, pair it with `@yaks/embedding`.
60
+ *
61
+ * @module
62
+ */ export * from "./fields.js";
63
+ export * from "./term.js";
64
+ export * from "./ddl.js";
65
+ export * from "./compile.js";
66
+ export * from "./search.js";
67
+ export * from "./lexicon.js";
68
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6DC,GAED,4BAA2B;AAC3B,0BAAyB;AACzB,yBAAwB;AACxB,6BAA4B;AAC5B,4BAA2B;AAC3B,6BAA4B"}