forked from lucaong/minisearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiniSearch.test.js
1193 lines (1026 loc) · 49.5 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('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('1/1/1320', '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')
})
})
})
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()
})
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()
})
})
})
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', () => {
expect(() => { ms.removeAll(null) }).toThrowError()
expect(() => { ms.removeAll(undefined) }).toThrowError()
expect(() => { ms.removeAll(false) }).toThrowError()
expect(() => { ms.removeAll([]) }).not.toThrowError()
})
})
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('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('')
expect(results).toEqual([])
})
it('returns empty results for terms that are not in the index', () => {
let results
expect(() => {
results = ms.search('sottomarino aeroplano')
}).not.toThrowError()
expect(results.length).toEqual(0)
})
it('boosts fields', () => {
const results = ms.search('vita', { boost: { title: 2 } })
expect(results.map(({ id }) => id)).toEqual([3, 1])
expect(results[0].score).toBeGreaterThan(results[1].score)
})
it('computes a meaningful score when fields are named liked default properties of object', () => {
const ms = new MiniSearch({ fields: ['constructor'] })
ms.add({ id: 1, constructor: 'something' })
ms.add({ id: 1, constructor: 'something else' })
const results = ms.search('something')
results.forEach((result) => {
expect(Number.isFinite(result.score)).toBe(true)
})
})
it('searches in the given fields', () => {
const results = ms.search('vita', { fields: ['title'] })
expect(results).toHaveLength(1)
expect(results[0].id).toEqual(3)
})
it('combines results with OR by default', () => {
const results = ms.search('cammin como sottomarino')
expect(results.length).toEqual(2)
expect(results.map(({ id }) => id)).toEqual([2, 1])
})
it('combines results with AND if combineWith is AND', () => {
const results = ms.search('vita cammin', { combineWith: 'AND' })
expect(results.length).toEqual(1)
expect(results.map(({ id }) => id)).toEqual([1])
expect(ms.search('vita sottomarino', { combineWith: 'AND' }).length).toEqual(0)
expect(ms.search('sottomarino vita', { combineWith: 'AND' }).length).toEqual(0)
})
it('combines results with AND_NOT if combineWith is AND_NOT', () => {
const results = ms.search('vita cammin', { combineWith: 'AND_NOT' })
expect(results.length).toEqual(1)
expect(results.map(({ id }) => id)).toEqual([3])
expect(ms.search('vita sottomarino', { combineWith: 'AND_NOT' }).length).toEqual(2)
expect(ms.search('sottomarino vita', { combineWith: 'AND_NOT' }).length).toEqual(0)
})
it('returns empty results for empty search', () => {
expect(ms.search('')).toEqual([])
expect(ms.search('', { combineWith: 'OR' })).toEqual([])
expect(ms.search('', { combineWith: 'AND' })).toEqual([])
expect(ms.search('', { combineWith: 'AND_NOT' })).toEqual([])
})
it('executes fuzzy search', () => {
const results = ms.search('camin memory', { fuzzy: 2 })
expect(results.length).toEqual(2)
expect(results.map(({ id }) => id)).toEqual([1, 3])
})
it('executes fuzzy search with maximum fuzziness', () => {
const results = ms.search('comedia', { fuzzy: 0.6, maxFuzzy: 3 })
expect(results.length).toEqual(1)
expect(results.map(({ id }) => id)).toEqual([1])
})
it('executes prefix search', () => {
const results = ms.search('que', { prefix: true })
expect(results.length).toEqual(2)
expect(results.map(({ id }) => id)).toEqual([2, 3])
})
it('combines prefix search and fuzzy search', () => {
const results = ms.search('cammino quel', { fuzzy: 0.25, prefix: true })
expect(results.length).toEqual(3)
expect(results.map(({ id }) => id)).toEqual([2, 1, 3])
})
it('assigns weights to prefix matches and fuzzy matches', () => {
const exact = ms.search('cammino quel')
expect(exact.map(({ id }) => id)).toEqual([2])
const prefixLast = ms.search('cammino quel', { fuzzy: true, prefix: true, weights: { prefix: 0.1 } })
expect(prefixLast.map(({ id }) => id)).toEqual([2, 1, 3])
expect(prefixLast[0].score).toEqual(exact[0].score)
const fuzzyLast = ms.search('cammino quel', { fuzzy: true, prefix: true, weights: { fuzzy: 0.1 } })
expect(fuzzyLast.map(({ id }) => id)).toEqual([2, 3, 1])
expect(fuzzyLast[0].score).toEqual(exact[0].score)
})
it('assigns weight lower than exact match to a match that is both a prefix and fuzzy match', () => {
const ms = new MiniSearch({ fields: ['text'] })
const documents = [
{ id: 1, text: 'Poi che la gente poverella crebbe' },
{ id: 2, text: 'Deus, venerunt gentes' }
]
ms.addAll(documents)
expect(ms.documentCount).toEqual(documents.length)
const exact = ms.search('gente')
const combined = ms.search('gente', { fuzzy: 0.2, prefix: true })
expect(combined.map(({ id }) => id)).toEqual([1, 2])
expect(combined[0].score).toEqual(exact[0].score)
expect(combined[1].match.gentes).toEqual(['text'])
})
it('accepts a function to compute fuzzy and prefix options from term', () => {
const fuzzy = jest.fn(term => term.length > 4 ? 2 : false)
const prefix = jest.fn(term => term.length > 4)
const results = ms.search('quel comedia', { fuzzy, prefix })
expect(fuzzy).toHaveBeenNthCalledWith(1, 'quel', 0, ['quel', 'comedia'])
expect(fuzzy).toHaveBeenNthCalledWith(2, 'comedia', 1, ['quel', 'comedia'])
expect(prefix).toHaveBeenNthCalledWith(1, 'quel', 0, ['quel', 'comedia'])
expect(prefix).toHaveBeenNthCalledWith(2, 'comedia', 1, ['quel', 'comedia'])
expect(results.length).toEqual(2)
expect(results.map(({ id }) => id)).toEqual([2, 1])
})
it('boosts documents by calling boostDocument with document ID and term', () => {
const query = 'divina commedia'
const boostFactor = 1.234
const boostDocument = jest.fn((id, term) => boostFactor)
const resultsWithoutBoost = ms.search(query)
const results = ms.search(query, { boostDocument })
expect(boostDocument).toHaveBeenCalledWith(1, 'divina')
expect(boostDocument).toHaveBeenCalledWith(1, 'commedia')
expect(results[0].score).toBeCloseTo(resultsWithoutBoost[0].score * boostFactor)
})
it('skips document if boostDocument returns a falsy value', () => {
const query = 'vita'
const boostDocument = jest.fn((id, term) => id === 3 ? null : 1)
const resultsWithoutBoost = ms.search(query)
const results = ms.search(query, { boostDocument })
expect(resultsWithoutBoost.map(({ id }) => id)).toContain(3)
expect(results.map(({ id }) => id)).not.toContain(3)
})
it('uses a specific search-time tokenizer if specified', () => {
const tokenize = (string) => string.split('X')
const results = ms.search('divinaXcommedia', { tokenize })
expect(results.length).toBeGreaterThan(0)
expect(results.map(({ id }) => id).sort()).toEqual([1])
})
it('uses a specific search-time term processing function if specified', () => {
const processTerm = (string) => string.replace(/1/g, 'i').replace(/4/g, 'a').toLowerCase()
const results = ms.search('d1v1n4', { processTerm })
expect(results.length).toBeGreaterThan(0)
expect(results.map(({ id }) => id).sort()).toEqual([1])
})
it('rejects falsy terms', () => {
const processTerm = (term) => term === 'quel' ? null : term
const results = ms.search('quel commedia', { processTerm })
expect(results.length).toBeGreaterThan(0)
expect(results.map(({ id }) => id).sort()).toEqual([1])
})
it('allows custom filtering of results on the basis of stored fields', () => {
const results = ms.search('del', {
filter: ({ category }) => category === 'poetry'
})
expect(results.length).toBe(1)
expect(results.every(({ category }) => category === 'poetry')).toBe(true)
})
describe('when passing a query tree', () => {
it('searches according to the given combination', () => {
const results = ms.search({
combineWith: 'OR',
queries: [
{
combineWith: 'AND',
queries: ['vita', 'cammin']
},
'como sottomarino',
{
combineWith: 'AND',
queries: ['nova', 'pappagallo']
}
]
})
expect(results.length).toEqual(2)
expect(results.map(({ id }) => id)).toEqual([1, 2])
})
it('uses the given options for each subquery, cascading them properly', () => {
const results = ms.search({
combineWith: 'OR',
fuzzy: true,
queries: [
{
prefix: true,
fields: ['title'],
queries: ['vit']
},
{
combineWith: 'AND',
queries: ['bago', 'coomo']
}
],
weights: {
fuzzy: 0.2,
prefix: 0.75
}
})
expect(results.length).toEqual(2)
expect(results.map(({ id }) => id)).toEqual([3, 2])
})
})
describe('match data', () => {
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' },
{ id: 3, title: 'Vita Nova', text: 'In quella parte del libro della mia memoria ... vita' }
]
const ms = new MiniSearch({ fields: ['title', 'text'] })
ms.addAll(documents)
it('reports information about matched terms and fields', () => {
const results = ms.search('vita nova')
expect(results.length).toBeGreaterThan(0)
expect(results.map(({ match }) => match)).toEqual([
{ vita: ['title', 'text'], nova: ['title'] },
{ vita: ['text'] }
])
expect(results.map(({ terms }) => terms)).toEqual([
['vita', 'nova'],
['vita']
])
})
it('reports correct info when combining terms with AND', () => {
const results = ms.search('vita nova', { combineWith: 'AND' })
expect(results.map(({ match }) => match)).toEqual([
{ vita: ['title', 'text'], nova: ['title'] }
])
expect(results.map(({ terms }) => terms)).toEqual([
['vita', 'nova']
])
})
it('reports correct info for fuzzy and prefix queries', () => {
const results = ms.search('vi nuova', { fuzzy: 0.2, prefix: true })
expect(results.map(({ match }) => match)).toEqual([
{ vita: ['title', 'text'], nova: ['title'] },
{ vita: ['text'] }
])
expect(results.map(({ terms }) => terms)).toEqual([
['vita', 'nova'],
['vita']
])
})
it('reports correct info for many fuzzy and prefix queries', () => {
const results = ms.search('vi nuova m de', { fuzzy: 0.2, prefix: true })
expect(results.map(({ match }) => match)).toEqual([
{ del: ['text'], della: ['text'], memoria: ['text'], mia: ['text'], vita: ['title', 'text'], nova: ['title'] },
{ del: ['text'], mezzo: ['text'], vita: ['text'] },
{ del: ['text'] }
])
expect(results.map(({ terms }) => terms)).toEqual([
['vita', 'nova', 'memoria', 'mia', 'della', 'del'],
['vita', 'mezzo', 'del'],
['del']
])
})
it('passes only the query to tokenize', () => {
const tokenize = jest.fn(string => string.split(/\W+/))
const ms = new MiniSearch({ fields: ['text', 'title'], searchOptions: { tokenize } })
const query = 'some search query'
ms.search(query)
expect(tokenize).toHaveBeenCalledWith(query)
})
it('passes only the term to processTerm', () => {
const processTerm = jest.fn(term => term.toLowerCase())
const ms = new MiniSearch({ fields: ['text', 'title'], searchOptions: { processTerm } })
const query = 'some search query'
ms.search(query)
query.split(/\W+/).forEach(term => {
expect(processTerm).toHaveBeenCalledWith(term)
})
})
it('does not break when special properties of object are used as a term', () => {
const specialWords = ['constructor', 'hasOwnProperty', 'isPrototypeOf']
const ms = new MiniSearch({ fields: ['text'] })
const processTerm = MiniSearch.getDefault('processTerm')
ms.add({ id: 1, text: specialWords.join(' ') })
specialWords.forEach((word) => {
expect(() => { ms.search(word) }).not.toThrowError()
const results = ms.search(word)
expect(results[0].id).toEqual(1)
expect(results[0].match[processTerm(word)]).toEqual(['text'])
})
})
})
describe('movie ranking set', () => {
const ms = new MiniSearch({
fields: ['title', 'description'],
storeFields: ['title']
})
ms.add({
id: 'tt1487931',
title: 'Khumba',
description: 'When half-striped zebra Khumba is blamed for the lack of rain by the rest of his insular, superstitious herd, he embarks on a daring quest to earn his stripes. In his search for the legendary waterhole in which the first zebras got their stripes, Khumba meets a quirky range of characters and teams up with an unlikely duo: overprotective wildebeest Mama V and Bradley, a self-obsessed, flamboyant ostrich. But before he can reunite with his herd, Khumba must confront Phango, a sadistic leopard who controls the waterholes and terrorizes all the animals in the Great Karoo. It\'s not all black-and-white in this colorful adventure with a difference.'
})
ms.add({
id: 'tt8737608',
title: 'Rams',
description: 'A feud between two sheep farmers.'
})
ms.add({
id: 'tt0983983',
title: 'Shaun the Sheep',
description: 'Shaun is a cheeky and mischievous sheep at Mossy Bottom farm who\'s the leader of the flock and always plays slapstick jokes, pranks and causes trouble especially on Farmer X and his grumpy guide dog, Bitzer.'
})
ms.add({
id: 'tt5174284',
title: 'Shaun the Sheep: The Farmer\'s Llamas',
description: 'At the annual County Fair, three peculiar llamas catch the eye of Shaun, who tricks the unsuspecting Farmer into buying them. At first, it\'s all fun and games at Mossy Bottom Farm until the trio of unruly animals shows their true colours, wreaking havoc before everyone\'s eyes. Now, it\'s up to Bitzer and Shaun to come up with a winning strategy, if they want to reclaim the farm. Can they rid the once-peaceful ranch of the troublemakers?'
})
ms.add({
id: 'tt0102926',
title: 'The Silence of the Lambs',
description: 'F.B.I. trainee Clarice Starling (Jodie Foster) works hard to advance her career, while trying to hide or put behind her West Virginia roots, of which if some knew, would automatically classify her as being backward or white trash. After graduation, she aspires to work in the agency\'s Behavioral Science Unit under the leadership of Jack Crawford (Scott Glenn). While she is still a trainee, Crawford asks her to question Dr. Hannibal Lecter (Sir Anthony Hopkins), a psychiatrist imprisoned, thus far, for eight years in maximum security isolation for being a serial killer who cannibalized his victims. Clarice is able to figure out the assignment is to pick Lecter\'s brains to help them solve another serial murder case, that of someone coined by the media as "Buffalo Bill" (Ted Levine), who has so far killed five victims, all located in the eastern U.S., all young women, who are slightly overweight (especially around the hips), all who were drowned in natural bodies of water, and all who were stripped of large swaths of skin. She also figures that Crawford chose her, as a woman, to be able to trigger some emotional response from Lecter. After speaking to Lecter for the first time, she realizes that everything with him will be a psychological game, with her often having to read between the very cryptic lines he provides. She has to decide how much she will play along, as his request in return for talking to him is to expose herself emotionally to him. The case takes a more dire turn when a sixth victim is discovered, this one from who they are able to retrieve a key piece of evidence, if Lecter is being forthright as to its meaning. A potential seventh victim is high profile Catherine Martin (Brooke Smith), the daughter of Senator Ruth Martin (Diane Baker), which places greater scrutiny on the case as they search for a hopefully still alive Catherine. Who may factor into what happens is Dr. Frederick Chilton (Anthony Heald), the warden at the prison, an opportunist who sees the higher profile with Catherine, meaning a higher profile for himself if he can insert himself successfully into the proceedings.'
})
ms.add({
id: 'tt0395479',
title: 'Boundin\'',
description: 'In the not too distant past, a lamb lives in the desert plateau just below the snow line. He is proud of how bright and shiny his coat of wool is, so much so that it makes him want to dance, which in turn makes all the other creatures around him also want to dance. His life changes when one spring day he is captured, his wool shorn, and thrown back out onto the plateau all naked and pink. But a bounding jackalope who wanders by makes the lamb look at life a little differently in seeing that there is always something exciting in life to bound about.'
})
ms.add({
id: 'tt9812474',
title: 'Lamb',
description: 'Haunted by the indelible mark of loss and silent grief, sad-eyed María and her taciturn husband, Ingvar, seek solace in back-breaking work and the demanding schedule at their sheep farm in the remote, harsh, wind-swept landscapes of mountainous Iceland. Then, with their relationship hanging on by a thread, something unexplainable happens, and just like that, happiness blesses the couple\'s grim household once more. Now, as a painful ending gives birth to a new beginning, Ingvar\'s troubled brother, Pétur, arrives at the farmhouse, threatening María and Ingvar\'s delicate, newfound bliss. But, nature\'s gifts demand sacrifice. How far are ecstatic María and Ingvar willing to go in the name of love?'
})
ms.add({
id: 'tt0306646',
title: 'Ringing Bell',
description: 'A baby lamb named Chirin is living an idyllic life on a farm with many other sheep. Chirin is very adventurous and tends to get lost, so he wears a bell around his neck so that his mother can always find him. His mother warns Chirin that he must never venture beyond the fence surrounding the farm, because a huge black wolf lives in the mountains and loves to eat sheep. Chirin is too young and naive to take the advice to heart, until one night the wolf enters the barn and is prepared to kill Chirin, but at the last moment the lamb\'s mother throws herself in the way and is killed instead. The wolf leaves, and Chirin is horrified to see his mother\'s body. Unable to understand why his mother was killed, he becomes very angry and swears that he will go into the mountains and kill the wolf.'
})
ms.add({
id: 'tt1212022',
title: 'The Lion of Judah',
description: 'Follow the adventures of a bold lamb (Judah) and his stable friends as they try to avoid the sacrificial alter the week preceding the crucifixion of Christ. It is a heart-warming account of the Easter story as seen through the eyes of a lovable pig (Horace), a faint-hearted horse (Monty), a pedantic rat (Slink), a rambling rooster (Drake), a motherly cow (Esmay) and a downtrodden donkey (Jack). This magnificent period piece with its epic sets is a roller coaster ride of emotions. Enveloped in humor, this quest follows the animals from the stable in Bethlehem to the great temple in Jerusalem and onto the hillside of Calvary as these unlikely heroes try to save their friend. The journey weaves seamlessly through the biblical accounts of Palm Sunday, Jesus turning the tables in the temple, Peter\'s denial and with a tense, heart-wrenching climax, depicts the crucifixion and resurrection with gentleness and breathtaking beauty. For Judah, the lamb with the heart of a lion, it is a story of courage and faith. For Jack, the disappointed donkey, it becomes a pivotal voyage of hope. For Horace, the, well the dirty pig, and Drake the ignorant rooster, it is an opportunity to do something inappropriate and get into trouble.'
})
it('returns best results for lamb', () => {
// This should be fairly easy. We test that exact matches come before
// prefix matches, and that hits in shorter fields (title) come before
// hits in longer fields (description)
const hits = ms.search('lamb', { fuzzy: 1, prefix: true })
expect(hits.map(({ title }) => title)).toEqual([
// Exact title match.
'Lamb',
// Contains term twice, shortest description.
'Boundin\'',
// Contains term twice.
'Ringing Bell',
// Contains term twice, longest description.
'The Lion of Judah',
// Prefix match in title.
'The Silence of the Lambs'
])
})
it('returns best results for sheep', () => {
// This tests more complex interaction between scoring. We want hits in
// the title to be automatically considered most relevant, because they
// are very short, and the search term occurs less frequently in the
// title than it does in the description. One result, 'Rams', has a very
// short description with an exact match, but it should never outrank
// the result with an exact match in the title AND description.
const hits = ms.search('sheep', { fuzzy: 1, prefix: true })
expect(hits.map(({ title }) => title)).toEqual([
// Has 'sheep' in title and once in a description of average length.
'Shaun the Sheep',
// Has 'sheep' just once, in a short description.
'Rams',
// Contains 'sheep' just once, in a long title.
'Shaun the Sheep: The Farmer\'s Llamas',
// Has most occurrences of 'sheep'.
'Ringing Bell',
// Contains 'sheep' just once, in a long description.
'Lamb'
])
})
it('returns best results for shaun', () => {
// Two movies contain the query in the title. Pick the shorter title.
expect(ms.search('shaun the sheep')[0].title).toEqual('Shaun the Sheep')
expect(ms.search('shaun the sheep', { fuzzy: 1, prefix: true })[0].title).toEqual('Shaun the Sheep')
})
it('returns best results for chirin', () => {
// The title contains neither 'sheep' nor the character name. Movies
// that have 'sheep' or 'the' in the title should not outrank this.
expect(ms.search('chirin the sheep')[0].title).toEqual('Ringing Bell')
expect(ms.search('chirin the sheep', { fuzzy: 1, prefix: true })[0].title).toEqual('Ringing Bell')
})
it('returns best results for judah', () => {
// Title contains the character's name, but the word 'sheep' never
// occurs. Other movies that do contain 'sheep' should not outrank this.
expect(ms.search('judah the sheep')[0].title).toEqual('The Lion of Judah')
expect(ms.search('judah the sheep', { fuzzy: 1, prefix: true })[0].title).toEqual('The Lion of Judah')
})
it('returns best results for bounding', () => {
// The expected hit has an exact match in the description and a fuzzy
// match in the title, and both variations of the term are highly
// specific. Does not contain 'sheep' at all! Because 'sheep' is a
// slightly more common term in the dataset, that should not cause other
// results to outrank this.
expect(ms.search('bounding sheep', { fuzzy: 1 })[0].title).toEqual('Boundin\'')
})
})
describe('song ranking set', () => {
const ms = new MiniSearch({
fields: ['song', 'artist'],
storeFields: ['song']
})
ms.add({
id: '1',
song: 'Killer Queen',
artist: 'Queen'
})
ms.add({
id: '2',
song: 'The Witch Queen Of New Orleans',
artist: 'Redbone'
})
ms.add({
id: '3',
song: 'Waterloo',
artist: 'Abba'
})
ms.add({
id: '4',
song: 'Take A Chance On Me',
artist: 'Abba'
})
ms.add({
id: '5',
song: 'Help',
artist: 'The Beatles'
})
ms.add({
id: '6',
song: 'Yellow Submarine',
artist: 'The Beatles'
})
ms.add({
id: '7',
song: 'Dancing Queen',
artist: 'Abba'
})
ms.add({
id: '8',
song: 'Bohemian Rhapsody',
artist: 'Queen'
})
it('returns best results for witch queen', () => {
const hits = ms.search('witch queen', { fuzzy: 1, prefix: true })
expect(hits.map(({ song }) => song)).toEqual([
// The only result that has both terms. This should not be outranked
// by hits that match only one term.
'The Witch Queen Of New Orleans',