-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
452 lines (418 loc) · 14.9 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
package search
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"math"
"net/url"
"time"
log "github.com/Sirupsen/logrus"
"github.com/golang/sync/errgroup"
"github.com/pkg/errors"
"gopkg.in/olivere/elastic.v5"
"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
// TODO: Is mdb required here?
mdb *sql.DB
}
var classTypes = [...]string{"source", "tag"}
// TODO: All interactions with ES should be throttled to prevent downstream pressure
func NewESEngine(esc *elastic.Client, db *sql.DB) *ESEngine {
return &ESEngine{esc: esc, mdb: db}
}
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) (interface{}, error) {
// Figure out index names from language order.
indices := make([]string, len(query.LanguageOrder))
for i := range query.LanguageOrder {
indices[i] = es.IndexName("prod", consts.ES_CLASSIFICATIONS_INDEX, query.LanguageOrder[i])
}
// We call ES in parallel. Each call with a different context query
// (classification type), i.e, tag, source, author...
g, ctx := errgroup.WithContext(ctx)
resp := make([]*elastic.SearchResult, 0)
for i := range classTypes {
classType := classTypes[i]
g.Go(func() error {
// Create MultiSearch request
multiSearchService := e.esc.MultiSearch()
for _, index := range indices {
searchSource := elastic.NewSearchSource().
Suggester(elastic.NewCompletionSuggester("classification_name").
Field("name_suggest").
Text(query.Term).
ContextQuery(elastic.NewSuggesterCategoryQuery("classification", classType))).
Suggester(elastic.NewCompletionSuggester("classification_description").
Field("description_suggest").
Text(query.Term).
ContextQuery(elastic.NewSuggesterCategoryQuery("classification", classType)))
request := elastic.NewSearchRequest().
SearchSource(searchSource).
Index(index)
multiSearchService.Add(request)
}
// Actual call to elastic
mr, err := multiSearchService.Do(ctx)
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 {
log.Warnf("ES suggestions %s: ctx cancelled", classType)
return nil
}
}
return errors.Wrapf(err, "ES suggestions %s", classType)
}
// 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]
}
resp = append(resp, sRes)
return nil
})
}
// Wait for first deadly error or all goroutines to finish
if err := g.Wait(); err != nil {
return nil, errors.Wrap(err, "ES error")
}
return resp, nil
}
func createContentUnitsQuery(q Query) elastic.Query {
boolQuery := elastic.NewBoolQuery()
if q.Term != "" {
boolQuery = boolQuery.Must(
// Don't calculate score here, as we use sloped score below.
elastic.NewConstantScoreQuery(
elastic.NewBoolQuery().Should(
elastic.NewMatchQuery("name.analyzed", q.Term),
elastic.NewMatchQuery("description.analyzed", q.Term),
elastic.NewMatchQuery("transcript.analyzed", q.Term),
).MinimumNumberShouldMatch(1),
).Boost(0.0),
).Should(
elastic.NewDisMaxQuery().Query(
elastic.NewMatchPhraseQuery("name.analyzed", q.Term).Slop(100).Boost(2.0),
elastic.NewMatchPhraseQuery("description.analyzed", q.Term).Slop(100).Boost(1.2),
elastic.NewMatchPhraseQuery("transcript.analyzed", q.Term).Slop(100),
),
)
}
for _, exactTerm := range q.ExactTerms {
boolQuery = boolQuery.Must(
// Don't calculate score here, as we use sloped score below.
elastic.NewConstantScoreQuery(
elastic.NewBoolQuery().Should(
elastic.NewMatchPhraseQuery("name", exactTerm),
elastic.NewMatchPhraseQuery("description", exactTerm),
elastic.NewMatchPhraseQuery("transcript", exactTerm),
).MinimumNumberShouldMatch(1),
).Boost(0.0),
).Should(
elastic.NewDisMaxQuery().Query(
elastic.NewMatchPhraseQuery("name", exactTerm).Slop(100).Boost(2.0),
elastic.NewMatchPhraseQuery("description", exactTerm).Slop(100).Boost(1.2),
elastic.NewMatchPhraseQuery("transcript", exactTerm).Slop(100),
),
)
}
contentTypeQuery := elastic.NewBoolQuery().MinimumNumberShouldMatch(1)
filterByContentType := false
for filter, values := range q.Filters {
s := make([]interface{}, len(values))
for i, v := range values {
s[i] = v
}
switch filter {
case consts.FILTERS[consts.FILTER_START_DATE]:
boolQuery.Filter(elastic.NewRangeQuery("effective_date").Gte(values[0]).Format("yyyy-MM-dd"))
case consts.FILTERS[consts.FILTER_END_DATE]:
boolQuery.Filter(elastic.NewRangeQuery("effective_date").Lte(values[0]).Format("yyyy-MM-dd"))
case consts.FILTERS[consts.FILTER_UNITS_CONTENT_TYPES], consts.FILTERS[consts.FILTER_COLLECTIONS_CONTENT_TYPES]:
contentTypeQuery.Should(elastic.NewTermsQuery(filter, s...))
filterByContentType = true
default:
boolQuery.Filter(elastic.NewTermsQuery(filter, s...))
}
if filterByContentType {
boolQuery.Filter(contentTypeQuery)
}
}
var query elastic.Query
query = boolQuery
if q.Term == "" && len(q.ExactTerms) == 0 {
// No potential score from string matching.
query = elastic.NewConstantScoreQuery(boolQuery).Boost(1.0)
}
return elastic.NewFunctionScoreQuery().Query(query).ScoreMode("sum").MaxBoost(100.0).
AddScoreFunc(elastic.NewWeightFactorFunction(3.0)).
AddScoreFunc(elastic.NewGaussDecayFunction().FieldName("effective_date").Decay(0.9).Scale("300d"))
}
func AddContentUnitsSearchRequests(mss *elastic.MultiSearchService, query Query, sortBy string, from int, size int, preference string) {
content_units_indices := make([]string, len(query.LanguageOrder))
for i := range query.LanguageOrder {
content_units_indices[i] = es.IndexName("prod", consts.ES_UNITS_INDEX, query.LanguageOrder[i])
}
fetchSourceContext := elastic.NewFetchSourceContext(true).
Include("mdb_uid", "effective_date")
for _, index := range content_units_indices {
searchSource := elastic.NewSearchSource().
Query(createContentUnitsQuery(query)).
Highlight(elastic.NewHighlight().HighlighterType("unified").Fields(
elastic.NewHighlighterField("name").NumOfFragments(0),
elastic.NewHighlighterField("description"),
elastic.NewHighlighterField("transcript"),
elastic.NewHighlighterField("name.analyzed").NumOfFragments(0),
elastic.NewHighlighterField("description.analyzed"),
elastic.NewHighlighterField("transcript.analyzed"),
)).
FetchSourceContext(fetchSourceContext).
From(from).
Size(size).
Explain(query.Deb)
switch sortBy {
case consts.SORT_BY_OLDER_TO_NEWER:
searchSource = searchSource.Sort("effective_date", true)
case consts.SORT_BY_NEWER_TO_OLDER:
searchSource = searchSource.Sort("effective_date", false)
}
request := elastic.NewSearchRequest().
SearchSource(searchSource).
Index(index).
Preference(preference)
mss.Add(request)
}
}
func createCollectionsQuery(q Query) elastic.Query {
boolQuery := elastic.NewBoolQuery()
if q.Term != "" {
boolQuery = boolQuery.Must(
// Don't calculate score here, as we use sloped score below.
elastic.NewConstantScoreQuery(
elastic.NewBoolQuery().Should(
elastic.NewMatchQuery("name.analyzed", q.Term),
elastic.NewMatchQuery("description.analyzed", q.Term),
).MinimumNumberShouldMatch(1),
).Boost(0.0),
).Should(
elastic.NewDisMaxQuery().Query(
elastic.NewMatchPhraseQuery("name.analyzed", q.Term).Slop(100).Boost(2.0),
elastic.NewMatchPhraseQuery("description.analyzed", q.Term).Slop(100),
),
)
}
for _, exactTerm := range q.ExactTerms {
boolQuery = boolQuery.Must(
// Don't calculate score here, as we use sloped score below.
elastic.NewConstantScoreQuery(
elastic.NewBoolQuery().Should(
elastic.NewMatchPhraseQuery("name", exactTerm),
elastic.NewMatchPhraseQuery("description", exactTerm),
).MinimumNumberShouldMatch(1),
).Boost(0.0),
).Should(
elastic.NewDisMaxQuery().Query(
elastic.NewMatchPhraseQuery("name", exactTerm).Slop(100).Boost(2.0),
elastic.NewMatchPhraseQuery("description", exactTerm).Slop(100),
),
)
}
contentTypeQuery := elastic.NewBoolQuery().MinimumNumberShouldMatch(1)
filterByContentType := false
for filter, values := range q.Filters {
s := make([]interface{}, len(values))
for i, v := range values {
s[i] = v
}
switch filter {
case consts.FILTERS[consts.FILTER_START_DATE]:
boolQuery.Filter(elastic.NewRangeQuery("effective_date").Gte(values[0]).Format("yyyy-MM-dd"))
case consts.FILTERS[consts.FILTER_END_DATE]:
boolQuery.Filter(elastic.NewRangeQuery("effective_date").Lte(values[0]).Format("yyyy-MM-dd"))
case consts.FILTERS[consts.FILTER_UNITS_CONTENT_TYPES]:
// Skip, do nothing (filtring on content units).
case consts.FILTERS[consts.FILTER_COLLECTIONS_CONTENT_TYPES]:
contentTypeQuery.Should(elastic.NewTermsQuery("content_type", s...))
filterByContentType = true
default:
boolQuery.Filter(elastic.NewTermsQuery(filter, s...))
}
if filterByContentType {
boolQuery.Filter(contentTypeQuery)
}
}
var query elastic.Query
query = boolQuery
if q.Term == "" && len(q.ExactTerms) == 0 {
// No potential score from string matching.
query = elastic.NewConstantScoreQuery(boolQuery).Boost(1.0)
}
return elastic.NewFunctionScoreQuery().Query(query).ScoreMode("sum").MaxBoost(100.0).
Boost(1.4). // Boost collections index.
AddScoreFunc(elastic.NewWeightFactorFunction(3.0)).
AddScoreFunc(elastic.NewGaussDecayFunction().FieldName("effective_date").Decay(0.9).Scale("300d"))
}
func AddCollectionsSearchRequests(mss *elastic.MultiSearchService, query Query, sortBy string, from int, size int, preference string) {
collections_indices := make([]string, len(query.LanguageOrder))
for i := range query.LanguageOrder {
collections_indices[i] = es.IndexName("prod", consts.ES_COLLECTIONS_INDEX, query.LanguageOrder[i])
}
fetchSourceContext := elastic.NewFetchSourceContext(true).
Include("mdb_uid", "effective_date")
for _, index := range collections_indices {
searchSource := elastic.NewSearchSource().
Query(createCollectionsQuery(query)).
Highlight(elastic.NewHighlight().HighlighterType("unified").Fields(
elastic.NewHighlighterField("name").NumOfFragments(0),
elastic.NewHighlighterField("description"),
elastic.NewHighlighterField("name.analyzed").NumOfFragments(0),
elastic.NewHighlighterField("description.analyzed"),
)).
FetchSourceContext(fetchSourceContext).
From(from).
Size(size).
Explain(query.Deb)
switch sortBy {
case consts.SORT_BY_OLDER_TO_NEWER:
searchSource = searchSource.Sort("effective_date", true)
case consts.SORT_BY_NEWER_TO_OLDER:
searchSource = searchSource.Sort("effective_date", false)
}
request := elastic.NewSearchRequest().
SearchSource(searchSource).
Index(index).
Preference(preference)
mss.Add(request)
}
}
func haveHits(r *elastic.SearchResult) bool {
return r != nil && r.Hits != nil && r.Hits.Hits != nil && len(r.Hits.Hits) > 0
}
func compareHits(h1 *elastic.SearchHit, h2 *elastic.SearchHit, sortBy string) (bool, error) {
if sortBy == consts.SORT_BY_RELEVANCE {
return *(h1.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 {
return !ed1.EffectiveDate.Time.After(ed2.EffectiveDate.Time), nil
} else {
return ed1.EffectiveDate.Time.After(ed2.EffectiveDate.Time), nil
}
}
}
func joinResponses(r1 *elastic.SearchResult, r2 *elastic.SearchResult, sortBy string, from int, size int) (*elastic.SearchResult, error) {
log.Infof("%+v %+v", r1, r2)
if r1.Hits.TotalHits == 0 {
r2.Hits.Hits = r2.Hits.Hits[from:utils.Min(from+size, len(r2.Hits.Hits))]
return r2, nil
} else if r2.Hits.TotalHits == 0 {
r1.Hits.Hits = r1.Hits.Hits[from:utils.Min(from+size, len(r1.Hits.Hits))]
return r1, nil
}
result := elastic.SearchResult(*r1)
result.Hits.TotalHits += r2.Hits.TotalHits
if sortBy == consts.SORT_BY_RELEVANCE {
result.Hits.MaxScore = new(float64)
*result.Hits.MaxScore = math.Max(*result.Hits.MaxScore, *r2.Hits.MaxScore)
}
var hits []*elastic.SearchHit
// Merge using compareHits
i1, i2 := int(0), int(0)
for i1 < len(r1.Hits.Hits) || i2 < len(r2.Hits.Hits) {
if i1 == len(r1.Hits.Hits) {
hits = append(hits, r2.Hits.Hits[i2:]...)
break
}
if i2 == len(r2.Hits.Hits) {
hits = append(hits, r1.Hits.Hits[i1:]...)
break
}
h1Larger, err := compareHits(r1.Hits.Hits[i1], r2.Hits.Hits[i2], sortBy)
if err != nil {
return nil, err
}
if h1Larger {
hits = append(hits, r1.Hits.Hits[i1])
i1++
} else {
hits = append(hits, r2.Hits.Hits[i2])
i2++
}
}
result.Hits.Hits = hits[from:utils.Min(from+size, len(hits))]
return &result, nil
}
func (e *ESEngine) DoSearch(ctx context.Context, query Query, sortBy string, from int, size int, preference string) (*elastic.SearchResult, error) {
log.Infof("Query: %+v sort by: %s, from: %d, size: %d", query, sortBy, from, size)
multiSearchService := e.esc.MultiSearch()
// Content Units
AddContentUnitsSearchRequests(multiSearchService, query, sortBy, 0, from+size, preference)
// Collections
AddCollectionsSearchRequests(multiSearchService, query, sortBy, 0, from+size, preference)
// Do search.
mr, err := multiSearchService.Do(context.TODO())
if err != nil {
return nil, errors.Wrap(err, "ES error.")
}
if len(mr.Responses) != 2*len(query.LanguageOrder) {
return nil, errors.New(fmt.Sprintf("Unexpected number of results %d, expected %d",
len(mr.Responses), 2*len(query.LanguageOrder)))
}
// Interleave content units and collection results by language.
// Then go over responses and choose first not empty retults list.
for i := 0; i < len(query.LanguageOrder); i++ {
cuR := mr.Responses[i]
cR := mr.Responses[i+len(query.LanguageOrder)]
if cuR.Error != nil {
log.Warnf("%+v", cuR.Error)
return nil, errors.New("Failed multi get.")
}
if cR.Error != nil {
log.Warnf("%+v", cR.Error)
return nil, errors.New("Failed multi get.")
}
if haveHits(cuR) || haveHits(cR) {
log.Debugf("Joining:\n%+v\n\n%+v\n\n\n", cuR.Hits, cR.Hits)
ret, err := joinResponses(cuR, cR, sortBy, from, size)
log.Debugf("Res: %+v", ret.Hits)
return ret, err
}
}
if len(mr.Responses) > 0 {
return mr.Responses[0], nil
} else {
return nil, errors.Wrap(err, "No responses from multi search.")
}
}