-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
627 lines (567 loc) · 23.5 KB
/
query.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
package search
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"unicode"
"gopkg.in/olivere/elastic.v6"
"github.com/Bnei-Baruch/archive-backend/consts"
"github.com/Bnei-Baruch/archive-backend/es"
"github.com/Bnei-Baruch/archive-backend/utils"
"github.com/pkg/errors"
)
const (
// Content boost.
TITLE_BOOST = 2.0
DESCRIPTION_BOOST = 1.2
FULL_TITLE_BOOST = 1.1
DEFAULT_BOOST = 1.0
// Max slop.
SLOP = 100
// Following two boosts may be agregated.
// Boost for standard anylyzer, i.e., without stemming.
STANDARD_BOOST = 1.2
// Boost for exact phrase match, without slop.
EXACT_BOOST = 1.5
SPAN_NEAR_BOOST = 0.01
MIN_SCORE_FOR_RESULTS = 0.01
NUM_SUGGESTS = 30
)
type Query struct {
Term string `json:"term,omitempty"`
ExactTerms []string `json:"exact_terms,omitempty"`
Original string `json:"original,omitempty"`
Filters map[string][]string `json:"filters,omitempty"`
LanguageOrder []string `json:"language_order,omitempty"`
Deb bool `json:"deb,omitempty"`
Intents []Intent `json:"intents,omitempty"`
}
func isTokenStart(i int, runes []rune, lastQuote rune) bool {
return i == 0 && !unicode.IsSpace(runes[0]) ||
(i > 0 && !unicode.IsSpace(runes[i]) && unicode.IsSpace(runes[i-1]))
}
func isTokenEnd(i int, runes []rune, lastQuote rune, lastQuoteIdx int) bool {
return i == len(runes)-1 ||
(i < len(runes)-1 && unicode.IsSpace(runes[i+1]) &&
(lastQuote == rune(0) || runes[i] == lastQuote && lastQuoteIdx >= 0 && lastQuoteIdx < i))
}
func isRuneQuotationMark(r rune) bool {
return unicode.In(r, unicode.Quotation_Mark) || r == rune(1523) || r == rune(1524)
}
// Tokenizes string to work with user friendly escapings of quotes (see tests).
func tokenize(str string) []string {
runes := []rune(str)
start := -1
lastQuote := rune(0)
lastQuoteIdx := -1
parts := 0
var tokens []string
for i, r := range runes {
if start == -1 && isTokenStart(i, runes, lastQuote) {
start = i
}
if i == start && lastQuote == rune(0) && isRuneQuotationMark(r) {
for k := i + 1; k < len(runes); k++ { // Make sure we have closing QuotationMark
if isTokenEnd(k, runes, r, i) && isRuneQuotationMark(runes[k]) {
// Closing QuotationMark found
lastQuote = r
lastQuoteIdx = i
break
}
}
}
if start >= 0 && isTokenEnd(i, runes, lastQuote, lastQuoteIdx) {
tokens = append(tokens, string(runes[start:i+1]))
lastQuote = rune(0)
lastQuoteIdx = -1
start = -1
parts += 1
}
}
return tokens
}
// Parses query and extracts terms and filters.
func ParseQuery(q string) Query {
filters := make(map[string][]string)
var terms []string
var exactTerms []string
for _, t := range tokenize(q) {
isFilter := false
for filter := range consts.FILTERS {
prefix := fmt.Sprintf("%s:", filter)
if isFilter = strings.HasPrefix(t, prefix); isFilter {
filters[consts.FILTERS[filter]] = strings.Split(strings.TrimPrefix(t, prefix), ",")
break
}
}
if !isFilter {
// Not clear what kind of decoding is happening here, utf-8?!
runes := []rune(t)
// For debug
// for _, c := range runes {
// fmt.Printf("%04x %s\n", c, string(c))
// }
if len(runes) >= 2 && isRuneQuotationMark(runes[0]) && runes[0] == runes[len(runes)-1] {
exactTerms = append(exactTerms, string(runes[1:len(runes)-1]))
} else {
terms = append(terms, t)
}
}
}
return Query{Term: strings.Join(terms, " "), ExactTerms: exactTerms, Original: q, Filters: filters}
}
// Here we build the span_near query with span_multi sub queries to allow effective fuzzy search
// with slop and special cases like avoiding numeric values from applying fuzziness and handling of single hebrew letter in the query.
// The query is not supported in the elastic SDK so we build it manually.
// Arguments:
// field - the field where we search (title, full_title, description, content).
// term - the search term.
// boost - boost for the score.
// slop - number of words separating the span clauses.
// inOrder - we expect the words to be in order? We set it as true only for the search in title.
func createSpanNearQuery(field string, term string, boost float32, slop int, inOrder bool) (elastic.Query, error) {
clauses := make([]string, 0)
spanNearMask := `{"span_near": { "clauses": [%s], "slop": %d, "boost": %f, "in_order": %t } }`
clauseMask := `{"span_multi": { "match": { "fuzzy": { "%s": { "value": "%s", "fuzziness": %s, "transpositions": %s } } } } }`
splitted := strings.Fields(term)
for _, t := range splitted {
if t == "<" || t == ">" || t == "-" {
continue
}
fuzzines := `"AUTO"` // Default.
transpositions := "true" // Default.
runes := []rune(t)
_, convertToIntErr := strconv.Atoi(t)
if convertToIntErr == nil || (len(runes) == 3 && runes[1] == '"') || (len(runes) == 4 && runes[2] == '"') {
// We dont use fuzzines for numeric values (number or hebrew numeric representation like מ"ג)
fuzzines = "0"
} else if len(runes) == 1 && runes[0] >= 'א' && runes[0] <= 'ת' {
// This logic allows finding single hebrew letter with ' symbol without the mention of the ' symbol.
// The solution is not perfect for all times. In some (rare) cases the letter may be replaced with another letter: ג' קווים - ד
fuzzines = "1"
transpositions = "false" // Limit the fuzzines not to include transpositions of two adjacent characters (ח' -> 'ח). Maybe not required.
}
b, err := json.Marshal(t)
if err != nil {
return nil, errors.Wrap(err, "createSpanNearQuery")
}
// Trim the beginning and trailing " character
esc := string(b[1 : len(b)-1])
clause := fmt.Sprintf(clauseMask, field, esc, fuzzines, transpositions)
clauses = append(clauses, clause)
}
clausesStr := strings.Join(clauses, ",")
queryStr := fmt.Sprintf(spanNearMask, clausesStr, slop, boost, inOrder)
//fmt.Printf("SpanNear Query: %s\n", queryStr)
query := elastic.NewRawStringQuery(queryStr)
return query, nil
}
// Creates a result query for elastic.
// resultTypes - list of search result types: sources, topics, CU's, etc..
// docIds - optional list of _uid's for filtering the search. If the parameter value is nil, no filtering is applied. Used for highlight search.
// filterOutCUSources - optional list of sources for which we want to filter out the CU's that connected to those sources
// (in order to avoid duplication between carousel and regular results).
// titlesOnly - limit our search only to title fields: title, full_title and description in case we search for intent sources. Used for intent search.
func createResultsQuery(resultTypes []string, q Query, docIds []string, filterOutCUSources []string, titlesOnly bool) (elastic.Query, error) {
boolQuery := elastic.NewBoolQuery().Must(
elastic.NewConstantScoreQuery(
elastic.NewTermsQuery("result_type", utils.ConvertArgsString(resultTypes)...),
).Boost(0.0),
)
if docIds != nil && len(docIds) > 0 {
idsQuery := elastic.NewIdsQuery().Ids(docIds...)
boolQuery.Filter(idsQuery)
}
if len(filterOutCUSources) > 0 {
rtForMustNotQuery := elastic.NewTermsQuery(consts.ES_RESULT_TYPE, consts.ES_RESULT_TYPE_UNITS)
for _, src := range filterOutCUSources {
sourceForMustNotQuery := elastic.NewTermsQuery("typed_uids", fmt.Sprintf("%s:%s", consts.FILTER_SOURCE, src))
innerBoolQuery := elastic.NewBoolQuery().Filter(sourceForMustNotQuery, rtForMustNotQuery)
boolQuery.MustNot(innerBoolQuery)
}
}
// We append description for intent sources search because the description is commonly used as subtitle
appendDecription := !titlesOnly || (len(resultTypes) == 1 && resultTypes[0] == consts.ES_RESULT_TYPE_SOURCES)
if q.Term != "" {
constantScoreQueries := []elastic.Query{
elastic.NewMatchQuery("title.language", q.Term),
elastic.NewMatchQuery("full_title.language", q.Term),
}
if appendDecription {
constantScoreQueries = append(constantScoreQueries,
elastic.NewMatchQuery("description.language", q.Term),
)
}
if !titlesOnly {
constantScoreQueries = append(constantScoreQueries,
elastic.NewMatchQuery("content.language", q.Term),
)
}
disMaxQueries := []elastic.Query{
// Language analyzed
elastic.NewMatchPhraseQuery("title.language", q.Term).Slop(SLOP).Boost(TITLE_BOOST),
elastic.NewMatchPhraseQuery("full_title.language", q.Term).Slop(SLOP).Boost(FULL_TITLE_BOOST),
// Language analyzed, exact (no slop)
elastic.NewMatchPhraseQuery("title.language", q.Term).Boost(EXACT_BOOST * TITLE_BOOST),
elastic.NewMatchPhraseQuery("full_title.language", q.Term).Boost(EXACT_BOOST * FULL_TITLE_BOOST),
// Standard analyzed
elastic.NewMatchPhraseQuery("title", q.Term).Slop(SLOP).Boost(STANDARD_BOOST * TITLE_BOOST),
elastic.NewMatchPhraseQuery("full_title", q.Term).Slop(SLOP).Boost(STANDARD_BOOST * FULL_TITLE_BOOST),
// Standard analyzed, exact (no slop).
elastic.NewMatchPhraseQuery("title", q.Term).Boost(STANDARD_BOOST * EXACT_BOOST * TITLE_BOOST),
elastic.NewMatchPhraseQuery("full_title", q.Term).Boost(STANDARD_BOOST * EXACT_BOOST * FULL_TITLE_BOOST),
}
// Language analyzed
snq, err := createSpanNearQuery("title.language", q.Term, TITLE_BOOST*SPAN_NEAR_BOOST, SLOP, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
snq, err = createSpanNearQuery("full_title.language", q.Term, FULL_TITLE_BOOST*SPAN_NEAR_BOOST, SLOP, false)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
// Language analyzed, exact (no slop)
snq, err = createSpanNearQuery("title.language", q.Term, EXACT_BOOST*TITLE_BOOST*SPAN_NEAR_BOOST, 0, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
snq, err = createSpanNearQuery("full_title.language", q.Term, EXACT_BOOST*FULL_TITLE_BOOST*SPAN_NEAR_BOOST, 0, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
// Standard analyzed
snq, err = createSpanNearQuery("title", q.Term, STANDARD_BOOST*TITLE_BOOST*SPAN_NEAR_BOOST, SLOP, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
snq, err = createSpanNearQuery("full_title", q.Term, STANDARD_BOOST*FULL_TITLE_BOOST*SPAN_NEAR_BOOST, SLOP, false)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
// Standard analyzed, exact (no slop).
snq, err = createSpanNearQuery("title", q.Term, STANDARD_BOOST*EXACT_BOOST*TITLE_BOOST*SPAN_NEAR_BOOST, 0, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
snq, err = createSpanNearQuery("full_title", q.Term, STANDARD_BOOST*EXACT_BOOST*FULL_TITLE_BOOST*SPAN_NEAR_BOOST, 0, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
if appendDecription {
disMaxQueries = append(disMaxQueries,
// Language analyzed
elastic.NewMatchPhraseQuery("description.language", q.Term).Slop(SLOP).Boost(DESCRIPTION_BOOST),
// Language analyzed, exact (no slop)
elastic.NewMatchPhraseQuery("description.language", q.Term).Boost(EXACT_BOOST*DESCRIPTION_BOOST),
// Standard analyzed
elastic.NewMatchPhraseQuery("description", q.Term).Slop(SLOP).Boost(STANDARD_BOOST*DESCRIPTION_BOOST),
// Standard analyzed, exact (no slop).
elastic.NewMatchPhraseQuery("description", q.Term).Boost(STANDARD_BOOST*EXACT_BOOST*DESCRIPTION_BOOST),
)
// Language analyzed
snq, err = createSpanNearQuery("description.language", q.Term, DESCRIPTION_BOOST*SPAN_NEAR_BOOST, SLOP, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
// Language analyzed, exact (no slop)
snq, err = createSpanNearQuery("description.language", q.Term, EXACT_BOOST*DESCRIPTION_BOOST*SPAN_NEAR_BOOST, 0, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
// Standard analyzed
snq, err = createSpanNearQuery("description", q.Term, STANDARD_BOOST*DESCRIPTION_BOOST*SPAN_NEAR_BOOST, SLOP, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
// Standard analyzed, exact (no slop).
snq, err = createSpanNearQuery("description", q.Term, STANDARD_BOOST*EXACT_BOOST*DESCRIPTION_BOOST*SPAN_NEAR_BOOST, 0, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
}
if !titlesOnly {
disMaxQueries = append(disMaxQueries,
// Language analyzed
elastic.NewMatchPhraseQuery("content.language", q.Term).Slop(SLOP),
// Language analyzed, exact (no slop)
elastic.NewMatchPhraseQuery("content.language", q.Term).Boost(EXACT_BOOST),
// Standard analyzed
elastic.NewMatchPhraseQuery("content", q.Term).Slop(SLOP).Boost(STANDARD_BOOST),
// Standard analyzed, exact (no slop).
elastic.NewMatchPhraseQuery("content", q.Term).Boost(STANDARD_BOOST*EXACT_BOOST),
)
// Language analyzed
snq, err = createSpanNearQuery("content.language", q.Term, DEFAULT_BOOST*SPAN_NEAR_BOOST, SLOP, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
// Language analyzed, exact (no slop)
snq, err = createSpanNearQuery("content.language", q.Term, EXACT_BOOST*SPAN_NEAR_BOOST, 0, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
// Standard analyzed
snq, err = createSpanNearQuery("content", q.Term, STANDARD_BOOST*SPAN_NEAR_BOOST, SLOP, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
// Standard analyzed, exact (no slop).
snq, err = createSpanNearQuery("content", q.Term, STANDARD_BOOST*EXACT_BOOST*SPAN_NEAR_BOOST, 0, true)
if err != nil {
return nil, err
}
disMaxQueries = append(disMaxQueries, snq)
}
boolQuery = boolQuery.Must(
// Don't calculate score here, as we use sloped score below.
elastic.NewConstantScoreQuery(
elastic.NewBoolQuery().Should(constantScoreQueries...).MinimumNumberShouldMatch(1),
).Boost(0.0),
).Should(
elastic.NewDisMaxQuery().Query(disMaxQueries...),
)
}
for _, exactTerm := range q.ExactTerms {
constantScoreQueries := []elastic.Query{
elastic.NewMatchPhraseQuery("title", exactTerm),
elastic.NewMatchPhraseQuery("full_title", exactTerm),
}
if appendDecription {
constantScoreQueries = append(constantScoreQueries,
elastic.NewMatchPhraseQuery("description", exactTerm),
)
}
if !titlesOnly {
constantScoreQueries = append(constantScoreQueries,
elastic.NewMatchPhraseQuery("content", exactTerm),
)
}
disMaxQueries := []elastic.Query{
// Language analyzed, exact (no slop)
elastic.NewMatchPhraseQuery("title.language", exactTerm).Boost(EXACT_BOOST * TITLE_BOOST),
elastic.NewMatchPhraseQuery("full_title.language", exactTerm).Boost(EXACT_BOOST * FULL_TITLE_BOOST),
// Standard analyzed, exact (no slop).
elastic.NewMatchPhraseQuery("title", exactTerm).Boost(STANDARD_BOOST * EXACT_BOOST * TITLE_BOOST),
elastic.NewMatchPhraseQuery("full_title", exactTerm).Boost(STANDARD_BOOST * EXACT_BOOST * FULL_TITLE_BOOST),
}
if appendDecription {
disMaxQueries = append(disMaxQueries,
// Language analyzed, exact (no slop)
elastic.NewMatchPhraseQuery("description.language", exactTerm).Boost(EXACT_BOOST*DESCRIPTION_BOOST),
// Standard analyzed, exact (no slop).
elastic.NewMatchPhraseQuery("description", exactTerm).Boost(STANDARD_BOOST*EXACT_BOOST*DESCRIPTION_BOOST),
)
}
if !titlesOnly {
disMaxQueries = append(disMaxQueries,
// Language analyzed, exact (no slop)
elastic.NewMatchPhraseQuery("content.language", exactTerm).Boost(EXACT_BOOST),
// Standard analyzed, exact (no slop).
elastic.NewMatchPhraseQuery("content", exactTerm).Boost(STANDARD_BOOST*EXACT_BOOST),
)
}
boolQuery = boolQuery.Must(
// Don't calculate score here, as we use sloped score below.
elastic.NewConstantScoreQuery(
elastic.NewBoolQuery().Should(constantScoreQueries...).MinimumNumberShouldMatch(1),
).Boost(0.0),
).Should(
elastic.NewDisMaxQuery().Query(disMaxQueries...),
)
}
contentTypeQuery := elastic.NewBoolQuery().MinimumNumberShouldMatch(1)
filterByContentType := false
for filter, values := range q.Filters {
s := make([]string, 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_values", es.KeyIValues(filter, s)...))
filterByContentType = true
case consts.FILTERS[consts.FILTER_SECTION_SOURCES]:
boolQuery.Filter(elastic.NewTermsQuery("result_type", consts.ES_RESULT_TYPE_SOURCES))
default:
boolQuery.Filter(elastic.NewTermsQuery("filter_values", es.KeyIValues(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)
}
scoreQuery := elastic.NewFunctionScoreQuery().ScoreMode("multiply")
for _, resultType := range resultTypes {
weight := 1.0
if resultType == consts.ES_RESULT_TYPE_UNITS {
weight = 1.1
} else if resultType == consts.ES_RESULT_TYPE_TAGS {
weight = 2.3 // We use tags for intents only
} else if resultType == consts.ES_RESULT_TYPE_SOURCES {
weight = 1.8
} else if resultType == consts.ES_RESULT_TYPE_COLLECTIONS {
weight = 2.0
}
scoreQuery.Add(elastic.NewTermsQuery("result_type", resultType), elastic.NewWeightFactorFunction(weight))
}
// Reduce score for clips.
scoreQuery.Add(elastic.NewTermsQuery("filter_values", es.KeyValue("content_type", consts.CT_CLIP)), elastic.NewWeightFactorFunction(0.7))
return elastic.NewFunctionScoreQuery().Query(scoreQuery.Query(query).MinScore(MIN_SCORE_FOR_RESULTS)).ScoreMode("sum").MaxBoost(100.0).
AddScoreFunc(elastic.NewWeightFactorFunction(2.0)).
AddScoreFunc(elastic.NewGaussDecayFunction().FieldName("effective_date").Decay(0.6).Scale("2000d")), nil
}
func NewResultsSearchRequest(options SearchRequestOptions) (*elastic.SearchRequest, error) {
fetchSourceContext := elastic.NewFetchSourceContext(true).Include("mdb_uid", "result_type", "effective_date")
titleAdded := false
fullTitleAdded := false
contentAdded := false
// This is a generic imp. that supports searching tweets together with other results.
// Currently we are not searching for tweets together with other results but in parallel.
for _, rt := range options.resultTypes {
if rt == consts.ES_RESULT_TYPE_TWEETS && !contentAdded {
fetchSourceContext.Include("content")
contentAdded = true
} else if rt == consts.ES_RESULT_TYPE_SOURCES && !fullTitleAdded {
fetchSourceContext.Include("full_title")
fullTitleAdded = true
}
if !titleAdded && rt != consts.ES_RESULT_TYPE_TWEETS {
fetchSourceContext.Include("title")
titleAdded = true
}
if contentAdded && titleAdded && fullTitleAdded {
break
}
}
resultsQuery, err := createResultsQuery(options.resultTypes, options.query, options.docIds, options.filterOutCUSources, options.titlesOnly)
if err != nil {
fmt.Printf("Error creating results query: %s", err.Error())
return nil, err
}
source := elastic.NewSearchSource().
Query(resultsQuery).
FetchSourceContext(fetchSourceContext).
From(options.from).
Size(options.size).
Explain(options.query.Deb)
if options.useHighlight {
terms := make([]string, 1)
if options.query.Term != "" {
terms = append(terms, options.query.Term)
} else {
terms = options.query.ExactTerms
}
contentNumOfFragments := 5 // elastic default
if options.highlightFullContent {
contentNumOfFragments = 0
}
highlightQuery := createHighlightQuery(terms, contentNumOfFragments, options.partialHighlight)
source = source.Highlight(highlightQuery)
}
switch options.sortBy {
case consts.SORT_BY_OLDER_TO_NEWER:
source = source.Sort("effective_date", true)
case consts.SORT_BY_NEWER_TO_OLDER:
source = source.Sort("effective_date", false)
}
return elastic.NewSearchRequest().
SearchSource(source).
Index(options.index).
Preference(options.preference), nil
}
func createHighlightQuery(terms []string, n int, partialHighlight bool) *elastic.Highlight {
// We use special HighlightQuery with SimpleQueryStringQuery to
// solve elastic issue with synonyms and highlights.
query := elastic.NewHighlight()
for _, term := range terms {
query.Fields(
elastic.NewHighlighterField("title").NumOfFragments(0).HighlightQuery(elastic.NewSimpleQueryStringQuery(term)),
elastic.NewHighlighterField("full_title").NumOfFragments(0).HighlightQuery(elastic.NewSimpleQueryStringQuery(term)),
elastic.NewHighlighterField("description").HighlightQuery(elastic.NewSimpleQueryStringQuery(term)),
elastic.NewHighlighterField("description.language").HighlightQuery(elastic.NewSimpleQueryStringQuery(term)),
elastic.NewHighlighterField("content").NumOfFragments(n).HighlightQuery(elastic.NewSimpleQueryStringQuery(term)),
elastic.NewHighlighterField("content.language").NumOfFragments(n).HighlightQuery(elastic.NewSimpleQueryStringQuery(term)))
if !partialHighlight {
// Following field not used in intents to solve elastic bug with highlight.
query.Fields(
elastic.NewHighlighterField("title.language").NumOfFragments(0).HighlightQuery(elastic.NewSimpleQueryStringQuery(term)))
}
}
return query
}
func NewResultsSearchRequests(options SearchRequestOptions) ([]*elastic.SearchRequest, error) {
requests := make([]*elastic.SearchRequest, 0)
indices := make([]string, len(options.query.LanguageOrder))
for i := range options.query.LanguageOrder {
indices[i] = es.IndexNameForServing("prod", consts.ES_RESULTS_INDEX, options.query.LanguageOrder[i])
}
for _, index := range indices {
options.index = index
request, err := NewResultsSearchRequest(options)
if err != nil {
return nil, err
}
requests = append(requests, request)
}
return requests, nil
}
func NewResultsSuggestRequest(resultTypes []string, index string, query Query, preference string) *elastic.SearchRequest {
fetchSourceContext := elastic.NewFetchSourceContext(true).Include("mdb_uid", "result_type", "title", "full_title")
searchSource := elastic.NewSearchSource().
FetchSourceContext(fetchSourceContext).
Suggester(
elastic.NewCompletionSuggester("title_suggest").
Field("title_suggest").
Text(query.Term).
ContextQuery(elastic.NewSuggesterCategoryQuery("result_type", resultTypes...)).
Size(NUM_SUGGESTS).
SkipDuplicates(true)).
Suggester(
elastic.NewCompletionSuggester("title_suggest.language").
Field("title_suggest.language").
Text(query.Term).
ContextQuery(elastic.NewSuggesterCategoryQuery("result_type", resultTypes...)).
Size(NUM_SUGGESTS).
SkipDuplicates(true))
return elastic.NewSearchRequest().
SearchSource(searchSource).
Index(index).
Preference(preference)
}
func NewResultsSuggestRequests(resultTypes []string, query Query, preference string) []*elastic.SearchRequest {
requests := make([]*elastic.SearchRequest, 0)
indices := make([]string, len(query.LanguageOrder))
for i := range query.LanguageOrder {
indices[i] = es.IndexNameForServing("prod", consts.ES_RESULTS_INDEX, query.LanguageOrder[i])
}
for _, index := range indices {
request := NewResultsSuggestRequest(resultTypes, index, query, preference)
requests = append(requests, request)
}
return requests
}