-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsearch_test.go
More file actions
1612 lines (1286 loc) · 47.7 KB
/
Copy pathsearch_test.go
File metadata and controls
1612 lines (1286 loc) · 47.7 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
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
package blaze
import (
"strings"
"testing"
)
// ═══════════════════════════════════════════════════════════════════════════════
// PHRASE SEARCH TESTS
// ═══════════════════════════════════════════════════════════════════════════════
func TestInvertedIndex_NextPhrase_SimplePhrase(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "the quick brown fox")
// Search for "quick brown"
result := idx.NextPhrase("quick brown", BOFDocument)
if result[0].IsEnd() {
t.Fatal("NextPhrase() should find 'quick brown'")
}
// Should find it at Doc1, starting at position 0 (quick) ending at position 1 (brown)
if result[0].GetDocumentID() != 1 || result[0].GetOffset() != 0 {
t.Errorf("Phrase start = Doc%d:Pos%d, want Doc1:Pos0",
result[0].GetDocumentID(), result[0].GetOffset())
}
if result[1].GetDocumentID() != 1 || result[1].GetOffset() != 1 {
t.Errorf("Phrase end = Doc%d:Pos%d, want Doc1:Pos1",
result[1].GetDocumentID(), result[1].GetOffset())
}
}
func TestInvertedIndex_NextPhrase_ThreeWords(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "the quick brown fox jumps")
// Search for "quick brown fox"
result := idx.NextPhrase("quick brown fox", BOFDocument)
if result[0].IsEnd() {
t.Fatal("NextPhrase() should find 'quick brown fox'")
}
// Phrase spans positions 0-2
if result[0].GetOffset() != 0 || result[1].GetOffset() != 2 {
t.Errorf("Phrase = Pos%d-Pos%d, want Pos0-Pos2",
result[0].GetOffset(), result[1].GetOffset())
}
}
func TestInvertedIndex_NextPhrase_NotFound(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "the quick brown fox")
// Search for phrase that doesn't exist
result := idx.NextPhrase("brown quick", BOFDocument)
if !result[0].IsEnd() {
t.Error("NextPhrase() should return EOF for non-existent phrase")
}
}
func TestInvertedIndex_NextPhrase_NonConsecutive(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick jumps brown fox")
// "quick brown" exists but not consecutively
result := idx.NextPhrase("quick brown", BOFDocument)
if !result[0].IsEnd() {
t.Error("NextPhrase() should not find non-consecutive words")
}
}
func TestInvertedIndex_NextPhrase_MultipleDocuments(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "the lazy dog")
idx.Index(2, "the quick brown fox")
idx.Index(3, "more text here")
// Search for phrase in Doc2
result := idx.NextPhrase("quick brown", BOFDocument)
if result[0].GetDocumentID() != 2 {
t.Errorf("Found phrase in Doc%d, want Doc2", result[0].GetDocumentID())
}
}
func TestInvertedIndex_NextPhrase_StartMidDocument(t *testing.T) {
idx := NewInvertedIndex()
// After stop word removal and stemming: "quick brown fox jump quick brown dog"
// Positions: 0=quick, 1=brown, 2=fox, 3=jump, 4=quick, 5=brown, 6=dog
idx.Index(1, "quick brown fox jumps over quick brown dog")
// Find first occurrence
result1 := idx.NextPhrase("quick brown", BOFDocument)
if result1[0].GetOffset() != 0 {
t.Errorf("First occurrence at Pos%d, want Pos0", result1[0].GetOffset())
}
// Find second occurrence (starting after first)
// After stop words removed: positions are 0,1,2,3,4,5,6
// Second "quick brown" is at positions 4-5
result2 := idx.NextPhrase("quick brown", result1[0])
if result2[0].GetOffset() != 4 {
t.Errorf("Second occurrence at Pos%d, want Pos4", result2[0].GetOffset())
}
}
func TestInvertedIndex_NextPhrase_SingleWord(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown fox")
// Single word phrase should work
result := idx.NextPhrase("brown", BOFDocument)
if result[0].IsEnd() {
t.Fatal("NextPhrase() should find single word 'brown'")
}
// Start and end should be the same position
if result[0].GetOffset() != result[1].GetOffset() {
t.Errorf("Single word phrase: start=%d, end=%d, should be equal",
result[0].GetOffset(), result[1].GetOffset())
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// FIND ALL PHRASES TESTS
// ═══════════════════════════════════════════════════════════════════════════════
func TestInvertedIndex_FindAllPhrases_Multiple(t *testing.T) {
idx := NewInvertedIndex()
// After stop word removal: "quick brown fox jump quick brown dog"
// Positions: 0=quick, 1=brown, 2=fox, 3=jump, 4=quick, 5=brown, 6=dog
idx.Index(1, "quick brown fox jumps over quick brown dog")
// Find all occurrences of "quick brown"
results := idx.FindAllPhrases("quick brown", BOFDocument)
if len(results) != 2 {
t.Fatalf("Found %d occurrences, want 2", len(results))
}
// First occurrence at positions 0-1
if results[0][0].GetOffset() != 0 || results[0][1].GetOffset() != 1 {
t.Errorf("First occurrence = Pos%d-Pos%d, want Pos0-Pos1",
results[0][0].GetOffset(), results[0][1].GetOffset())
}
// Second occurrence at positions 4-5
if results[1][0].GetOffset() != 4 || results[1][1].GetOffset() != 5 {
t.Errorf("Second occurrence = Pos%d-Pos%d, want Pos4-Pos5",
results[1][0].GetOffset(), results[1][1].GetOffset())
}
}
func TestInvertedIndex_FindAllPhrases_AcrossDocuments(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown fox")
idx.Index(2, "lazy dog sleeps")
idx.Index(3, "quick brown dog")
idx.Index(4, "more quick brown text")
// Find all occurrences of "quick brown"
results := idx.FindAllPhrases("quick brown", BOFDocument)
if len(results) != 3 {
t.Fatalf("Found %d occurrences, want 3", len(results))
}
// Verify documents
expectedDocs := []int{1, 3, 4}
for i, result := range results {
docID := result[0].GetDocumentID()
if docID != expectedDocs[i] {
t.Errorf("Occurrence %d in Doc%d, want Doc%d", i, docID, expectedDocs[i])
}
}
}
func TestInvertedIndex_FindAllPhrases_None(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown fox")
idx.Index(2, "lazy dog")
// Search for phrase that doesn't exist
results := idx.FindAllPhrases("brown lazy", BOFDocument)
if len(results) != 0 {
t.Errorf("Found %d occurrences, want 0", len(results))
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// COVER SEARCH TESTS
// ═══════════════════════════════════════════════════════════════════════════════
func TestInvertedIndex_NextCover_SimpleCover(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "the quick brown fox")
// Search for cover containing "quick" and "fox"
tokens := []string{"quick", "fox"}
result := idx.NextCover(tokens, BOFDocument)
if result[0].IsEnd() {
t.Fatal("NextCover() should find a cover")
}
// Should find cover from position 0 (quick) to position 2 (fox)
if result[0].GetDocumentID() != 1 {
t.Errorf("Cover in Doc%d, want Doc1", result[0].GetDocumentID())
}
if result[0].GetOffset() != 0 || result[1].GetOffset() != 2 {
t.Errorf("Cover = Pos%d-Pos%d, want Pos0-Pos2",
result[0].GetOffset(), result[1].GetOffset())
}
}
func TestInvertedIndex_NextCover_SamePosition(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown fox")
// Search for single token (cover of itself)
tokens := []string{"brown"}
result := idx.NextCover(tokens, BOFDocument)
if result[0].IsEnd() {
t.Fatal("NextCover() should find a cover")
}
// Cover should be a single position
if result[0].GetOffset() != result[1].GetOffset() {
t.Errorf("Single token cover: start=%d, end=%d, should be equal",
result[0].GetOffset(), result[1].GetOffset())
}
}
func TestInvertedIndex_NextCover_NotInSameDocument(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown")
idx.Index(2, "lazy fox")
// "quick" in Doc1, "fox" in Doc2 - should find no cover
tokens := []string{"quick", "fox"}
result := idx.NextCover(tokens, BOFDocument)
if !result[0].IsEnd() {
t.Error("NextCover() should return EOF when tokens span documents")
}
}
func TestInvertedIndex_NextCover_MultipleCovers(t *testing.T) {
idx := NewInvertedIndex()
// After stop word removal: "quick brown fox jump tall dog"
// Positions: 0=quick, 1=brown, 2=fox, 3=jump, 4=tall, 5=dog
idx.Index(1, "quick brown fox jumps over tall dog")
// First cover
tokens := []string{"quick", "tall"}
result1 := idx.NextCover(tokens, BOFDocument)
if result1[0].IsEnd() {
t.Fatal("Should find a cover")
}
// Cover should span from quick (pos 0) to tall (pos 4)
if result1[0].GetOffset() != 0 || result1[1].GetOffset() != 4 {
t.Errorf("First cover = Pos%d-Pos%d, want Pos0-Pos4",
result1[0].GetOffset(), result1[1].GetOffset())
}
// There shouldn't be another cover in this document
result2 := idx.NextCover(tokens, result1[0])
if !result2[0].IsEnd() {
t.Error("Should not find another cover")
}
}
func TestInvertedIndex_NextCover_TokenNotFound(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown fox")
// One token doesn't exist
tokens := []string{"quick", "elephant"}
result := idx.NextCover(tokens, BOFDocument)
if !result[0].IsEnd() {
t.Error("NextCover() should return EOF when token not found")
}
}
func TestInvertedIndex_NextCover_ThreeTokens(t *testing.T) {
idx := NewInvertedIndex()
// After stop word removal: "quick brown tall fox jump"
// Positions: 0=quick, 1=brown, 2=tall, 3=fox, 4=jump
idx.Index(1, "the quick brown tall fox jumps")
// Cover containing three tokens
tokens := []string{"quick", "tall", "fox"}
result := idx.NextCover(tokens, BOFDocument)
if result[0].IsEnd() {
t.Fatal("NextCover() should find a cover")
}
// Cover should span from "quick" (pos 0) to "fox" (pos 3)
if result[0].GetOffset() != 0 || result[1].GetOffset() != 3 {
t.Errorf("Cover = Pos%d-Pos%d, want Pos0-Pos3",
result[0].GetOffset(), result[1].GetOffset())
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// MATCH TESTS
// ═══════════════════════════════════════════════════════════════════════════════
func TestMatch_GetKey_Unique(t *testing.T) {
match1 := Match{
DocID: 1,
Offsets: []Position{
{DocumentID: 1, Offset: 0},
{DocumentID: 1, Offset: 5},
},
Score: 1.5,
}
match2 := Match{
DocID: 2,
Offsets: []Position{
{DocumentID: 2, Offset: 0},
{DocumentID: 2, Offset: 5},
},
Score: 1.5,
}
key1, err1 := match1.GetKey()
key2, err2 := match2.GetKey()
if err1 != nil || err2 != nil {
t.Fatalf("GetKey() errors: %v, %v", err1, err2)
}
// Keys should be different (different documents)
if key1 == key2 {
t.Error("Different matches should have different keys")
}
}
func TestMatch_GetKey_Deterministic(t *testing.T) {
match := Match{
DocID: 1,
Offsets: []Position{
{DocumentID: 1, Offset: 0},
{DocumentID: 1, Offset: 5},
},
Score: 1.5,
}
// Get key multiple times
key1, _ := match.GetKey()
key2, _ := match.GetKey()
key3, _ := match.GetKey()
// Should always return the same key
if key1 != key2 || key2 != key3 {
t.Error("GetKey() should be deterministic")
}
}
func TestMatch_GetKey_HashLength(t *testing.T) {
match := Match{
DocID: 1,
Offsets: []Position{
{DocumentID: 1, Offset: 0},
},
Score: 1.0,
}
key, err := match.GetKey()
if err != nil {
t.Fatalf("GetKey() error = %v", err)
}
// MD5 hash should be 32 hex characters
if len(key) != 32 {
t.Errorf("Key length = %d, want 32", len(key))
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// PROXIMITY RANKING TESTS
// ═══════════════════════════════════════════════════════════════════════════════
func TestInvertedIndex_RankProximity_SingleDocument(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown fox")
// Search for "quick fox"
results := idx.RankProximity("quick fox", 10)
if len(results) != 1 {
t.Fatalf("Found %d results, want 1", len(results))
}
// Should find document 1
if results[0].Offsets[0].GetDocumentID() != 1 {
t.Errorf("Result in Doc%d, want Doc1", results[0].Offsets[0].GetDocumentID())
}
// Score should be positive
if results[0].Score <= 0 {
t.Errorf("Score = %f, want > 0", results[0].Score)
}
}
func TestInvertedIndex_RankProximity_MultipleDocuments(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown fox")
idx.Index(2, "lazy dog")
idx.Index(3, "quick lazy fox")
// Search for "quick fox"
results := idx.RankProximity("quick fox", 10)
// Should find 2 documents (Doc1 and Doc3)
if len(results) != 2 {
t.Fatalf("Found %d results, want 2", len(results))
}
}
func TestInvertedIndex_RankProximity_ProximityScoring(t *testing.T) {
idx := NewInvertedIndex()
// Doc1: "quick" and "fox" are close (distance 2)
idx.Index(1, "quick brown fox")
// Doc2: "quick" and "fox" are far apart (distance 5)
idx.Index(2, "quick brown lazy sleeping tired fox")
// Search for "quick fox"
results := idx.RankProximity("quick fox", 10)
if len(results) != 2 {
t.Fatalf("Found %d results, want 2", len(results))
}
// Doc1 should have higher score (closer proximity)
doc1Score := 0.0
doc2Score := 0.0
for _, result := range results {
docID := result.Offsets[0].GetDocumentID()
switch docID {
case 1:
doc1Score = result.Score
case 2:
doc2Score = result.Score
}
}
if doc1Score <= doc2Score {
t.Errorf("Doc1 score (%f) should be > Doc2 score (%f)", doc1Score, doc2Score)
}
}
func TestInvertedIndex_RankProximity_MaxResults(t *testing.T) {
idx := NewInvertedIndex()
// Index many documents
for i := 1; i <= 10; i++ {
idx.Index(i, "quick brown fox")
}
// Request only 5 results
results := idx.RankProximity("quick fox", 5)
if len(results) > 5 {
t.Errorf("Returned %d results, want at most 5", len(results))
}
}
func TestInvertedIndex_RankProximity_EmptyQuery(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown fox")
// Empty query
results := idx.RankProximity("", 10)
if len(results) != 0 {
t.Errorf("Empty query returned %d results, want 0", len(results))
}
}
func TestInvertedIndex_RankProximity_NoResults(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown fox")
// Search for tokens that don't exist
results := idx.RankProximity("elephant giraffe", 10)
if len(results) != 0 {
t.Errorf("Found %d results, want 0", len(results))
}
}
func TestInvertedIndex_RankProximity_SingleToken(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "quick brown fox")
idx.Index(2, "lazy dog")
idx.Index(3, "quick rabbit")
// Search for single token
results := idx.RankProximity("quick", 10)
// Should find Doc1 and Doc3
if len(results) != 2 {
t.Fatalf("Found %d results, want 2", len(results))
}
}
func TestInvertedIndex_RankProximity_MultipleCoversInDocument(t *testing.T) {
idx := NewInvertedIndex()
// After stop word removal: "quick fox jump quick fox"
// Positions: 0=quick, 1=fox, 2=jump, 3=quick, 4=fox
idx.Index(1, "quick fox jumps over quick fox")
// Search for "quick fox"
results := idx.RankProximity("quick fox", 10)
if len(results) != 1 {
t.Fatalf("Found %d results, want 1", len(results))
}
// The algorithm finds covers. Each cover gets score = 1/(end-start+1)
// Cover 1: positions 0-1 → score = 1/(1-0+1) = 1/2 = 0.5
// Cover 2: positions 3-4 → score = 1/(4-3+1) = 1/2 = 0.5
// But the algorithm continues from the start position, so it might find
// an overlapping cover. Let's just check the score is reasonable.
actualScore := results[0].Score
// Score should be positive and reasonable
if actualScore <= 0 {
t.Errorf("Score = %f, should be positive", actualScore)
}
// Score should be at least 0.5 (one cover)
if actualScore < 0.5 {
t.Errorf("Score = %f, should be at least 0.5", actualScore)
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// INTEGRATION TESTS
// ═══════════════════════════════════════════════════════════════════════════════
func TestSearch_CompleteWorkflow(t *testing.T) {
idx := NewInvertedIndex()
// Index a small corpus
idx.Index(1, "the quick brown fox jumps over the lazy dog")
idx.Index(2, "a lazy brown dog sleeps peacefully")
idx.Index(3, "the quick brown rabbit hops quickly")
idx.Index(4, "foxes and dogs are both animals")
// Test 1: Phrase search
phraseResults := idx.FindAllPhrases("brown dog", BOFDocument)
if len(phraseResults) != 1 {
t.Errorf("Phrase search found %d results, want 1", len(phraseResults))
}
// Test 2: Proximity search
proximityResults := idx.RankProximity("quick brown", 10)
// Should find Doc1 and Doc3
if len(proximityResults) != 2 {
t.Errorf("Proximity search found %d results, want 2", len(proximityResults))
}
// Test 3: Multi-word query
multiResults := idx.RankProximity("fox dog", 10)
// Doc1 has both, Doc2 has dog, Doc4 has both
if len(multiResults) < 2 {
t.Errorf("Multi-word search found %d results, want at least 2", len(multiResults))
}
}
func TestSearch_RealWorldScenario(t *testing.T) {
idx := NewInvertedIndex()
// Index blog posts
idx.Index(1, "introduction to machine learning algorithms")
idx.Index(2, "deep learning tutorial for beginners")
idx.Index(3, "machine learning and deep learning compared")
idx.Index(4, "natural language processing tutorial")
idx.Index(5, "machine learning in python")
// Search: "machine learning"
results := idx.RankProximity("machine learning", 10)
// Should find Doc1, Doc3, and Doc5
if len(results) != 3 {
t.Errorf("Found %d results for 'machine learning', want 3", len(results))
}
// All results should have both words
for i, result := range results {
docID := result.Offsets[0].GetDocumentID()
if docID != 1 && docID != 3 && docID != 5 {
t.Errorf("Result %d is Doc%d, should be Doc1, Doc3, or Doc5", i, docID)
}
}
// Search: "deep learning tutorial"
results2 := idx.RankProximity("deep learning tutorial", 10)
// Should find Doc2 with high score (all three words close together)
if len(results2) == 0 {
t.Fatal("Should find results for 'deep learning tutorial'")
}
// Doc2 should be in the results
foundDoc2 := false
for _, result := range results2 {
if result.Offsets[0].GetDocumentID() == 2 {
foundDoc2 = true
break
}
}
if !foundDoc2 {
t.Error("Doc2 should be in results for 'deep learning tutorial'")
}
}
func TestSearch_EdgeCases(t *testing.T) {
idx := NewInvertedIndex()
// Test with special characters and punctuation
idx.Index(1, "Hello, world! This is a test.")
idx.Index(2, "Test-driven development is great!")
// Search should work despite punctuation
results := idx.RankProximity("test", 10)
// Should find both documents
if len(results) != 2 {
t.Errorf("Found %d results, want 2", len(results))
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// HELPER FUNCTION TESTS
// ═══════════════════════════════════════════════════════════════════════════════
func TestLimitResults_LessThanMax(t *testing.T) {
matches := []Match{
{Score: 1.0},
{Score: 2.0},
{Score: 3.0},
}
result := limitResults(matches, 10)
if len(result) != 3 {
t.Errorf("limitResults() returned %d items, want 3", len(result))
}
}
func TestLimitResults_MoreThanMax(t *testing.T) {
matches := []Match{
{Score: 1.0},
{Score: 2.0},
{Score: 3.0},
{Score: 4.0},
{Score: 5.0},
}
result := limitResults(matches, 3)
if len(result) != 3 {
t.Errorf("limitResults() returned %d items, want 3", len(result))
}
}
func TestLimitResults_Empty(t *testing.T) {
matches := []Match{}
result := limitResults(matches, 10)
if len(result) != 0 {
t.Errorf("limitResults() returned %d items, want 0", len(result))
}
}
func TestIsValidPhrase(t *testing.T) {
idx := NewInvertedIndex()
tests := []struct {
name string
start Position
end Position
termCount int
want bool
}{
{
"Valid 2-word phrase",
Position{DocumentID: 1, Offset: 0},
Position{DocumentID: 1, Offset: 1},
2,
true,
},
{
"Valid 3-word phrase",
Position{DocumentID: 1, Offset: 5},
Position{DocumentID: 1, Offset: 7},
3,
true,
},
{
"Non-consecutive words",
Position{DocumentID: 1, Offset: 0},
Position{DocumentID: 1, Offset: 5},
3,
false,
},
{
"Different documents",
Position{DocumentID: 1, Offset: 0},
Position{DocumentID: 2, Offset: 1},
2,
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := idx.isValidPhrase(tt.start, tt.end, tt.termCount)
if got != tt.want {
t.Errorf("isValidPhrase() = %v, want %v", got, tt.want)
}
})
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// BENCHMARK TESTS
// ═══════════════════════════════════════════════════════════════════════════════
func BenchmarkNextPhrase(b *testing.B) {
idx := NewInvertedIndex()
// Pre-populate index
for i := 1; i <= 100; i++ {
idx.Index(i, "the quick brown fox jumps over the lazy dog")
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
idx.NextPhrase("quick brown", BOFDocument)
}
}
func BenchmarkNextCover(b *testing.B) {
idx := NewInvertedIndex()
// Pre-populate index
for i := 1; i <= 100; i++ {
idx.Index(i, "the quick brown fox jumps over the lazy dog")
}
tokens := []string{"quick", "lazy"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
idx.NextCover(tokens, BOFDocument)
}
}
func BenchmarkRankProximity(b *testing.B) {
idx := NewInvertedIndex()
// Pre-populate index with realistic documents
documents := []string{
"introduction to machine learning algorithms and techniques",
"deep learning neural networks for image recognition",
"natural language processing with python programming",
"machine learning models and evaluation metrics",
"computer vision and image processing fundamentals",
}
for i, doc := range documents {
idx.Index(i+1, strings.Repeat(doc+" ", 20)) // Repeat for larger corpus
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
idx.RankProximity("machine learning", 10)
}
}
func BenchmarkFindAllPhrases(b *testing.B) {
idx := NewInvertedIndex()
// Pre-populate index
for i := 1; i <= 50; i++ {
idx.Index(i, "the quick brown fox jumps over the lazy dog and quick brown cat")
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
idx.FindAllPhrases("quick brown", BOFDocument)
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// BM25 TESTS
// ═══════════════════════════════════════════════════════════════════════════════
func TestInvertedIndex_calculateIDF_BasicCases(t *testing.T) {
idx := NewInvertedIndex()
// Index 3 documents
idx.Index(1, "machine learning")
idx.Index(2, "machine learning algorithms")
idx.Index(3, "deep learning")
// Get analyzed/stemmed versions of terms
machineTokens := Analyze("machine")
learningTokens := Analyze("learning")
deepTokens := Analyze("deep")
// Test IDF for "machine" (appears in 2 out of 3 docs)
idfMachine := idx.calculateIDF(machineTokens[0])
if idfMachine <= 0 {
t.Errorf("IDF for 'machine' = %f, want > 0", idfMachine)
}
// Test IDF for "learning" (appears in all 3 docs - should be lower)
idfLearning := idx.calculateIDF(learningTokens[0])
if idfLearning <= 0 {
t.Errorf("IDF for 'learning' = %f, want > 0", idfLearning)
}
// Test IDF for "deep" (appears in 1 out of 3 docs - should be highest)
idfDeep := idx.calculateIDF(deepTokens[0])
if idfDeep <= 0 {
t.Errorf("IDF for 'deep' = %f, want > 0", idfDeep)
}
// Rarer terms should have higher IDF
if idfDeep <= idfMachine {
t.Errorf("IDF('deep')=%f should be > IDF('machine')=%f (rarer term)", idfDeep, idfMachine)
}
}
func TestInvertedIndex_calculateIDF_NonExistentTerm(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "machine learning")
// IDF for non-existent term should be 0
idf := idx.calculateIDF("nonexistent")
if idf != 0 {
t.Errorf("IDF for non-existent term = %f, want 0", idf)
}
}
func TestInvertedIndex_calculateIDF_SingleDocument(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "machine learning algorithms")
// Get analyzed/stemmed version of term
machineTokens := Analyze("machine")
// With only 1 document, IDF calculation should still work
idf := idx.calculateIDF(machineTokens[0])
// N=1, df=1: log((1-1+0.5)/(1+0.5) + 1) = log(0.5/1.5 + 1) = log(1.333...) ≈ 0.287
if idf <= 0 {
t.Errorf("IDF with single document = %f, want > 0", idf)
}
}
func TestInvertedIndex_countDocsInPostingList(t *testing.T) {
idx := NewInvertedIndex()
// Index documents where "machine" appears multiple times per doc
idx.Index(1, "machine learning machine vision")
idx.Index(2, "machine intelligence")
idx.Index(3, "deep learning")
// Get analyzed/stemmed version of term
machineTokens := Analyze("machine")
// Get posting list for "machine" (stemmed version)
skipList, exists := idx.getPostingList(machineTokens[0])
if !exists {
t.Fatal("posting list for 'machine' should exist")
}
// Count unique documents
count := idx.countDocsInPostingList(skipList)
if count != 2 {
t.Errorf("countDocsInPostingList() = %d, want 2 (Doc1 and Doc2)", count)
}
}
func TestInvertedIndex_calculateBM25Score_BasicScoring(t *testing.T) {
idx := NewInvertedIndex()
// Index documents
idx.Index(1, "machine learning algorithms")
idx.Index(2, "deep learning neural networks")
idx.Index(3, "machine learning and deep learning")
// Calculate BM25 score for Doc1 with query "machine learning"
// Use analyzed tokens (stemmed versions)
tokens := Analyze("machine learning")
score := idx.calculateBM25Score(1, tokens)
// Score should be positive
if score <= 0 {
t.Errorf("BM25 score for Doc1 = %f, want > 0", score)
}
}
func TestInvertedIndex_calculateBM25Score_DocumentWithAllTerms(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "machine learning")
idx.Index(2, "machine")
idx.Index(3, "learning")
// Doc1 has both terms, Doc2 and Doc3 have only one
// Use analyzed tokens (stemmed versions)
tokens := Analyze("machine learning")
score1 := idx.calculateBM25Score(1, tokens)
score2 := idx.calculateBM25Score(2, tokens)
score3 := idx.calculateBM25Score(3, tokens)
// Doc1 should have higher score than Doc2 or Doc3
if score1 <= score2 {
t.Errorf("Doc1 (both terms) score=%f should be > Doc2 (one term) score=%f", score1, score2)
}
if score1 <= score3 {
t.Errorf("Doc1 (both terms) score=%f should be > Doc3 (one term) score=%f", score1, score3)
}
}
func TestInvertedIndex_calculateBM25Score_TermFrequency(t *testing.T) {
idx := NewInvertedIndex()
// Doc1: "machine" appears once
idx.Index(1, "machine learning algorithms")
// Doc2: "machine" appears three times
idx.Index(2, "machine learning machine vision machine intelligence")
// Use analyzed tokens (stemmed versions)
tokens := Analyze("machine")
score1 := idx.calculateBM25Score(1, tokens)
score2 := idx.calculateBM25Score(2, tokens)
// Doc2 should have higher score due to higher term frequency
if score2 <= score1 {
t.Errorf("Doc2 (TF=3) score=%f should be > Doc1 (TF=1) score=%f", score2, score1)
}
}
func TestInvertedIndex_calculateBM25Score_LengthNormalization(t *testing.T) {
idx := NewInvertedIndex()
// Short document with term
idx.Index(1, "machine learning")
// Long document with same term
idx.Index(2, "machine learning algorithms neural networks deep learning artificial intelligence natural language processing computer vision")
// Use analyzed tokens (stemmed versions)
tokens := Analyze("machine")
score1 := idx.calculateBM25Score(1, tokens)
score2 := idx.calculateBM25Score(2, tokens)
// Shorter document should typically score higher (length normalization)
// Both have "machine" once, but Doc1 is much shorter
if score1 <= score2 {
t.Errorf("Short doc score=%f should be > long doc score=%f due to length normalization", score1, score2)
}
}
func TestInvertedIndex_calculateBM25Score_NonExistentDocument(t *testing.T) {
idx := NewInvertedIndex()
idx.Index(1, "machine learning")
// Score for non-existent document should be 0
score := idx.calculateBM25Score(999, []string{"machine"})
if score != 0 {
t.Errorf("Score for non-existent doc = %f, want 0", score)
}
}
func TestInvertedIndex_RankBM25_BasicRanking(t *testing.T) {