forked from krisk/Fuse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
601 lines (524 loc) · 16.9 KB
/
Copy pathindex.ts
File metadata and controls
601 lines (524 loc) · 16.9 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import { isArray, isDefined, isString, isNumber } from '../helpers/typeGuards'
import KeyStore from '../tools/KeyStore'
import FuseIndex, { createIndex } from '../tools/FuseIndex'
import {
LogicalOperator,
parse,
type ParsedNode,
type ParsedLeaf,
type ParsedOperator
} from './queryParser'
import { createSearcher } from './register'
import Config from './config'
import computeScore, { computeScoreSingle } from './computeScore'
import MaxHeap from '../tools/MaxHeap'
import format from './format'
import * as ErrorMsg from './errorMessages'
import { createAnalyzer } from '../search/token/analyzer'
import { MAX_MASK_TERMS } from '../search/token'
import {
buildInvertedIndex,
addToInvertedIndex,
removeAndShiftInvertedIndex
} from '../search/token/InvertedIndex'
import type { InvertedIndexData } from '../search/token/InvertedIndex'
import type {
Searcher,
SearchResult,
InternalResult,
MatchScore,
IFuseOptions,
FuseSearchOptions,
FuseResult,
Expression,
KeyObject,
SubRecord
} from '../types'
interface HeapSearchOptions {
heap?: MaxHeap
ignoreFieldNorm?: boolean
}
export default class Fuse<T> {
options: Required<IFuseOptions<T>>
_keyStore: KeyStore
_docs: T[]
_myIndex: FuseIndex<T>
_invertedIndex: InvertedIndexData | null
_lastQuery: string | null
_lastSearcher: Searcher | null
// Statics are assigned in entry.ts
static version: string
static createIndex: typeof createIndex
static parseIndex: typeof import('../tools/FuseIndex').parseIndex
static config: typeof Config
static parseQuery: typeof parse
static use: (...plugins: any[]) => void
static match: (
pattern: string,
text: string,
options?: IFuseOptions<any>
) => SearchResult
constructor(
docs: ReadonlyArray<T>,
options?: IFuseOptions<T>,
index?: FuseIndex<T>
) {
this.options = { ...Config, ...options } as Required<IFuseOptions<T>>
if (
this.options.useExtendedSearch &&
!process.env.EXTENDED_SEARCH_ENABLED
) {
throw new Error(ErrorMsg.EXTENDED_SEARCH_UNAVAILABLE)
}
if (this.options.useTokenSearch && !process.env.TOKEN_SEARCH_ENABLED) {
throw new Error(ErrorMsg.TOKEN_SEARCH_UNAVAILABLE)
}
this._keyStore = new KeyStore(this.options.keys)
this._docs = docs as T[]
this._myIndex = null as any
this._invertedIndex = null
this.setCollection(docs, index)
this._lastQuery = null
this._lastSearcher = null
}
_getSearcher(query: string): Searcher {
if (this._lastQuery === query) {
return this._lastSearcher!
}
const opts = this._invertedIndex
? { ...this.options, _invertedIndex: this._invertedIndex }
: this.options
const searcher = createSearcher(query, opts)
this._lastQuery = query
this._lastSearcher = searcher
return searcher
}
setCollection(docs: ReadonlyArray<T>, index?: FuseIndex<T>): void {
this._docs = docs as T[]
if (index && !(index instanceof FuseIndex)) {
throw new Error(ErrorMsg.INCORRECT_INDEX_TYPE)
}
this._myIndex =
index ||
createIndex(this.options.keys, this._docs, {
getFn: this.options.getFn,
fieldNormWeight: this.options.fieldNormWeight
})
if (this.options.useTokenSearch) {
const analyzer = createAnalyzer({
isCaseSensitive: this.options.isCaseSensitive,
ignoreDiacritics: this.options.ignoreDiacritics,
tokenize: this.options.tokenize
})
this._invertedIndex = buildInvertedIndex(
this._myIndex.records,
this._myIndex.keys.length,
analyzer
)
}
this._invalidateSearcherCache()
}
add(doc: T): void {
if (!isDefined(doc)) {
return
}
this._docs.push(doc)
const record = this._myIndex.add(doc, this._docs.length - 1)
// Skip inverted-index bookkeeping when no record was appended (blank
// strings produce null). The previous code read `records[records.length-1]`
// unconditionally, which would re-ingest the previous doc on `add("")`.
if (this._invertedIndex && record) {
const analyzer = createAnalyzer({
isCaseSensitive: this.options.isCaseSensitive,
ignoreDiacritics: this.options.ignoreDiacritics,
tokenize: this.options.tokenize
})
addToInvertedIndex(
this._invertedIndex,
record,
this._myIndex.keys.length,
analyzer
)
}
this._invalidateSearcherCache()
}
remove(predicate: (doc: T, idx: number) => boolean = () => false): T[] {
const results: T[] = []
const indicesToRemove: number[] = []
for (let i = 0, len = this._docs.length; i < len; i += 1) {
if (predicate(this._docs[i], i)) {
results.push(this._docs[i])
indicesToRemove.push(i)
}
}
if (indicesToRemove.length) {
if (this._invertedIndex) {
removeAndShiftInvertedIndex(this._invertedIndex, indicesToRemove)
}
// Filter docs in a single pass instead of reverse-splicing
const toRemove = new Set(indicesToRemove)
this._docs = this._docs.filter((_, i) => !toRemove.has(i))
this._myIndex.removeAll(indicesToRemove)
this._invalidateSearcherCache()
}
return results
}
removeAt(idx: number): T {
// Validate before any mutation. The previous code spliced `_docs` first
// and let FuseIndex.removeAt throw afterward — partial-state on invalid
// input. Atomic now.
if (!Number.isInteger(idx) || idx < 0 || idx >= this._docs.length) {
throw new Error(ErrorMsg.INVALID_DOC_INDEX)
}
if (this._invertedIndex) {
removeAndShiftInvertedIndex(this._invertedIndex, [idx])
}
const doc = this._docs.splice(idx, 1)[0]
this._myIndex.removeAt(idx)
this._invalidateSearcherCache()
return doc
}
_invalidateSearcherCache(): void {
this._lastQuery = null
this._lastSearcher = null
}
getIndex(): FuseIndex<T> {
return this._myIndex
}
search(
query: string | Expression,
options?: FuseSearchOptions
): FuseResult<T>[] {
const { limit = -1 } = options || {}
const {
includeMatches,
includeScore,
shouldSort,
sortFn,
ignoreFieldNorm
} = this.options
// Empty string query returns all docs (useful for search UIs)
if (isString(query) && !query.trim()) {
let docs: FuseResult<T>[] = this._docs.map((item, idx) => ({
item,
refIndex: idx
}))
if (isNumber(limit) && limit > -1) {
docs = docs.slice(0, limit)
}
return docs
}
const useHeap = isNumber(limit) && limit > 0 && isString(query)
let results: InternalResult[]
if (useHeap) {
const heap = new MaxHeap(limit)
if (isString(this._docs[0])) {
this._searchStringList(query as string, { heap, ignoreFieldNorm })
} else {
this._searchObjectList(query as string, { heap, ignoreFieldNorm })
}
results = heap.extractSorted(sortFn as any)
} else {
results = isString(query)
? isString(this._docs[0])
? this._searchStringList(query)!
: this._searchObjectList(query)!
: this._searchLogical(query as Expression)
computeScore(results, { ignoreFieldNorm })
if (shouldSort) {
results.sort(sortFn as any)
}
if (isNumber(limit) && limit > -1) {
results = results.slice(0, limit)
}
}
return format(results, this._docs, {
includeMatches,
includeScore
})
}
_searchStringList(
query: string,
{ heap, ignoreFieldNorm }: HeapSearchOptions = {}
): InternalResult[] | null {
const searcher = this._getSearcher(query)
const requireAllTokens =
this.options.useTokenSearch && this.options.tokenMatch === 'all'
const { records } = this._myIndex
const results: InternalResult[] | null = heap ? null : []
// Iterate over every string in the index
records.forEach(({ v: text, i: idx, n: norm }) => {
if (!isDefined(text)) {
return
}
const searchResult = searcher.searchIn(text)
if (searchResult.isMatch) {
const match: MatchScore = {
score: searchResult.score,
value: text,
norm: norm!,
indices: searchResult.indices
}
if (requireAllTokens) {
match.matchedMask = searchResult.matchedMask
match.matchedTerms = searchResult.matchedTerms
match.termCount = searchResult.termCount
}
const matches = [match]
// Record-level AND gate (token search `tokenMatch: 'all'`), applied
// before heap insertion so `limit` returns the same top-N as unlimited.
if (!requireAllTokens || this._coversAllTokens(matches)) {
const result: InternalResult = { item: text, idx, matches }
if (heap) {
result.score = computeScoreSingle(result.matches, {
ignoreFieldNorm
})
if (heap.shouldInsert(result.score)) {
heap.insert(result)
}
} else {
results!.push(result)
}
}
}
})
return results
}
_searchLogical(query: Expression): InternalResult[] {
if (!process.env.LOGICAL_SEARCH_ENABLED) {
throw new Error(ErrorMsg.LOGICAL_SEARCH_UNAVAILABLE)
}
const expression = parse(query, this.options)
const evaluate = (
node: ParsedNode,
item: any,
idx: number
): InternalResult[] => {
if (!('children' in node)) {
const { keyId, searcher } = node as ParsedLeaf
let matches: MatchScore[]
if (keyId === null) {
// Keyless entry: search across all keys
matches = []
this._myIndex.keys.forEach((key, keyIndex) => {
matches.push(
...this._findMatches({
key,
value: item[keyIndex],
searcher: searcher!
})
)
})
} else {
matches = this._findMatches({
key: this._keyStore.get(keyId),
value: this._myIndex.getValueForItemAtKeyId(item, keyId),
searcher: searcher!
})
}
if (matches && matches.length) {
return [
{
idx,
item,
matches
}
]
}
return []
}
const { children, operator } = node as ParsedOperator
const res: InternalResult[] = []
for (let i = 0, len = children.length; i < len; i += 1) {
const child = children[i]
const result = evaluate(child, item, idx)
if (result.length) {
res.push(...result)
} else if (operator === LogicalOperator.AND) {
return []
}
}
return res
}
const records = this._myIndex.records
const resultMap = new Map<number, InternalResult>()
const results: InternalResult[] = []
records.forEach(({ $: item, i: idx }) => {
if (isDefined(item)) {
const expResults = evaluate(expression, item, idx)
if (expResults.length) {
// Dedupe when adding
if (!resultMap.has(idx)) {
resultMap.set(idx, { idx, item, matches: [] })
results.push(resultMap.get(idx)!)
}
expResults.forEach(({ matches }) => {
resultMap.get(idx)!.matches.push(...matches)
})
}
}
})
return results
}
// When a search involves inverse patterns (e.g. !Syrup), the aggregation
// across keys switches from "ANY key matches" to "ALL keys must match."
// This is signaled by hasInverse on the SearchResult from ExtendedSearch.
//
// For mixed patterns like "^hello !Syrup", a key failure is ambiguous —
// it could be the positive or inverse term that failed. In that case we
// conservatively exclude the item, which is strictly better than the old
// behavior of including it. See: https://github.com/krisk/Fuse/issues/712
_searchObjectList(
query: string,
{ heap, ignoreFieldNorm }: HeapSearchOptions = {}
): InternalResult[] | null {
const searcher = this._getSearcher(query)
const requireAllTokens =
this.options.useTokenSearch && this.options.tokenMatch === 'all'
const { records } = this._myIndex
// Use KeyStore's normalised keys so that key.weight reflects the
// weight normalisation performed by KeyStore (weights sum to 1).
// Previously this used this._myIndex.keys whose weights are the raw
// user-supplied values; with extreme weights (e.g. 100) the exponent
// Math.pow(Number.EPSILON, weight * norm) underflows to 0, and scores
// become inconsistent with _searchLogical which already reads from
// this._keyStore.get(keyId).
const keys = this._keyStore.keys()
const results: InternalResult[] | null = heap ? null : []
// List is Array<Object>
records.forEach(({ $: item, i: idx }) => {
if (!isDefined(item)) {
return
}
const matches: MatchScore[] = []
let anyKeyFailed = false
let hasInverse = false
// Iterate over every key (i.e, path), and fetch the value at that key
keys.forEach((key, keyIndex) => {
const keyMatches = this._findMatches({
key,
value: item[keyIndex],
searcher
})
if (keyMatches.length) {
matches.push(...keyMatches)
if (keyMatches[0].hasInverse) {
hasInverse = true
}
} else {
anyKeyFailed = true
}
})
// If the search involves inverse patterns, ALL keys must match
if (hasInverse && anyKeyFailed) {
return
}
// Record-level AND gate (token search `tokenMatch: 'all'`): every query
// term must be covered across the record's field/array-element matches.
// Applied before heap insertion so `limit` returns the same top-N.
if (
matches.length &&
(!requireAllTokens || this._coversAllTokens(matches))
) {
const result: InternalResult = { idx, item, matches }
if (heap) {
result.score = computeScoreSingle(result.matches, { ignoreFieldNorm })
if (heap.shouldInsert(result.score)) {
heap.insert(result)
}
} else {
results!.push(result)
}
}
})
return results
}
_findMatches({
key,
value,
searcher
}: {
key: KeyObject | null
value: SubRecord | SubRecord[] | undefined
searcher: Searcher
}): MatchScore[] {
if (!isDefined(value)) {
return []
}
const matches: MatchScore[] = []
if (isArray(value)) {
value.forEach(({ v: text, i: idx, n: norm }: SubRecord) => {
if (!isDefined(text)) {
return
}
const searchResult = searcher.searchIn(text)
if (searchResult.isMatch) {
const match: MatchScore = {
score: searchResult.score,
key,
value: text,
idx,
norm,
indices: searchResult.indices,
hasInverse: searchResult.hasInverse
}
// Carry token-search AND coverage only when present, so the default
// (non-token / 'any') MatchScore keeps its original object shape.
if (searchResult.termCount !== undefined) {
match.matchedMask = searchResult.matchedMask
match.matchedTerms = searchResult.matchedTerms
match.termCount = searchResult.termCount
}
matches.push(match)
}
})
} else {
const { v: text, n: norm } = value
const searchResult = searcher.searchIn(text)
if (searchResult.isMatch) {
const match: MatchScore = {
score: searchResult.score,
key,
value: text,
norm,
indices: searchResult.indices,
hasInverse: searchResult.hasInverse
}
if (searchResult.termCount !== undefined) {
match.matchedMask = searchResult.matchedMask
match.matchedTerms = searchResult.matchedTerms
match.termCount = searchResult.termCount
}
matches.push(match)
}
}
return matches
}
// Record-level AND gate for token search (`tokenMatch: 'all'`). Returns true
// unless the matched terms across ALL of a record's field/array-element
// matches fail to cover every query term. `termCount` is only set by
// TokenSearch in 'all' mode, so non-token / 'any' searches always pass.
_coversAllTokens(matches: MatchScore[]): boolean {
const termCount = matches.length ? matches[0].termCount : undefined
if (termCount === undefined) {
return true
}
if (termCount <= MAX_MASK_TERMS) {
let coverage = 0
for (let i = 0; i < matches.length; i++) {
coverage |= matches[i].matchedMask || 0
}
return coverage === 2 ** termCount - 1
}
const coverage = new Set<number>()
for (let i = 0; i < matches.length; i++) {
const terms = matches[i].matchedTerms
if (terms) {
for (const t of terms) {
coverage.add(t)
}
}
}
return coverage.size === termCount
}
}