/
lyra.ts
273 lines (222 loc) 路 6.68 KB
/
lyra.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import type { queueAsPromised } from "fastq";
import { nanoid } from "nanoid";
import * as fastq from "fastq";
import { Trie } from "./prefix-tree/trie";
import * as ERRORS from "./errors";
import { tokenize } from "./tokenizer";
import { formatNanoseconds, getNanosecondsTime } from "./utils";
import { Language, SUPPORTED_LANGUAGES } from "./stemmer";
export type PropertyType = "string" | "number" | "boolean";
export type PropertiesSchema = {
[key: string]: PropertyType | PropertiesSchema;
};
export type LyraProperties = {
schema: PropertiesSchema;
defaultLanguage?: Language;
};
export type LyraDocs = Map<string, object>;
export type SearchParams = {
term: string;
properties?: "*" | string[];
limit?: number;
offset?: number;
};
type LyraIndex = Map<string, Trie>;
type QueueDocParams = {
id: string;
doc: object;
language: Language;
};
type SearchResult = Promise<{
count: number;
hits: object[];
elapsed: string;
}>;
export class Lyra {
private defaultLanguage: Language = "english";
private schema: PropertiesSchema;
private docs: LyraDocs = new Map();
private index: LyraIndex = new Map();
private queue: queueAsPromised<QueueDocParams> = fastq.promise(
this,
this._insert,
1
);
constructor(properties: LyraProperties) {
const defaultLanguage =
(properties?.defaultLanguage?.toLowerCase() as Language) ?? "english";
if (!SUPPORTED_LANGUAGES.includes(defaultLanguage)) {
throw ERRORS.LANGUAGE_NOT_SUPPORTED(defaultLanguage);
}
this.defaultLanguage = defaultLanguage;
this.schema = properties.schema;
this.buildIndex(properties.schema);
}
private buildIndex(schema: PropertiesSchema) {
for (const prop in schema) {
const propType = typeof prop;
if (propType === "string") {
this.index.set(prop, new Trie());
} else if (propType === "object") {
// @todo nested properties will be supported with the next versions
//this.buildIndex(prop as unknown as PropertiesSchema);
throw ERRORS.UNSUPPORTED_NESTED_PROPERTIES();
} else {
throw ERRORS.INVALID_SCHEMA_TYPE(propType);
}
}
}
async search(params: SearchParams): SearchResult {
const tokens = tokenize(params.term).values();
const indices = this.getIndices(params.properties);
const { limit = 10, offset = 0 } = params;
const results: object[] = new Array({ length: limit });
let totalResults = 0;
const timeStart = getNanosecondsTime();
let i = 0;
let j = 0;
for (const token of tokens) {
for (const index of indices) {
const documentIDs = await this.getDocumentIDsFromSearch({
...params,
index: index,
term: token,
});
totalResults += documentIDs.size;
if (i >= limit) {
break;
}
if (documentIDs.size) {
for (const id of documentIDs) {
if (j < offset) {
j++;
continue;
}
if (i >= limit) {
break;
}
const fullDoc = this.docs.get(id);
results[i] = { id, ...fullDoc };
i++;
}
}
}
}
return {
elapsed: formatNanoseconds(getNanosecondsTime() - timeStart),
hits: results,
count: totalResults,
};
}
private getIndices(indices: SearchParams["properties"]): string[] {
const knownIndices = [...this.index.keys()];
if (!indices) {
return knownIndices;
}
if (typeof indices === "string") {
if (indices === "*") {
return knownIndices;
} else {
throw ERRORS.INVALID_PROPERTY(indices, knownIndices);
}
}
for (const index of indices as string[]) {
if (!knownIndices.includes(index)) {
throw ERRORS.INVALID_PROPERTY(index, knownIndices);
}
}
return indices as string[];
}
async delete(docID: string): Promise<boolean> {
if (!this.docs.has(docID)) {
throw ERRORS.DOC_ID_DOES_NOT_EXISTS(docID);
}
const document = this.docs.get(docID)!;
for (const key in document) {
const idx = this.index.get(key)!;
const tokens = tokenize((document as any)[key]);
for (const token of tokens) {
if (idx.removeDocByWord(token, docID)) {
throw `Unable to remove document "${docID}" from index "${key}" on word "${token}".`;
}
}
}
this.docs.delete(docID);
return true;
}
private async getDocumentIDsFromSearch(
params: SearchParams & { index: string }
): Promise<Set<string>> {
const idx = this.index.get(params.index);
const searchResult = idx?.find(params.term);
const ids = new Set<string>();
for (const key in searchResult) {
for (const id of (searchResult as any)[key]) {
ids.add(id);
}
}
return ids;
}
public async insert(
doc: object,
language: Language = this.defaultLanguage
): Promise<{ id: string }> {
const id = nanoid();
if (!SUPPORTED_LANGUAGES.includes(language)) {
throw ERRORS.LANGUAGE_NOT_SUPPORTED(language);
}
if (!(await this.checkInsertDocSchema(doc))) {
throw ERRORS.INVALID_DOC_SCHEMA(this.schema, doc);
}
await this.queue.push({
id,
doc,
language,
});
return { id };
}
private async _insert({ doc, id, language }: QueueDocParams): Promise<void> {
const index = this.index;
this.docs.set(id, doc);
function recursiveTrieInsertion(doc: object) {
for (const key in doc) {
if (typeof (doc as any)[key] === "object") {
throw ERRORS.UNSUPPORTED_NESTED_PROPERTIES();
// @todo nested properties will be supported with the nexrt versions
// recursiveTrieInsertion((doc as any)[key]);
} else if (typeof (doc as any)[key] === "string") {
const requestedTrie = index.get(key);
const tokens = tokenize((doc as any)[key], language);
for (const token of tokens) {
requestedTrie?.insert(token, id);
}
}
}
}
recursiveTrieInsertion(doc);
}
private async checkInsertDocSchema(
doc: QueueDocParams["doc"]
): Promise<boolean> {
function recursiveCheck(
newDoc: QueueDocParams["doc"],
schema: PropertiesSchema
): boolean {
for (const key in newDoc) {
if (!(key in schema)) {
return false;
}
const propType = typeof (newDoc as any)[key];
if (propType === "object") {
recursiveCheck((newDoc as any)[key], schema);
} else {
if (typeof (newDoc as any)[key] !== schema[key]) {
return false;
}
}
}
return true;
}
return recursiveCheck(doc, this.schema);
}
}