-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
312 lines (288 loc) · 11.9 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
package search
import (
"fmt"
"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"
)
const (
// Content boost.
TITLE_BOOST = 2.0
DESCRIPTION_BOOST = 1.2
// 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
NUM_SUGGESTS = 500
)
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) {
lastQuote = r
lastQuoteIdx = i
}
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}
}
func createResultsQuery(resultTypes []string, q Query, docIds []string) elastic.Query {
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 q.Term != "" {
boolQuery = boolQuery.Must(
// Don't calculate score here, as we use sloped score below.
elastic.NewConstantScoreQuery(
elastic.NewBoolQuery().Should(
elastic.NewMatchQuery("title.language", q.Term),
elastic.NewMatchQuery("description.language", q.Term),
elastic.NewMatchQuery("content.language", q.Term),
).MinimumNumberShouldMatch(1),
).Boost(0.0),
).Should(
elastic.NewDisMaxQuery().Query(
// Language analyzed
elastic.NewMatchPhraseQuery("title.language", q.Term).Slop(SLOP).Boost(TITLE_BOOST),
elastic.NewMatchPhraseQuery("description.language", q.Term).Slop(SLOP).Boost(DESCRIPTION_BOOST),
elastic.NewMatchPhraseQuery("content.language", q.Term).Slop(SLOP),
// Language analyzed, exact (no slop)
elastic.NewMatchPhraseQuery("title.language", q.Term).Boost(EXACT_BOOST*TITLE_BOOST),
elastic.NewMatchPhraseQuery("description.language", q.Term).Boost(EXACT_BOOST*DESCRIPTION_BOOST),
elastic.NewMatchPhraseQuery("content.language", q.Term).Boost(EXACT_BOOST),
// Standard analyzed
elastic.NewMatchPhraseQuery("title", q.Term).Slop(SLOP).Boost(STANDARD_BOOST*TITLE_BOOST),
elastic.NewMatchPhraseQuery("description", q.Term).Slop(SLOP).Boost(STANDARD_BOOST*DESCRIPTION_BOOST),
elastic.NewMatchPhraseQuery("content", q.Term).Slop(SLOP).Boost(STANDARD_BOOST),
// Standard analyzed, exact (no slop).
elastic.NewMatchPhraseQuery("title", q.Term).Boost(STANDARD_BOOST*EXACT_BOOST*TITLE_BOOST),
elastic.NewMatchPhraseQuery("description", q.Term).Boost(STANDARD_BOOST*EXACT_BOOST*DESCRIPTION_BOOST),
elastic.NewMatchPhraseQuery("content", q.Term).Boost(STANDARD_BOOST*EXACT_BOOST),
),
)
}
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("title", exactTerm),
elastic.NewMatchPhraseQuery("description", exactTerm),
elastic.NewMatchPhraseQuery("content", exactTerm),
).MinimumNumberShouldMatch(1),
).Boost(0.0),
).Should(
elastic.NewDisMaxQuery().Query(
// Language analyzed, exact (no slop)
elastic.NewMatchPhraseQuery("title.language", exactTerm).Boost(EXACT_BOOST*TITLE_BOOST),
elastic.NewMatchPhraseQuery("description.language", exactTerm).Boost(EXACT_BOOST*DESCRIPTION_BOOST),
elastic.NewMatchPhraseQuery("content.language", exactTerm).Boost(EXACT_BOOST),
// Standard analyzed, exact (no slop).
elastic.NewMatchPhraseQuery("title", exactTerm).Boost(STANDARD_BOOST*EXACT_BOOST*TITLE_BOOST),
elastic.NewMatchPhraseQuery("description", exactTerm).Boost(STANDARD_BOOST*EXACT_BOOST*DESCRIPTION_BOOST),
elastic.NewMatchPhraseQuery("content", exactTerm).Boost(STANDARD_BOOST*EXACT_BOOST),
),
)
}
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("first")
for _, resultType := range resultTypes {
weight := 1.0
if resultType == consts.ES_RESULT_TYPE_UNITS {
weight = 1.0
} else if resultType == consts.ES_RESULT_TYPE_TAGS {
weight = 1.5 // We use tags for intents only, score should be same as for sources.
} else if resultType == consts.ES_RESULT_TYPE_SOURCES {
weight = 1.5
} else if resultType == consts.ES_RESULT_TYPE_COLLECTIONS {
weight = 2.0
}
scoreQuery.Add(elastic.NewTermsQuery("result_type", resultType), elastic.NewWeightFactorFunction(weight))
}
return elastic.NewFunctionScoreQuery().Query(scoreQuery.Query(query)).ScoreMode("sum").MaxBoost(100.0).
AddScoreFunc(elastic.NewWeightFactorFunction(2.0)).
AddScoreFunc(elastic.NewGaussDecayFunction().FieldName("effective_date").Decay(0.6).Scale("2000d"))
}
func NewResultsSearchRequest(options SearchRequestOptions) *elastic.SearchRequest {
fetchSourceContext := elastic.NewFetchSourceContext(true).Include("mdb_uid", "result_type", "title")
source := elastic.NewSearchSource().
Query(createResultsQuery(options.resultTypes, options.query, options.docIds)).
FetchSourceContext(fetchSourceContext).
From(options.from).
Size(options.size).
Explain(options.query.Deb)
if options.useHighlight {
// We use special HighlightQuery with SimpleQueryStringQuery to
// solve elastic issue with synonyms and highlights.
highlightQuery := elastic.NewHighlight().Fields(
elastic.NewHighlighterField("title").NumOfFragments(0).HighlightQuery(elastic.NewSimpleQueryStringQuery(options.query.Term)),
elastic.NewHighlighterField("description").HighlightQuery(elastic.NewSimpleQueryStringQuery(options.query.Term)),
elastic.NewHighlighterField("content").HighlightQuery(elastic.NewSimpleQueryStringQuery(options.query.Term)),
elastic.NewHighlighterField("description.language").HighlightQuery(elastic.NewSimpleQueryStringQuery(options.query.Term)),
elastic.NewHighlighterField("content.language").HighlightQuery(elastic.NewSimpleQueryStringQuery(options.query.Term)))
if !options.partialHighlight {
// Following field not used in intents to solve elastic bug with highlight.
highlightQuery.Fields(
elastic.NewHighlighterField("title.language").NumOfFragments(0).HighlightQuery(elastic.NewSimpleQueryStringQuery(options.query.Term)))
}
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)
}
func NewResultsSearchRequests(options SearchRequestOptions) []*elastic.SearchRequest {
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 := NewResultsSearchRequest(options)
requests = append(requests, request)
}
return requests
}
func NewResultsSuggestRequest(resultTypes []string, index string, query Query, preference string) *elastic.SearchRequest {
fetchSourceContext := elastic.NewFetchSourceContext(true).Include("mdb_uid", "result_type", "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),
)
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
}