-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
1209 lines (1124 loc) · 40.3 KB
/
engine.go
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 search
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"math"
"net/url"
"sort"
"strings"
"sync"
"time"
"gopkg.in/volatiletech/null.v6"
log "github.com/Sirupsen/logrus"
"github.com/pkg/errors"
"gopkg.in/olivere/elastic.v6"
"github.com/Bnei-Baruch/archive-backend/cache"
"github.com/Bnei-Baruch/archive-backend/consts"
"github.com/Bnei-Baruch/archive-backend/es"
"github.com/Bnei-Baruch/archive-backend/utils"
)
type ESEngine struct {
esc *elastic.Client
mdb *sql.DB
cache cache.CacheManager
ExecutionTimeLog *TimeLogMap
grammars Grammars
TokensCache *TokensCache
variables VariablesV2
}
type ClassificationIntent struct {
// Fields from result.
ResultType string `json:"result_type"`
MDB_UID string `json:"mdb_uid"`
Title string `json:"title"`
FullTitle string `json:"full_title"`
// Intent fields.
ContentType string `json:"content_type"`
Exist bool `json:"exist"`
Score *float64 `json:"score,omitempty"`
Explanation elastic.SearchExplanation `json:"explanation,omitempty"`
MaxScore *float64 `json:"max_score,omitempty"`
MaxExplanation elastic.SearchExplanation `json:"max_explanation,omitempty"`
}
type FilteredSearchResult struct {
Term string
PreserveTermForHighlight bool //Use the term as highlight term even if we have same hit result from regular search
HitIdsMap map[string]bool
Results []*elastic.SearchResult
MaxScore *float64
ProgramCollection *string
}
type TimeLogMap struct {
mx sync.Mutex
m map[string]time.Duration
}
func NewTimeLogMap() *TimeLogMap {
return &TimeLogMap{
m: make(map[string]time.Duration),
}
}
func (c *TimeLogMap) Load(key string) (time.Duration, bool) {
c.mx.Lock()
defer c.mx.Unlock()
val, ok := c.m[key]
return val, ok
}
func (c *TimeLogMap) Store(key string, value time.Duration) {
c.mx.Lock()
defer c.mx.Unlock()
c.m[key] = value
fmt.Printf("%s - %s\n", key, value.String())
}
func (c *TimeLogMap) ToMap() map[string]time.Duration {
c.mx.Lock()
defer c.mx.Unlock()
copyMap := map[string]time.Duration{}
for k, v := range c.m {
copyMap[k] = v
}
return copyMap
}
type byRelevance []*elastic.SearchHit
type byNewerToOlder []*elastic.SearchHit
type byOlderToNewer []*elastic.SearchHit
type bySourceFirst []*elastic.SearchHit
func (s byRelevance) Len() int {
return len(s)
}
func (s byRelevance) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byRelevance) Less(i, j int) bool {
res, err := compareHits(s[i], s[j], consts.SORT_BY_RELEVANCE)
if err != nil {
panic(fmt.Sprintf("compareHits error: %s", err))
}
return res
}
func (s byNewerToOlder) Len() int {
return len(s)
}
func (s byNewerToOlder) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byNewerToOlder) Less(i, j int) bool {
res, err := compareHits(s[i], s[j], consts.SORT_BY_NEWER_TO_OLDER)
if err != nil {
panic(fmt.Sprintf("compareHits error: %s", err))
}
return res
}
func (s byOlderToNewer) Len() int {
return len(s)
}
func (s byOlderToNewer) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byOlderToNewer) Less(i, j int) bool {
res, err := compareHits(s[i], s[j], consts.SORT_BY_OLDER_TO_NEWER)
if err != nil {
panic(fmt.Sprintf("compareHits error: %s", err))
}
return res
}
func (s bySourceFirst) Len() int {
return len(s)
}
func (s bySourceFirst) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s bySourceFirst) Less(i, j int) bool {
res, err := compareHits(s[i], s[j], consts.SORT_BY_SOURCE_FIRST)
if err != nil {
panic(fmt.Sprintf("compareHits error: %s", err))
}
return res
}
// TODO: All interactions with ES should be throttled to prevent downstream pressure
func NewESEngine(esc *elastic.Client, db *sql.DB, cache cache.CacheManager /*, grammars Grammars*/, tc *TokensCache, variables VariablesV2) *ESEngine {
return &ESEngine{
esc: esc,
mdb: db,
cache: cache,
ExecutionTimeLog: NewTimeLogMap(),
//grammars: grammars,
TokensCache: tc,
variables: variables,
}
}
func SuggestionHasOptions(ss elastic.SearchSuggest) bool {
for _, v := range ss {
for _, s := range v {
if len(s.Options) > 0 {
return true
}
}
}
return false
}
func (e *ESEngine) GetSuggestions(ctx context.Context, query Query, preference string) (interface{}, error) {
beforeGetSuggest := time.Now()
defer func() { e.timeTrack(beforeGetSuggest, consts.LAT_GETSUGGESTIONS) }()
// Run grammar suggestions in parallel.
grammarSuggestionsChannel := make(chan map[string][]VariablesByPhrase)
go func() {
defer func() {
if err := recover(); err != nil {
log.Errorf("ESEngine.GetSuggestions - Panic adding intents: %+v", err)
grammarSuggestionsChannel <- make(map[string][]VariablesByPhrase)
}
}()
beforeSuggestSuggest := time.Now()
grammarSuggestions, err := e.SuggestGrammarsV2(&query, preference)
if err != nil {
log.Errorf("ESEngine.GetSuggestions - Error adding intents: %+v", err)
grammarSuggestionsChannel <- make(map[string][]VariablesByPhrase)
} else {
grammarSuggestionsChannel <- grammarSuggestions
}
e.timeTrack(beforeSuggestSuggest, consts.LAT_SUGGEST_SUGGESTIONS)
}()
multiSearchService := e.esc.MultiSearch()
requests := NewResultsSuggestRequests([]string{
consts.ES_RESULT_TYPE_UNITS,
consts.ES_RESULT_TYPE_COLLECTIONS,
consts.ES_RESULT_TYPE_TAGS,
consts.ES_RESULT_TYPE_SOURCES,
consts.ES_RESULT_TYPE_BLOG_POSTS,
//consts.ES_RESULT_TYPE_TWEETS,
}, query, preference)
multiSearchService.Add(requests...)
// Actual call to elastic
beforeMssDo := time.Now()
mr, err := multiSearchService.Do(ctx)
e.timeTrack(beforeMssDo, consts.LAT_GETSUGGESTIONS_MULTISEARCHDO)
if err != nil {
// don't kill entire request if ctx was cancelled
if ue, ok := err.(*url.Error); ok {
if ue.Err == context.DeadlineExceeded || ue.Err == context.Canceled {
if ue.Err == context.DeadlineExceeded {
log.Warn("ESEngine.GetSuggestions - ctx cancelled - deadline.")
}
if ue.Err == context.Canceled {
log.Warn("ESEngine.GetSuggestions - ctx cancelled - canceled.")
}
return nil, nil
}
}
return nil, errors.Wrap(err, "ESEngine.GetSuggestions")
}
// Nativize response to client - Replace title with full title
for _, r := range mr.Responses {
for key := range r.Suggest {
for j := range r.Suggest[key] {
for opIdx, op := range r.Suggest[key][j].Options {
var src es.Result
err = json.Unmarshal(*op.Source, &src)
if err != nil {
log.Errorf("ESEngine.GetSuggestions - cannot unmarshal source.")
continue
}
if src.ResultType == consts.ES_RESULT_TYPE_SOURCES && src.FullTitle != "" {
src.Title = src.FullTitle
src.FullTitle = ""
nsrc, err := json.Marshal(src)
if err != nil {
log.Errorf("ESEngine.GetSuggestions - cannot marshal source with title correction.")
continue
}
r.Suggest[key][j].Options[opIdx].Source = (*json.RawMessage)(&nsrc)
}
}
}
}
}
// Merge with grammar suggestions.
var grammarSuggestions map[string][]VariablesByPhrase
grammarSuggestions = <-grammarSuggestionsChannel
for i, lang := range query.LanguageOrder {
if langSuggestions, ok := grammarSuggestions[lang]; ok && len(langSuggestions) > 0 && mr != nil && len(mr.Responses) > i {
r := mr.Responses[i]
if r.Suggest == nil {
r.Suggest = make(map[string][]elastic.SearchSuggestion)
}
if len(r.Suggest) == 0 {
r.Suggest["title_suggest"] = []elastic.SearchSuggestion{}
}
for key := range r.Suggest {
for j := range r.Suggest[key] {
for _, variablesByPhrase := range langSuggestions {
for suggestion, _ := range variablesByPhrase {
source := struct {
Title string `json:"title"`
ResultType string `json:"result_type"`
}{Title: suggestion, ResultType: consts.GRAMMAR_TYPE_LANDING_PAGE}
sourceRawMessage, err := json.Marshal(source)
if err != nil {
return nil, err
}
raw := json.RawMessage(sourceRawMessage)
option := elastic.SearchSuggestionOption{
Text: suggestion,
Source: &raw,
}
r.Suggest[key][j].Options = append([]elastic.SearchSuggestionOption{option}, r.Suggest[key][j].Options...)
}
}
}
}
}
}
// Debug. Tokens stats: fmt.Printf("--------------Count: %d, First: %d\n", countVM, countVMFirst)
// Process response
sRes := (*elastic.SearchResult)(nil)
for _, r := range mr.Responses {
if r != nil && SuggestionHasOptions(r.Suggest) {
sRes = r
break
}
}
if sRes == nil && len(mr.Responses) > 0 {
sRes = mr.Responses[0]
}
return sRes, nil
}
func (e *ESEngine) IntentsToResults(query *Query) (error, map[string]*elastic.SearchResult) {
srMap := make(map[string]*elastic.SearchResult)
for _, lang := range query.LanguageOrder {
sh := &elastic.SearchHits{TotalHits: 0}
sr := &elastic.SearchResult{Hits: sh}
srMap[lang] = sr
}
// Limit ClassificationIntents to top MAX_CLASSIFICATION_INTENTS
boostClassificationScore := func(intentValue *ClassificationIntent) float64 {
if intentValue.MaxScore != nil {
// Boost up to 33% for exact match, i.e., for score / max score of 1.0.
return *intentValue.Score * (3.0 + *intentValue.Score / *intentValue.MaxScore) / 3.0
}
return *intentValue.Score
}
scores := []float64{}
for i := range query.Intents {
// Convert intent to result with score.
if intentValue, ok := query.Intents[i].Value.(ClassificationIntent); ok && intentValue.Exist {
scores = append(scores, boostClassificationScore(&intentValue))
}
}
sort.Float64s(scores)
minClassificationScore := float64(0)
if len(scores) > 0 {
scores = scores[utils.MaxInt(0, len(scores)-consts.MAX_CLASSIFICATION_INTENTS):]
minClassificationScore = scores[0]
}
// log.Infof("IntentsToResults - %d intents.", len(query.Intents))
for _, intent := range query.Intents {
// Convert intent to result with score.
if intentValue, ok := intent.Value.(ClassificationIntent); ok {
boostedScore := float64(0.0)
if intentValue.Exist {
sh := srMap[intent.Language].Hits
sh.TotalHits++
boostedScore = boostClassificationScore(&intentValue)
if boostedScore < minClassificationScore {
continue // Skip classificaiton intents with score lower then first MAX_CLASSIFICATION_INTENTS
}
if sh.MaxScore != nil {
maxScore := math.Max(*sh.MaxScore, boostedScore)
sh.MaxScore = &maxScore
} else {
sh.MaxScore = &boostedScore
}
intentHit := &elastic.SearchHit{}
intentHit.Explanation = &intentValue.Explanation
intentHit.Score = &boostedScore
intentHit.Index = consts.INTENT_INDEX_BY_TYPE[intent.Type]
intentHit.Type = consts.INTENT_HIT_TYPE_BY_CT[intentValue.ContentType]
source, err := json.Marshal(intentValue)
if err != nil {
return err, nil
}
intentHit.Source = (*json.RawMessage)(&source)
sh.Hits = append(sh.Hits, intentHit)
}
// log.Infof("Added intent %s %s %s boost score:%f exist:%t", intentValue.Title, intent.Type, intent.Language, boostedScore, intentValue.Exist)
}
if intentValue, ok := intent.Value.(GrammarIntent); ok {
sh := srMap[intent.Language].Hits
sh.TotalHits++
boostedScore := float64(2000.0)
if intentValue.Score > 0 {
boostedScore = intentValue.Score
}
if sh.MaxScore != nil {
maxScore := math.Max(*sh.MaxScore, boostedScore)
sh.MaxScore = &maxScore
} else {
sh.MaxScore = &boostedScore
}
var intentHit *elastic.SearchHit
convertedToSingleHit := false
if intentValue.SingleHit != nil {
intentHit = intentValue.SingleHit
convertedToSingleHit = true
} else {
intentHit = &elastic.SearchHit{}
}
if intentValue.Explanation != nil {
intentHit.Explanation = intentValue.Explanation
}
intentHit.Score = &boostedScore
if !convertedToSingleHit {
intentHit.Index = consts.GRAMMAR_INDEX
intentHit.Type = intent.Type
source, err := json.Marshal(intentValue)
if err != nil {
return err, nil
}
intentHit.Source = (*json.RawMessage)(&source)
}
sh.Hits = append(sh.Hits, intentHit)
}
}
return nil, srMap
}
func haveHits(r *elastic.SearchResult) bool {
return r != nil && r.Hits != nil && r.Hits.Hits != nil && len(r.Hits.Hits) > 0
}
func score(score *float64) float64 {
if score == nil {
return 0
} else {
return *score
}
}
func compareHits(h1 *elastic.SearchHit, h2 *elastic.SearchHit, sortBy string) (bool, error) {
if sortBy == consts.SORT_BY_RELEVANCE {
return score(h1.Score) > score(h2.Score), nil
} else if sortBy == consts.SORT_BY_SOURCE_FIRST {
var rt1, rt2 es.ResultType
if err := json.Unmarshal(*h1.Source, &rt1); err != nil {
return false, err
}
if err := json.Unmarshal(*h2.Source, &rt2); err != nil {
return false, err
}
// Order by sources first, then be score.
return rt1.ResultType == consts.ES_RESULT_TYPE_SOURCES && rt2.ResultType != consts.ES_RESULT_TYPE_SOURCES || score(h1.Score) > score(h2.Score), nil
} else {
var ed1, ed2 es.EffectiveDate
if err := json.Unmarshal(*h1.Source, &ed1); err != nil {
return false, err
}
if err := json.Unmarshal(*h2.Source, &ed2); err != nil {
return false, err
}
if ed1.EffectiveDate == nil {
ed1.EffectiveDate = &utils.Date{time.Time{}}
}
if ed2.EffectiveDate == nil {
ed2.EffectiveDate = &utils.Date{time.Time{}}
}
if sortBy == consts.SORT_BY_OLDER_TO_NEWER {
// Oder by older to newer, break ties using score.
return ed2.EffectiveDate.Time.After(ed1.EffectiveDate.Time) ||
ed2.EffectiveDate.Time.Equal(ed1.EffectiveDate.Time) && score(h1.Score) > score(h2.Score), nil
} else {
//log.Infof("%+v %+v %+v %+v", ed1, ed2, h1, h2)
// Order by newer to older, break ties using score.
return ed2.EffectiveDate.Time.Before(ed1.EffectiveDate.Time) ||
ed2.EffectiveDate.Time.Equal(ed1.EffectiveDate.Time) && score(h1.Score) > score(h2.Score), nil
}
}
}
func joinResponses(sortBy string, from int, size int, results ...*elastic.SearchResult) (*elastic.SearchResult, error) {
if len(results) == 0 {
return nil, nil
}
// Concatenate all result hits to single slice.
concatenated := make([]*elastic.SearchHit, 0)
for _, result := range results {
concatenated = append(concatenated, result.Hits.Hits...)
}
// Keep only unique results by MDB_UID (additional results with a duplicate MDB_UID might be added by Grammar).
unique := uniqueHitsByMdbUid(concatenated, []string{consts.INTENT_INDEX_TAG, consts.INTENT_INDEX_SOURCE})
// Apply sorting.
if sortBy == consts.SORT_BY_RELEVANCE {
sort.Stable(byRelevance(unique))
} else if sortBy == consts.SORT_BY_OLDER_TO_NEWER {
sort.Stable(byOlderToNewer(unique))
} else if sortBy == consts.SORT_BY_NEWER_TO_OLDER {
sort.Stable(byNewerToOlder(unique))
} else if sortBy == consts.SORT_BY_SOURCE_FIRST {
sort.Stable(bySourceFirst(unique))
}
if from >= len(unique) {
// Edge case when we cannot calculate totalHits correctly due to many duplications of grammar and regular results (that we filter out only when loading a specific page).
unique = []*elastic.SearchHit{}
} else {
// Filter by relevant page.
unique = unique[from:utils.Min(from+size, len(unique))]
}
// Take arbitrary result to use as base and set it's hits.
// TODO: Rewrite this to be cleaner.
result := results[0]
// Get hits count and max score
totalHits := int64(0)
var maxScore float64
if result.Hits.MaxScore != nil {
maxScore = *result.Hits.MaxScore
} else {
maxScore = 0
}
for _, result := range results {
totalHits += result.Hits.TotalHits
if sortBy == consts.SORT_BY_RELEVANCE {
if result.Hits.MaxScore != nil {
maxScore = math.Max(maxScore, *result.Hits.MaxScore)
}
}
}
result.Hits.Hits = unique
result.Hits.TotalHits = totalHits
result.Hits.MaxScore = &maxScore
return result, nil
}
func uniqueHitsByMdbUid(hits []*elastic.SearchHit, indexesToIgnore []string) []*elastic.SearchHit {
unique := make([]*elastic.SearchHit, 0)
mdbMap := make(map[string]*elastic.SearchHit)
for _, hit := range hits {
var mdbUid es.MdbUid
if hit.Score != nil && !utils.Contains(utils.Is(indexesToIgnore), hit.Index) {
if err := json.Unmarshal(*hit.Source, &mdbUid); err == nil {
if mdbUid.MDB_UID != "" {
// Uncomment for debug
/*if _, ok := mdbMap[mdbUid.MDB_UID]; ok {
log.Infof("Found duplicate of %+v", hit)
}*/
// We keep the result with a higher score.
if _, ok := mdbMap[mdbUid.MDB_UID]; !ok || *hit.Score > *mdbMap[mdbUid.MDB_UID].Score {
mdbMap[mdbUid.MDB_UID] = hit
}
} else {
unique = append(unique, hit)
}
} else {
log.Warnf("Unable to unmarshal source for hit ''%s.", hit.Id)
unique = append(unique, hit)
}
} else {
unique = append(unique, hit)
}
}
for _, hit := range mdbMap {
unique = append(unique, hit)
}
return unique
}
func (e *ESEngine) timeTrack(start time.Time, operation string) {
elapsed := time.Since(start)
e.ExecutionTimeLog.Store(operation, elapsed)
}
func (e *ESEngine) DoSearch(ctx context.Context, query Query, sortBy string, from int, size int, preference string, checkTypo bool, timeoutForHighlight time.Duration) (*QueryResult, error) {
defer e.timeTrack(time.Now(), consts.LAT_DOSEARCH)
// Initializing all channels.
suggestChannel := make(chan null.String)
grammarsSingleHitIntentsChannel := make(chan []Intent, 1)
grammarsFilterIntentsChannel := make(chan []Intent, 1)
grammarsFilteredResultsByLangChannel := make(chan map[string][]FilteredSearchResult)
tweetsByLangChannel := make(chan map[string]*elastic.SearchResult)
var resultTypes []string
if sortBy == consts.SORT_BY_NEWER_TO_OLDER || sortBy == consts.SORT_BY_OLDER_TO_NEWER {
resultTypes = make([]string, 0)
for _, str := range consts.ES_SEARCH_RESULT_TYPES {
if str != consts.ES_RESULT_TYPE_COLLECTIONS {
resultTypes = append(resultTypes, str)
}
}
} else {
resultTypes = consts.ES_SEARCH_RESULT_TYPES
}
// Search grammars in parallel to native search.
go func() {
defer func() {
if err := recover(); err != nil {
log.Errorf("ESEngine.DoSearch - Panic searching grammars: %+v", err)
grammarsSingleHitIntentsChannel <- []Intent{}
grammarsFilterIntentsChannel <- []Intent{}
grammarsFilteredResultsByLangChannel <- map[string][]FilteredSearchResult{}
}
}()
if singleHitIntents, filterIntents, err := e.SearchGrammarsV2(&query, from, size, sortBy, resultTypes, preference); err != nil {
log.Errorf("ESEngine.DoSearch - Error searching grammars: %+v", err)
grammarsSingleHitIntentsChannel <- []Intent{}
grammarsFilterIntentsChannel <- []Intent{}
grammarsFilteredResultsByLangChannel <- map[string][]FilteredSearchResult{}
} else {
grammarsSingleHitIntentsChannel <- singleHitIntents
grammarsFilterIntentsChannel <- filterIntents
if filtered, err := e.SearchByFilterIntents(filterIntents, query.Filters, query.Term, from, size, sortBy, resultTypes, preference, query.Deb); err != nil {
log.Errorf("ESEngine.DoSearch - Error searching filtered results by grammars: %+v", err)
grammarsFilteredResultsByLangChannel <- map[string][]FilteredSearchResult{}
} else {
grammarsFilteredResultsByLangChannel <- filtered
}
}
}()
// Search tweets in parallel to native search.
go func() {
defer func() {
if err := recover(); err != nil {
log.Errorf("ESEngine.DoSearch - Panic searching tweets: %+v", err)
tweetsByLangChannel <- map[string]*elastic.SearchResult{}
}
}()
if tweetsByLang, err := e.SearchTweets(query, sortBy, from, size, preference); err != nil {
log.Errorf("ESEngine.DoSearch - Error searching tweets: %+v", err)
tweetsByLangChannel <- map[string]*elastic.SearchResult{}
} else {
tweetsByLangChannel <- tweetsByLang
}
}()
filterIntents := <-grammarsFilterIntentsChannel
if checkTypo {
go func() {
defer func() {
if err := recover(); err != nil {
log.Errorf("ESEngine.GetTypoSuggest - Panic getting typo suggest: %+v", err)
suggestChannel <- null.String{"", false}
}
}()
if suggestText, err := e.GetTypoSuggest(query, filterIntents); err != nil {
log.Errorf("ESEngine.GetTypoSuggest - Error getting typo suggest: %+v", err)
suggestChannel <- null.String{"", false}
} else {
suggestChannel <- suggestText
}
}()
}
query.Intents = append(query.Intents, <-grammarsSingleHitIntentsChannel...)
hasClassificationIntentFromGrammar := false
for _, intent := range query.Intents {
if intentValue, ok := intent.Value.(ClassificationIntent); ok && intentValue.Exist {
hasClassificationIntentFromGrammar = true
break
}
}
// Grammar engine is currently support a search for classification intents according to 'by_content_type_and_source' rule only.
// If we have classification intents from Grammar, IntentsEngine will search for intents only by tag.
intents, err := e.AddIntents(&query, preference, sortBy, true, !hasClassificationIntentFromGrammar, filterIntents)
if err != nil {
log.Errorf("ESEngine.DoSearch - Error adding intents: %+v", err)
}
query.Intents = append(query.Intents, intents...)
log.Debugf("Intents: %+v", query.Intents)
// When we have a lessons carousel we filter out the regular results that are also exist in the carousel.
filterOutCUSources := make([]string, 0)
for _, intent := range query.Intents {
if intent.Type == consts.INTENT_TYPE_SOURCE {
if intentValue, ok := intent.Value.(ClassificationIntent); ok && intentValue.Exist {
// This is not a perfect solution since we dont know yet what is the currentLang and we filter by all languages
// Also: it is possible that we may filter regular lesson results even if the carousel is not on the first page.
filterOutCUSources = append(filterOutCUSources, intentValue.MDB_UID)
log.Infof("MDB_UID added to filterOutCUSources: %s.", intentValue.MDB_UID)
}
}
}
multiSearchService := e.esc.MultiSearch()
requests, err := NewResultsSearchRequests(
SearchRequestOptions{
resultTypes: resultTypes,
index: "",
query: query,
sortBy: sortBy,
from: 0,
size: from + size,
preference: preference,
useHighlight: false,
partialHighlight: false,
filterOutCUSources: filterOutCUSources})
if err != nil {
return nil, errors.Wrap(err, "ESEngine.DoSearch - Error multisearch Do on creating requests.")
}
multiSearchService.Add(requests...)
// Do search.
beforeDoSearch := time.Now()
mr, err := multiSearchService.Do(context.TODO())
e.timeTrack(beforeDoSearch, consts.LAT_DOSEARCH_MULTISEARCHDO)
if err != nil {
return nil, errors.Wrap(err, "ESEngine.DoSearch - Error multisearch Do.")
}
shouldMergeResults := false
// Right now we are testing the language results merge for Spanish UI only
for _, lang := range query.LanguageOrder {
if lang == consts.LANG_SPANISH {
shouldMergeResults = true
break
}
}
if len(mr.Responses) != len(query.LanguageOrder) {
return nil, errors.New(fmt.Sprintf("Unexpected number of results %d, expected %d",
len(mr.Responses), len(query.LanguageOrder)))
}
resultsByLang := make(map[string][]*elastic.SearchResult)
// Responses are ordered by language by index, i.e., for languages [bg, ru, en].
// We want the first matching language that has at least any result.
var maxRegularScore *float64 // max score for regular result - not intent, grammar or tweet
programsToReplaceWithGrammarResults := []struct {
hitId string
score float64
grammarHitId *string
}{}
for i, currentResults := range mr.Responses {
if currentResults.Error != nil {
log.Warnf("%+v", currentResults.Error)
return nil, errors.New(fmt.Sprintf("Failed multi get: %+v", currentResults.Error))
}
if haveHits(currentResults) {
if len(filterIntents) > 0 {
var programCollectionUid *string
for _, fi := range filterIntents {
if intentValue, ok := fi.Value.(GrammarIntent); ok {
freeText := getFilterValue(intentValue.FilterValues, consts.VARIABLE_TO_FILTER[consts.VAR_TEXT])
if freeText == nil {
programCollectionUid = getFilterValue(intentValue.FilterValues, consts.VARIABLE_TO_FILTER[consts.VAR_PROGRAM])
if programCollectionUid != nil {
break
}
}
}
}
if programCollectionUid != nil {
for _, hit := range currentResults.Hits.Hits {
if hit.Score == nil {
continue
}
var src es.Result
err = json.Unmarshal(*hit.Source, &src)
if err != nil {
log.Errorf("ESEngine.DoSearch - cannot unmarshal source for hit '%v'.", hit.Id)
continue
}
if src.ResultType == consts.ES_RESULT_TYPE_UNITS {
if utils.Contains(utils.Is(src.TypedUids), es.KeyValue(consts.ES_UID_TYPE_COLLECTION, *programCollectionUid)) {
programsToReplaceWithGrammarResults = append(programsToReplaceWithGrammarResults,
struct {
hitId string
score float64
grammarHitId *string
}{
hit.Id,
*hit.Score,
nil,
})
}
}
}
}
}
if len(programsToReplaceWithGrammarResults) > 0 {
sort.SliceStable(programsToReplaceWithGrammarResults, func(i, j int) bool {
return programsToReplaceWithGrammarResults[i].score > programsToReplaceWithGrammarResults[j].score
})
}
for _, p := range programsToReplaceWithGrammarResults {
log.Infof("Program to replace with grammar result: %+v", p)
}
if currentResults.Hits.MaxScore != nil {
if maxRegularScore == nil {
maxRegularScore = new(float64)
*maxRegularScore = *currentResults.Hits.MaxScore
}
if shouldMergeResults {
if *currentResults.Hits.MaxScore > *maxRegularScore {
*maxRegularScore = *currentResults.Hits.MaxScore
}
}
}
lang := query.LanguageOrder[i]
if _, ok := resultsByLang[lang]; !ok {
resultsByLang[lang] = make([]*elastic.SearchResult, 0)
}
resultsByLang[lang] = append(resultsByLang[lang], currentResults)
}
}
// Convert intents and grammars to results.
err, intentResultsMap := e.IntentsToResults(&query)
if err != nil {
return nil, errors.Wrap(err, "ESEngine.DoSearch - Error adding intents to results.")
}
for lang, intentResults := range intentResultsMap {
if haveHits(intentResults) {
if _, ok := resultsByLang[lang]; !ok {
resultsByLang[lang] = make([]*elastic.SearchResult, 0)
}
resultsByLang[lang] = append(resultsByLang[lang], intentResults)
}
}
tweetsByLang := <-tweetsByLangChannel
for lang, tweets := range tweetsByLang {
if _, ok := resultsByLang[lang]; !ok {
resultsByLang[lang] = make([]*elastic.SearchResult, 0)
}
resultsByLang[lang] = append(resultsByLang[lang], tweets)
}
filteredByLang := <-grammarsFilteredResultsByLangChannel
var programToReplaceIndex int
if len(programsToReplaceWithGrammarResults) > 0 {
for lang, filtered := range filteredByLang {
if _, ok := resultsByLang[lang]; !ok {
resultsByLang[lang] = make([]*elastic.SearchResult, 0)
}
for _, fr := range filtered {
if fr.ProgramCollection != nil {
for _, result := range fr.Results {
for _, hit := range result.Hits.Hits {
var src es.Result
err = json.Unmarshal(*hit.Source, &src)
if err != nil {
log.Errorf("ESEngine.DoSearch - cannot unmarshal source for hit '%v'.", hit.Id)
continue
}
if src.ResultType == consts.ES_RESULT_TYPE_UNITS {
if utils.Contains(utils.Is(src.TypedUids), es.KeyValue(consts.ES_UID_TYPE_COLLECTION, *fr.ProgramCollection)) {
if programToReplaceIndex < len(programsToReplaceWithGrammarResults) {
hit.Score = &programsToReplaceWithGrammarResults[programToReplaceIndex].score
programsToReplaceWithGrammarResults[programToReplaceIndex].grammarHitId = &hit.Id
// TBD update hit explanation
programToReplaceIndex++
} else {
zero := 0.0
hit.Score = &zero
}
}
}
}
}
}
}
}
}
// Loop over grammar filtered results to apply the score logic for combination with regular results
for lang, filtered := range filteredByLang {
if _, ok := resultsByLang[lang]; !ok {
resultsByLang[lang] = make([]*elastic.SearchResult, 0)
}
for _, fr := range filtered {
for _, result := range fr.Results {
sort.Strings(filterOutCUSources)
withoutCarouselDuplications := []*elastic.SearchHit{}
var maxScore float64
for _, hit := range result.Hits.Hits {
var src es.Result
err = json.Unmarshal(*hit.Source, &src)
if err != nil {
log.Errorf("ESEngine.DoSearch - cannot unmarshal source for hit '%v'.", hit.Id)
continue
}
if src.ResultType == consts.ES_RESULT_TYPE_UNITS {
hitSources, err := es.KeyValuesToValues(consts.ES_UID_TYPE_SOURCE, src.TypedUids)
if err != nil {
log.Errorf("ESEngine.DoSearch - cannot read TypedUids for hit '%v'.", hit.Id)
continue
}
sort.Strings(hitSources)
if len(utils.IntersectSortedStringSlices(hitSources, filterOutCUSources)) > 0 {
// We remove the hits we recieved from 'filter grammar' that are duplicate the existed items inside carousels
log.Infof("Remove CU hit from 'filter grammar' that duplicates carousels source: %v", src.MDB_UID)
} else {
if hit.Score != nil {
maxScore = math.Max(*hit.Score, maxScore)
}
withoutCarouselDuplications = append(withoutCarouselDuplications, hit)
}
} else {
withoutCarouselDuplications = append(withoutCarouselDuplications, hit)
}
}
result.Hits.Hits = withoutCarouselDuplications
result.Hits.MaxScore = &maxScore
result.Hits.TotalHits = int64(len(withoutCarouselDuplications))
}
}
// Note:
// Below we handle 2 result types from a different elastic queries: grammar based results and regular results.
// Changes we made to the scores that is based on the reliance to the results of another type
// can potentially break in some way the uniqueness of results for each page (page 2 may contain a result from page 1).
// Also the logic of boosting results that identical to both types has a limited effect
// since we we are not checking identification in all results but only in the results we received according to page filter.
// Ideal solution for these issues is to handle all score calculations for both types within a single elastic query.
if maxRegularScore != nil && *maxRegularScore >= 15 { // if we have big enough regular scores, we should increase or decrease the filtered results scores
var filteredMaxScore float64
for _, fr := range filtered {
for _, result := range fr.Results {
for _, hit := range result.Hits.Hits {
if hit.Score != nil {
filteredMaxScore = math.Max(*hit.Score, filteredMaxScore)
}
}
}
}
for _, fr := range filtered {
for _, result := range fr.Results {
var maxScore float64
boost := ((*maxRegularScore * 0.9) + 10) / filteredMaxScore
// Why we add +10 to the formula:
// In some cases we have several regular results with a very close scores that above 90% of the maxRegularScore.
// Since the top score for the best 'filter grammar' result is 90% of the maxRegularScore,
// we have cases where the best 'filter grammar' result will be below the high regular results with a VERY SMALL GAP between them.
// To minimize this gap, we add +10 to the formula.
// e.g. search of term "ביטול קטעי מקור" without adding 10 bring the relevant result in position #4. With adding 10, the relevant result is the first.
for _, hit := range result.Hits.Hits {
replaced := false
for _, p := range programsToReplaceWithGrammarResults {
if p.grammarHitId != nil && *p.grammarHitId == hit.Id {
replaced = true
break
}
}
if !replaced && hit.Score != nil {
*hit.Score *= boost
}
maxScore = math.Max(*hit.Score, maxScore)
result.Hits.MaxScore = &maxScore
}
}
}
}
for _, result := range resultsByLang[lang] {
for _, hit := range result.Hits.Hits {
if hit.Score != nil {
if len(programsToReplaceWithGrammarResults) > 0 {
// Assign results score to zero if the results are to be replaced by program grammar
for i := 0; i < programToReplaceIndex; i++ {
if hit.Id == programsToReplaceWithGrammarResults[i].hitId {
log.Infof("Setting zero score for %s.", hit.Id)
zero := 0.0
hit.Score = &zero
break
}
}
}
for _, fr := range filtered {
if _, hasId := fr.HitIdsMap[hit.Id]; hasId {
log.Infof("Same hit found for both regular and grammar filtered results: %v", hit.Id)
if hit.Score != nil && *hit.Score > 5 { // We will increment the score only if the result is relevant enough (score > 5)
*hit.Score += consts.FILTER_GRAMMAR_INCREMENT_FOR_MATCH_TO_FULL_TERM
}
if !fr.PreserveTermForHighlight {
// We remove this hit id from HitIdsMap in order to highlight the original search term and not $Text val.
delete(fr.HitIdsMap, hit.Id)
}
}
}
}
}
}
for _, fr := range filtered {
resultsByLang[lang] = append(resultsByLang[lang], fr.Results...)
}
}
var currentLang string
results := make([]*elastic.SearchResult, 0)
for _, lang := range query.LanguageOrder {
if r, ok := resultsByLang[lang]; ok {
if shouldMergeResults {
results = append(results, resultsByLang[lang]...)
} else {
if len(r) > 0 {
results = r
currentLang = lang
break