-
Notifications
You must be signed in to change notification settings - Fork 144
/
Copy pathMiniSearch.test.js
1957 lines (1649 loc) · 77.3 KB
/
MiniSearch.test.js
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-env jest */
import MiniSearch from './MiniSearch'
describe('MiniSearch', () => {
describe('constructor', () => {
it('throws error if fields option is missing', () => {
expect(() => new MiniSearch()).toThrow('MiniSearch: option "fields" must be provided')
})
it('initializes the attributes', () => {
const options = { fields: ['title', 'text'] }
const ms = new MiniSearch(options)
expect(ms._documentCount).toEqual(0)
expect(ms._fieldIds).toEqual({ title: 0, text: 1 })
expect(ms._documentIds.size).toEqual(0)
expect(ms._fieldLength.size).toEqual(0)
expect(ms._avgFieldLength.length).toEqual(0)
expect(ms._options).toMatchObject(options)
})
})
describe('add', () => {
it('adds the document to the index', () => {
const ms = new MiniSearch({ fields: ['text'] })
ms.add({ id: 1, text: 'Nel mezzo del cammin di nostra vita' })
expect(ms.documentCount).toEqual(1)
})
it('does not throw error if a field is missing', () => {
const ms = new MiniSearch({ fields: ['title', 'text'] })
ms.add({ id: 1, text: 'Nel mezzo del cammin di nostra vita' })
expect(ms.documentCount).toEqual(1)
})
it('throws error if the document does not have the ID field', () => {
const ms = new MiniSearch({ idField: 'foo', fields: ['title', 'text'] })
expect(() => {
ms.add({ text: 'I do not have an ID' })
}).toThrowError('MiniSearch: document does not have ID field "foo"')
})
it('throws error on duplicate ID', () => {
const ms = new MiniSearch({ idField: 'foo', fields: ['title', 'text'] })
ms.add({ foo: 'abc', text: 'Something' })
expect(() => {
ms.add({ foo: 'abc', text: 'I have a duplicate ID' })
}).toThrowError('MiniSearch: duplicate ID abc')
})
it('extracts the ID field using extractField', () => {
const extractField = (document, fieldName) => {
if (fieldName === 'id') { return document.id.value }
return MiniSearch.getDefault('extractField')(document, fieldName)
}
const ms = new MiniSearch({ fields: ['text'], extractField })
ms.add({ id: { value: 123 }, text: 'Nel mezzo del cammin di nostra vita' })
const results = ms.search('vita')
expect(results[0].id).toEqual(123)
})
it('rejects falsy terms', () => {
const processTerm = term => term === 'foo' ? null : term
const ms = new MiniSearch({ fields: ['title', 'text'], processTerm })
expect(() => {
ms.add({ id: 123, text: 'foo bar' })
}).not.toThrowError()
})
it('turns the field to string before tokenization', () => {
const tokenize = jest.fn(x => x.split(/\W+/))
const ms = new MiniSearch({ fields: ['id', 'tags', 'isBlinky'], tokenize })
expect(() => {
ms.add({ id: 123, tags: ['foo', 'bar'], isBlinky: false })
ms.add({ id: 321, isBlinky: true })
}).not.toThrowError()
expect(tokenize).toHaveBeenCalledWith('123', 'id')
expect(tokenize).toHaveBeenCalledWith('foo,bar', 'tags')
expect(tokenize).toHaveBeenCalledWith('false', 'isBlinky')
expect(tokenize).toHaveBeenCalledWith('321', 'id')
expect(tokenize).toHaveBeenCalledWith('true', 'isBlinky')
})
it('passes document and field name to the field extractor', () => {
const extractField = jest.fn((document, fieldName) => {
if (fieldName === 'pubDate') {
return document[fieldName] && document[fieldName].toLocaleDateString('it-IT')
}
return fieldName.split('.').reduce((doc, key) => doc && doc[key], document)
})
const tokenize = jest.fn(string => string.split(/\W+/))
const ms = new MiniSearch({
fields: ['title', 'pubDate', 'author.name'],
storeFields: ['category'],
extractField,
tokenize
})
const document = {
id: 1,
title: 'Divina Commedia',
pubDate: new Date(1320, 0, 1),
author: { name: 'Dante Alighieri' },
category: 'poetry'
}
ms.add(document)
expect(extractField).toHaveBeenCalledWith(document, 'title')
expect(extractField).toHaveBeenCalledWith(document, 'pubDate')
expect(extractField).toHaveBeenCalledWith(document, 'author.name')
expect(extractField).toHaveBeenCalledWith(document, 'category')
expect(tokenize).toHaveBeenCalledWith(document.title, 'title')
expect(tokenize).toHaveBeenCalledWith(document.pubDate.toLocaleDateString('it-IT'), 'pubDate')
expect(tokenize).toHaveBeenCalledWith(document.author.name, 'author.name')
expect(tokenize).not.toHaveBeenCalledWith(document.category, 'category')
})
it('passes field value and name to tokenizer', () => {
const tokenize = jest.fn(string => string.split(/\W+/))
const ms = new MiniSearch({ fields: ['text', 'title'], tokenize })
const document = { id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' }
ms.add(document)
expect(tokenize).toHaveBeenCalledWith(document.text, 'text')
expect(tokenize).toHaveBeenCalledWith(document.title, 'title')
})
it('passes field value and name to term processor', () => {
const processTerm = jest.fn(term => term.toLowerCase())
const ms = new MiniSearch({ fields: ['text', 'title'], processTerm })
const document = { id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' }
ms.add(document)
document.text.split(/\W+/).forEach(term => {
expect(processTerm).toHaveBeenCalledWith(term, 'text')
})
document.title.split(/\W+/).forEach(term => {
expect(processTerm).toHaveBeenCalledWith(term, 'title')
})
})
it('allows processTerm to expand a single term into several terms', () => {
const processTerm = (string) => string === 'foobar' ? ['foo', 'bar'] : string
const ms = new MiniSearch({ fields: ['title', 'text'], processTerm })
expect(() => {
ms.add({ id: 123, text: 'foobar' })
}).not.toThrowError()
expect(ms.search('bar')).toHaveLength(1)
})
})
describe('remove', () => {
const documents = [
{ id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita ... cammin' },
{ id: 2, title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como' },
{ id: 3, title: 'Vita Nova', text: 'In quella parte del libro della mia memoria ... cammin' }
]
let ms, _warn
beforeEach(() => {
ms = new MiniSearch({ fields: ['title', 'text'] })
ms.addAll(documents)
_warn = console.warn
console.warn = jest.fn()
})
afterEach(() => {
console.warn = _warn
})
it('removes the document from the index', () => {
expect(ms.documentCount).toEqual(3)
ms.remove(documents[0])
expect(ms.documentCount).toEqual(2)
expect(ms.search('commedia').length).toEqual(0)
expect(ms.search('vita').map(({ id }) => id)).toEqual([3])
expect(console.warn).not.toHaveBeenCalled()
})
it('cleans up all data of the deleted document', () => {
const otherDocument = { id: 4, title: 'Decameron', text: 'Umana cosa è aver compassione degli afflitti' }
const originalFieldLength = new Map(ms._fieldLength)
const originalAverageFieldLength = ms._avgFieldLength.slice()
ms.add(otherDocument)
ms.remove(otherDocument)
expect(ms.documentCount).toEqual(3)
expect(ms._fieldLength).toEqual(originalFieldLength)
expect(ms._avgFieldLength).toEqual(originalAverageFieldLength)
})
it('does not remove terms from other documents', () => {
ms.remove(documents[0])
expect(ms.search('cammin').length).toEqual(1)
})
it('removes re-added document', () => {
ms.remove(documents[0])
ms.add(documents[0])
ms.remove(documents[0])
expect(console.warn).not.toHaveBeenCalled()
})
it('removes documents when using a custom extractField', () => {
const extractField = (document, fieldName) => {
const path = fieldName.split('.')
return path.reduce((doc, key) => doc && doc[key], document)
}
const ms = new MiniSearch({ fields: ['text.value'], storeFields: ['id'], extractField })
const document = { id: 123, text: { value: 'Nel mezzo del cammin di nostra vita' } }
ms.add(document)
expect(() => {
ms.remove(document)
}).not.toThrowError()
expect(ms.search('vita')).toEqual([])
})
it('cleans up the index', () => {
const originalIdsSize = ms._documentIds.size
ms.remove(documents[0])
expect(ms._index.has('commedia')).toEqual(false)
expect(ms._documentIds.size).toEqual(originalIdsSize - 1)
expect(Array.from(ms._index.get('vita').keys())).toEqual([ms._fieldIds.title])
})
it('throws error if the document does not have the ID field', () => {
const ms = new MiniSearch({ idField: 'foo', fields: ['title', 'text'] })
expect(() => {
ms.remove({ text: 'I do not have an ID' })
}).toThrowError('MiniSearch: document does not have ID field "foo"')
})
it('extracts the ID field using extractField', () => {
const extractField = (document, fieldName) => {
if (fieldName === 'id') { return document.id.value }
return MiniSearch.getDefault('extractField')(document, fieldName)
}
const ms = new MiniSearch({ fields: ['text'], extractField })
const document = { id: { value: 123 }, text: 'Nel mezzo del cammin di nostra vita' }
ms.add(document)
expect(() => {
ms.remove(document)
}).not.toThrowError()
expect(ms.search('vita')).toEqual([])
})
it('does not crash when the document has field named like default properties of object', () => {
const ms = new MiniSearch({ fields: ['constructor'] })
const document = { id: 1 }
ms.add(document)
expect(() => {
ms.remove(document)
}).not.toThrowError()
})
it('does not reassign IDs', () => {
ms.remove(documents[0])
ms.add(documents[0])
expect(ms.search('commedia').map(result => result.id)).toEqual([documents[0].id])
expect(ms.search('nova').map(result => result.id)).toEqual([documents[documents.length - 1].id])
})
it('rejects falsy terms', () => {
const processTerm = term => term === 'foo' ? null : term
const ms = new MiniSearch({ fields: ['title', 'text'], processTerm })
const document = { id: 123, title: 'foo bar' }
ms.add(document)
expect(() => {
ms.remove(document)
}).not.toThrowError()
})
it('allows processTerm to expand a single term into several terms', () => {
const processTerm = (string) => string === 'foobar' ? ['foo', 'bar'] : string
const ms = new MiniSearch({ fields: ['title', 'text'], processTerm })
const document = { id: 123, title: 'foobar' }
ms.add(document)
expect(() => {
ms.remove(document)
}).not.toThrowError()
expect(ms.search('bar')).toHaveLength(0)
})
describe('when using custom per-field extraction/tokenizer/processing', () => {
const documents = [
{ id: 1, title: 'Divina Commedia', tags: 'dante,virgilio', author: { name: 'Dante Alighieri' } },
{ id: 2, title: 'I Promessi Sposi', tags: 'renzo,lucia', author: { name: 'Alessandro Manzoni' } },
{ id: 3, title: 'Vita Nova', author: { name: 'Dante Alighieri' } }
]
let ms, _warn
beforeEach(() => {
ms = new MiniSearch({
fields: ['title', 'tags', 'authorName'],
extractField: (doc, fieldName) => {
if (fieldName === 'authorName') {
return doc.author.name
} else {
return doc[fieldName]
}
},
tokenize: (field, fieldName) => {
if (fieldName === 'tags') {
return field.split(',')
} else {
return field.split(/\s+/)
}
},
processTerm: (term, fieldName) => {
if (fieldName === 'tags') {
return term.toUpperCase()
} else {
return term.toLowerCase()
}
}
})
ms.addAll(documents)
_warn = console.warn
console.warn = jest.fn()
})
afterEach(() => {
console.warn = _warn
})
it('removes the document from the index', () => {
expect(ms.documentCount).toEqual(3)
ms.remove(documents[0])
expect(ms.documentCount).toEqual(2)
expect(ms.search('commedia').length).toEqual(0)
expect(ms.search('vita').map(({ id }) => id)).toEqual([3])
expect(console.warn).not.toHaveBeenCalled()
})
})
describe('when the document was not in the index', () => {
it('throws an error', () => {
expect(() => ms.remove({ id: 99 }))
.toThrow('MiniSearch: cannot remove document with ID 99: it is not in the index')
})
})
describe('when the document has changed', () => {
it('warns of possible index corruption', () => {
expect(() => ms.remove({ id: 1, title: 'Divina Commedia cammin', text: 'something has changed' }))
.not.toThrow()
expect(console.warn).toHaveBeenCalledTimes(4)
;[
['cammin', 'title'],
['something', 'text'],
['has', 'text'],
['changed', 'text']
].forEach(([term, field], i) => {
expect(console.warn).toHaveBeenNthCalledWith(i + 1, `MiniSearch: document with ID 1 has changed before removal: term "${term}" was not present in field "${field}". Removing a document after it has changed can corrupt the index!`)
})
})
it('does not throw error if console.warn is undefined', () => {
console.warn = undefined
expect(() => ms.remove({ id: 1, title: 'Divina Commedia cammin', text: 'something has changed' }))
.not.toThrow()
})
it('calls the custom logger if given', () => {
const logger = jest.fn()
ms = new MiniSearch({ fields: ['title', 'text'], logger })
ms.addAll(documents)
ms.remove({ id: 1, title: 'Divina Commedia', text: 'something' })
expect(logger).toHaveBeenCalledWith('warn', 'MiniSearch: document with ID 1 has changed before removal: term "something" was not present in field "text". Removing a document after it has changed can corrupt the index!', 'version_conflict')
expect(console.warn).not.toHaveBeenCalled()
})
})
})
describe('removeAll', () => {
const documents = [
{ id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita ... cammin' },
{ id: 2, title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como' },
{ id: 3, title: 'Vita Nova', text: 'In quella parte del libro della mia memoria ... cammin' }
]
let ms, _warn
beforeEach(() => {
ms = new MiniSearch({ fields: ['title', 'text'] })
_warn = console.warn
console.warn = jest.fn()
})
afterEach(() => {
console.warn = _warn
})
it('removes all documents from the index if called with no argument', () => {
const empty = MiniSearch.loadJSON(JSON.stringify(ms), {
fields: ['title', 'text']
})
ms.addAll(documents)
expect(ms.documentCount).toEqual(3)
ms.removeAll()
expect(ms).toEqual(empty)
})
it('removes the given documents from the index', () => {
ms.addAll(documents)
expect(ms.documentCount).toEqual(3)
ms.removeAll([documents[0], documents[2]])
expect(ms.documentCount).toEqual(1)
expect(ms.search('commedia').length).toEqual(0)
expect(ms.search('vita').length).toEqual(0)
expect(ms.search('lago').length).toEqual(1)
})
it('raises an error if called with a falsey argument', () => {
ms.addAll(documents)
expect(() => { ms.removeAll(null) }).toThrowError()
expect(() => { ms.removeAll(undefined) }).toThrowError()
expect(() => { ms.removeAll(false) }).toThrowError()
expect(() => { ms.removeAll('') }).toThrowError()
expect(() => { ms.removeAll([]) }).not.toThrowError()
expect(ms.documentCount).toEqual(documents.length)
})
})
describe('discard', () => {
it('prevents a document from appearing in search results', () => {
const ms = new MiniSearch({ fields: ['text'] })
const documents = [
{ id: 1, text: 'Some interesting stuff' },
{ id: 2, text: 'Some more interesting stuff' }
]
ms.addAll(documents)
expect(ms.search('stuff').map((doc) => doc.id)).toEqual([1, 2])
expect([1, 2].map((id) => ms.has(id))).toEqual([true, true])
ms.discard(1)
expect(ms.search('stuff').map((doc) => doc.id)).toEqual([2])
expect([1, 2].map((id) => ms.has(id))).toEqual([false, true])
})
it('raises error if a document with the given ID does not exist', () => {
const ms = new MiniSearch({ fields: ['text'] })
expect(() => {
ms.discard(99)
}).toThrow('MiniSearch: cannot discard document with ID 99: it is not in the index')
})
it('adjusts internal data to account for the document being discarded', () => {
const ms = new MiniSearch({ fields: ['text'] })
const documents = [
{ id: 1, text: 'Some interesting stuff' },
{ id: 2, text: 'Some more interesting stuff' }
]
ms.addAll(documents)
const clone = MiniSearch.loadJSON(JSON.stringify(ms), {
fields: ['text']
})
ms.discard(1)
clone.remove({ id: 1, text: 'Some interesting stuff' })
expect(ms._idToShortId).toEqual(clone._idToShortId)
expect(ms._documentIds).toEqual(clone._documentIds)
expect(ms._fieldLength).toEqual(clone._fieldLength)
expect(ms._storedFields).toEqual(clone._storedFields)
expect(ms._avgFieldLength).toEqual(clone._avgFieldLength)
expect(ms._documentCount).toEqual(clone._documentCount)
expect(ms._dirtCount).toEqual(1)
})
it('allows adding a new version of the document afterwards', () => {
const ms = new MiniSearch({ fields: ['text'], storeFields: ['text'] })
const documents = [
{ id: 1, text: 'Some interesting stuff' },
{ id: 2, text: 'Some more interesting stuff' }
]
ms.addAll(documents)
ms.discard(1)
ms.add({ id: 1, text: 'Some new stuff' })
expect(ms.search('stuff').map((doc) => doc.id)).toEqual([1, 2])
expect(ms.search('new').map((doc) => doc.id)).toEqual([1])
ms.discard(1)
expect(ms.search('stuff').map((doc) => doc.id)).toEqual([2])
ms.add({ id: 1, text: 'Some newer stuff' })
expect(ms.search('stuff').map((doc) => doc.id)).toEqual([1, 2])
expect(ms.search('new').map((doc) => doc.id)).toEqual([])
expect(ms.search('newer').map((doc) => doc.id)).toEqual([1])
})
it('leaves the index in the same state as removal when all terms are searched at least once', () => {
const ms = new MiniSearch({ fields: ['text'], storeFields: ['text'] })
const document = { id: 1, text: 'Some stuff' }
ms.add(document)
const clone = MiniSearch.loadJSON(JSON.stringify(ms), {
fields: ['text'],
storeFields: ['text']
})
ms.discard(1)
clone.remove({ id: 1, text: 'Some stuff' })
expect(ms).not.toEqual(clone)
const results = ms.search('some stuff')
expect(ms._index).toEqual(clone._index)
// Results are the same after the first search
expect(ms.search('stuff')).toEqual(results)
})
it('triggers auto vacuum by default', () => {
const ms = new MiniSearch({ fields: ['text'] })
ms.add({ id: 1, text: 'Some stuff' })
ms._dirtCount = 1000
ms.discard(1)
expect(ms.isVacuuming).toEqual(true)
})
it('triggers auto vacuum when the threshold is met', () => {
const ms = new MiniSearch({
fields: ['text'],
autoVacuum: { minDirtCount: 2, minDirtFactor: 0, batchWait: 50, batchSize: 1 }
})
const documents = [
{ id: 1, text: 'Some stuff' },
{ id: 2, text: 'Some additional stuff' },
{ id: 3, text: 'Even more stuff' }
]
ms.addAll(documents)
expect(ms.isVacuuming).toEqual(false)
ms.discard(1)
expect(ms.isVacuuming).toEqual(false)
ms.discard(2)
expect(ms.isVacuuming).toEqual(true)
})
it('does not trigger auto vacuum if disabled', () => {
const ms = new MiniSearch({ fields: ['text'], autoVacuum: false })
const documents = [
{ id: 1, text: 'Some stuff' },
{ id: 2, text: 'Some additional stuff' }
]
ms.addAll(documents)
ms._dirtCount = 1000
ms.discard(1)
expect(ms.isVacuuming).toEqual(false)
})
it('applies default settings if autoVacuum is set to true', () => {
const ms = new MiniSearch({ fields: ['text'], autoVacuum: true })
const documents = [
{ id: 1, text: 'Some stuff' },
{ id: 2, text: 'Some additional stuff' }
]
ms.addAll(documents)
ms._dirtCount = 1000
ms.discard(1)
expect(ms.isVacuuming).toEqual(true)
})
it('applies default settings if options are set to null', async () => {
const ms = new MiniSearch({
fields: ['text'],
autoVacuum: { minDirtCount: null, minDirtFactor: null, batchWait: null, batchSize: null }
})
const documents = [
{ id: 1, text: 'Some stuff' },
{ id: 2, text: 'Some additional stuff' }
]
ms.addAll(documents)
ms._dirtCount = 1000
const x = ms.discard(1)
expect(ms.isVacuuming).toEqual(true)
await x
})
it('vacuums until under the dirt thresholds when called multiple times', async () => {
const minDirtCount = 2
const ms = new MiniSearch({
fields: ['text'],
autoVacuum: { minDirtCount, minDirtFactor: 0, batchSize: 1, batchWait: 10 }
})
const documents = []
for (let i = 0; i < 5; i++) {
documents.push({ id: i + 1, text: `Document number ${i}` })
}
ms.addAll(documents)
expect(ms._dirtCount).toEqual(0)
// Calling discard multiple times should start an auto-vacuum and enqueue
// another, so that the remaining dirt count afterwards is always below
// minDirtCount
documents.forEach((doc) => ms.discard(doc.id))
while (ms.isVacuuming) {
await ms._currentVacuum
}
expect(ms._dirtCount).toBeLessThan(minDirtCount)
})
it('does not perform unnecessary vacuuming when called multiple times', async () => {
const minDirtCount = 2
const ms = new MiniSearch({
fields: ['text'],
autoVacuum: { minDirtCount, minDirtFactor: 0, batchSize: 1, batchWait: 10 }
})
const documents = [
{ id: 1, text: 'Document one' },
{ id: 2, text: 'Document two' },
{ id: 3, text: 'Document three' }
]
ms.addAll(documents)
// Calling discard multiple times will start an auto-vacuum and enqueue
// another, subject to minDirtCount/minDirtFactor conditions. The last one
// should be a no-op, as the remaining dirt count after the first auto
// vacuum would be 1, which is below minDirtCount
documents.forEach((doc) => ms.discard(doc.id))
while (ms.isVacuuming) {
await ms._currentVacuum
}
expect(ms._dirtCount).toBe(1)
})
it('enqueued vacuum runs without conditions if a manual vacuum was called while enqueued', async () => {
const minDirtCount = 2
const ms = new MiniSearch({
fields: ['text'],
autoVacuum: { minDirtCount, minDirtFactor: 0, batchSize: 1, batchWait: 10 }
})
const documents = [
{ id: 1, text: 'Document one' },
{ id: 2, text: 'Document two' },
{ id: 3, text: 'Document three' }
]
ms.addAll(documents)
// Calling discard multiple times will start an auto-vacuum and enqueue
// another, subject to minDirtCount/minDirtFactor conditions. The last one
// would be a no-op, as the remaining dirt count after the first auto
// vacuum would be 1, which is below minDirtCount
documents.forEach((doc) => ms.discard(doc.id))
// But before the enqueued vacuum is ran, we invoke a manual vacuum with
// no conditions, so it should run even with a dirt count below
// minDirtCount
ms.vacuum()
while (ms.isVacuuming) {
await ms._currentVacuum
}
expect(ms._dirtCount).toBe(0)
})
})
describe('discardAll', () => {
it('prevents the documents from appearing in search results', () => {
const ms = new MiniSearch({ fields: ['text'] })
const documents = [
{ id: 1, text: 'Some interesting stuff' },
{ id: 2, text: 'Some more interesting stuff' },
{ id: 3, text: 'Some even more interesting stuff' }
]
ms.addAll(documents)
expect(ms.search('stuff').map((doc) => doc.id)).toEqual([1, 2, 3])
expect([1, 2, 3].map((id) => ms.has(id))).toEqual([true, true, true])
ms.discardAll([1, 3])
expect(ms.search('stuff').map((doc) => doc.id)).toEqual([2])
expect([1, 2, 3].map((id) => ms.has(id))).toEqual([false, true, false])
})
it('only triggers at most a single auto vacuum at the end', () => {
const ms = new MiniSearch({ fields: ['text'], autoVacuum: { minDirtCount: 3, minDirtFactor: 0, batchSize: 1, batchWait: 10 } })
const documents = []
for (let i = 1; i <= 10; i++) {
documents.push({ id: i, text: `Document ${i}` })
}
ms.addAll(documents)
ms.discardAll([1, 2])
expect(ms.isVacuuming).toEqual(false)
ms.discardAll([3, 4, 5, 6, 7, 8, 9, 10])
expect(ms.isVacuuming).toEqual(true)
expect(ms._enqueuedVacuum).toEqual(null)
})
it('does not change auto vacuum settings in case of errors', () => {
const ms = new MiniSearch({ fields: ['text'], autoVacuum: { minDirtCount: 1, minDirtFactor: 0, batchSize: 1, batchWait: 10 } })
ms.add({ id: 1, text: 'Some stuff' })
expect(() => { ms.discardAll([3]) }).toThrow()
expect(ms.isVacuuming).toEqual(false)
ms.discardAll([1])
expect(ms.isVacuuming).toEqual(true)
})
})
describe('replace', () => {
it('replaces an existing document with a new version', () => {
const ms = new MiniSearch({ fields: ['text'] })
const documents = [
{ id: 1, text: 'Some quite interesting stuff' },
{ id: 2, text: 'Some more interesting stuff' }
]
ms.addAll(documents)
expect(ms.search('stuff').map((doc) => doc.id)).toEqual([1, 2])
expect(ms.search('quite').map((doc) => doc.id)).toEqual([1])
expect(ms.search('even').map((doc) => doc.id)).toEqual([])
ms.replace({ id: 1, text: 'Some even more interesting stuff' })
expect(ms.search('stuff').map((doc) => doc.id)).toEqual([2, 1])
expect(ms.search('quite').map((doc) => doc.id)).toEqual([])
expect(ms.search('even').map((doc) => doc.id)).toEqual([1])
})
it('raises error if a document with the given ID does not exist', () => {
const ms = new MiniSearch({ fields: ['text'] })
expect(() => {
ms.replace({ id: 1, text: 'Some stuff' })
}).toThrow('MiniSearch: cannot discard document with ID 1: it is not in the index')
})
})
describe('vacuum', () => {
it('cleans up discarded documents from the index', async () => {
const ms = new MiniSearch({ fields: ['text'], storeFields: ['text'] })
const documents = [
{ id: 1, text: 'Some stuff' },
{ id: 2, text: 'Some additional stuff' }
]
ms.addAll(documents)
const clone = MiniSearch.loadJSON(JSON.stringify(ms), {
fields: ['text'],
storeFields: ['text']
})
ms.discard(1)
ms.discard(2)
clone.remove({ id: 1, text: 'Some stuff' })
clone.remove({ id: 2, text: 'Some additional stuff' })
expect(ms).not.toEqual(clone)
await ms.vacuum({ batchSize: 1 })
expect(ms).toEqual(clone)
expect(ms.isVacuuming).toEqual(false)
})
it('schedules a second vacuum right after the current one completes, if one is ongoing', async () => {
const ms = new MiniSearch({ fields: ['text'] })
const empty = MiniSearch.loadJSON(JSON.stringify(ms), {
fields: ['text']
})
const documents = [
{ id: 1, text: 'Some stuff' },
{ id: 2, text: 'Some additional stuff' }
]
ms.addAll(documents)
ms.discard(1)
ms.discard(2)
ms.add({ id: 3, text: 'Even more stuff' })
ms.vacuum({ batchSize: 1, batchWait: 50 })
ms.discard(3)
await ms.vacuum()
expect(ms._index).toEqual(empty._index)
expect(ms.isVacuuming).toEqual(false)
})
it('does not enqueue more than one vacuum on top of the ongoing one', async () => {
const ms = new MiniSearch({ fields: ['text'] })
const documents = [
{ id: 1, text: 'Some stuff' },
{ id: 2, text: 'Some additional stuff' }
]
ms.addAll(documents)
ms.discard(1)
ms.discard(2)
const a = ms.vacuum({ batchSize: 1, batchWait: 50 })
const b = ms.vacuum()
const c = ms.vacuum()
expect(a).not.toBe(b)
expect(b).toBe(c)
expect(ms.isVacuuming).toEqual(true)
await c
expect(ms.isVacuuming).toEqual(false)
})
it('allows batch size to be bigger than the term count', async () => {
const ms = new MiniSearch({ fields: ['text'] })
const documents = [
{ id: 1, text: 'Some stuff' },
{ id: 2, text: 'Some additional stuff' }
]
ms.addAll(documents)
await ms.vacuum({ batchSize: ms.termCount + 1 })
expect(ms.isVacuuming).toEqual(false)
})
})
describe('addAll', () => {
it('adds all the documents to the index', () => {
const ms = new MiniSearch({ fields: ['text'] })
const documents = [
{ id: 1, text: 'Nel mezzo del cammin di nostra vita' },
{ id: 2, text: 'Mi ritrovai per una selva oscura' }
]
ms.addAll(documents)
expect(ms.documentCount).toEqual(documents.length)
})
})
describe('addAllAsync', () => {
it('adds all the documents to the index', () => {
const ms = new MiniSearch({ fields: ['text'] })
const documents = [
{ id: 1, text: 'Nel mezzo' },
{ id: 2, text: 'del cammin' },
{ id: 3, text: 'di nostra vita' },
{ id: 4, text: 'Mi ritrovai' },
{ id: 5, text: 'per una' },
{ id: 6, text: 'selva oscura' },
{ id: 7, text: 'ché la' },
{ id: 8, text: 'diritta via' },
{ id: 9, text: 'era smarrita' },
{ id: 10, text: 'ahi quanto' },
{ id: 11, text: 'a dir' },
{ id: 12, text: 'qual era' },
{ id: 13, text: 'è cosa dura' }
]
return ms.addAllAsync(documents).then(() => {
expect(ms.documentCount).toEqual(documents.length)
})
})
it('accepts a chunkSize option', () => {
const ms = new MiniSearch({ fields: ['text'] })
const documents = [
{ id: 1, text: 'Nel mezzo' },
{ id: 2, text: 'del cammin' },
{ id: 3, text: 'di nostra vita' },
{ id: 4, text: 'Mi ritrovai' },
{ id: 5, text: 'per una' },
{ id: 6, text: 'selva oscura' },
{ id: 7, text: 'ché la' },
{ id: 8, text: 'diritta via' },
{ id: 9, text: 'era smarrita' },
{ id: 10, text: 'ahi quanto' },
{ id: 11, text: 'a dir' },
{ id: 12, text: 'qual era' },
{ id: 13, text: 'è cosa dura' }
]
return ms.addAllAsync(documents, { chunkSize: 3 }).then(() => {
expect(ms.documentCount).toEqual(documents.length)
})
})
})
describe('has', () => {
it('returns true if a document with the given ID was added to the index, false otherwise', () => {
const documents = [
{ id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' },
{ id: 2, title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como' }
]
const ms = new MiniSearch({ fields: ['title', 'text'] })
ms.addAll(documents)
expect(ms.has(1)).toEqual(true)
expect(ms.has(2)).toEqual(true)
expect(ms.has(3)).toEqual(false)
ms.remove({ id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' })
ms.discard(2)
expect(ms.has(1)).toEqual(false)
expect(ms.has(2)).toEqual(false)
})
it('works well with custom ID fields', () => {
const documents = [
{ uid: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' },
{ uid: 2, title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como' }
]
const ms = new MiniSearch({ fields: ['title', 'text'], idField: 'uid' })
ms.addAll(documents)
expect(ms.has(1)).toEqual(true)
expect(ms.has(2)).toEqual(true)
expect(ms.has(3)).toEqual(false)
ms.remove({ uid: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' })
ms.discard(2)
expect(ms.has(1)).toEqual(false)
expect(ms.has(2)).toEqual(false)
})
})
describe('getStoredFields', () => {
it('returns the stored fields for the given document ID, or undefined if the document is not in the index', () => {
const documents = [
{ id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' },
{ id: 2, title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como' }
]
const ms = new MiniSearch({ fields: ['title', 'text'], storeFields: ['title', 'text'] })
ms.addAll(documents)
expect(ms.getStoredFields(1)).toEqual({ title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' })
expect(ms.getStoredFields(2)).toEqual({ title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como' })
expect(ms.getStoredFields(3)).toBe(undefined)
ms.discard(1)
expect(ms.getStoredFields(1)).toBe(undefined)
})
})
describe('search', () => {
const documents = [
{ id: 1, title: 'Divina Commedia', text: 'Nel mezzo del cammin di nostra vita' },
{ id: 2, title: 'I Promessi Sposi', text: 'Quel ramo del lago di Como', lang: 'it', category: 'fiction' },
{ id: 3, title: 'Vita Nova', text: 'In quella parte del libro della mia memoria', category: 'poetry' }
]
const ms = new MiniSearch({ fields: ['title', 'text'], storeFields: ['lang', 'category'] })
ms.addAll(documents)
it('returns scored results', () => {
const results = ms.search('vita')
expect(results.length).toBeGreaterThan(0)
expect(results.map(({ id }) => id).sort()).toEqual([1, 3])
expect(results[0].score).toBeGreaterThanOrEqual(results[1].score)
})
it('returns stored fields in the results', () => {
const results = ms.search('del')
expect(results.length).toBeGreaterThan(0)
expect(results.map(({ lang }) => lang).sort()).toEqual(['it', undefined, undefined])
expect(results.map(({ category }) => category).sort()).toEqual(['fiction', 'poetry', undefined])
})
it('returns empty array if there is no match', () => {
const results = ms.search('paguro')
expect(results).toEqual([])
})
it('returns empty array for empty search', () => {
const results = ms.search('')