/
grammar_engine.go
186 lines (174 loc) · 6.49 KB
/
grammar_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
package search
import (
"fmt"
"sort"
"strings"
"time"
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/utils"
)
type FilterValue struct {
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
Origin string `json:"origin,omitempty"`
OriginFull string `json:"origin_full,omitempty"`
}
type GrammarIntent struct {
LandingPage string `json:"landing_page,omitempty"`
FilterValues []FilterValue `json:"filter_values,omitempty"`
Score float64 `json:"score,omitempty"`
Explanation *elastic.SearchExplanation `json:"explanation,omitempty"`
SingleHit *elastic.SearchHit `json:"single_hit,omitempty"`
SingleHitMdbUid *string `json:"single_hit_mdb_uid,omitempty"`
}
func (e *ESEngine) SuggestGrammars(query *Query) (map[string][]VariablesByPhrase, error) {
suggests := make(map[string][]VariablesByPhrase)
if query.Term != "" && len(query.ExactTerms) > 0 {
// Will never match any grammar for query having simple terms and exact terms.
// This is not acurate but an edge case. Need to better think of query representation.
log.Infof("Both term and exact terms are defined, should not trigger: [%s] [%s]", query.Term, strings.Join(query.ExactTerms, " - "))
return suggests, nil
}
for _, language := range query.LanguageOrder {
if grammarByIntent, ok := e.grammars[language]; ok {
for grammarKey, grammar := range grammarByIntent {
start := time.Now()
grammarSuggest, err := grammar.SuggestGrammar(query, e.TokensCache, e.cache)
elapsed := time.Since(start)
if elapsed > 10*time.Millisecond {
fmt.Printf("%s-%s - %s\n", language, grammarKey, elapsed.String())
}
if err != nil {
return nil, err
}
if len(grammarSuggest) > 0 {
suggests[language] = append(suggests[language], grammarSuggest)
}
}
}
}
return suggests, nil
}
func (g *Grammar) SuggestGrammar(query *Query, tc *TokensCache, cm cache.CacheManager) (VariablesByPhrase, error) {
simpleQuery := query.Term
if simpleQuery == "" && len(query.ExactTerms) == 1 {
simpleQuery = query.ExactTerms[0]
}
// TODO: Tokenization is call to elastic. We can do this in parallel for all languages.
// Consider extracting up the generation of Tokens.
simpleQueryTokens, err := MakeTokensFromPhrase(simpleQuery, g.Language, g.Esc, tc)
if err != nil {
return VariablesByPhrase(nil), errors.Wrapf(err, "Error tokenizing simpleQuery: [%s] in %s.", simpleQuery, g.Language)
}
// Should filter variables by phrase here! By fetching from DB and checking item
// existense.
start := time.Now()
variablesByPhrase, err := TokensSearch(simpleQueryTokens, g.Patterns, g.Variables)
elapsed := time.Since(start)
if elapsed > 10*time.Millisecond {
fmt.Printf("TokenSearch - %s\n", elapsed.String())
}
if err != nil {
return variablesByPhrase, err
}
GrammarFilterVariablesMatch(g.Intent, variablesByPhrase, cm)
return variablesByPhrase, nil
}
func (e *ESEngine) SearchGrammars(query *Query) ([]Intent, error) {
intents := []Intent{}
if query.Term != "" && len(query.ExactTerms) > 0 {
// Will never match any grammar for query having simple terms and exact terms.
// This is not acurate but an edge case. Need to better think of query representation.
log.Infof("Both term and exact terms are defined, should not trigger: [%s] [%s]", query.Term, strings.Join(query.ExactTerms, " - "))
return intents, nil
}
for _, language := range query.LanguageOrder {
if grammarByIntent, ok := e.grammars[language]; ok {
for _, grammar := range grammarByIntent {
intent, err := grammar.SearchGrammar(query, e.TokensCache, e.cache)
if err != nil {
return []Intent{}, err
}
if intent != nil {
intents = append(intents, *intent)
}
}
}
}
return intents, nil
}
func VariableValuesToFilterValues(values []VariableValue) []FilterValue {
ret := []FilterValue{}
for i := range values {
// TODO: Actually map the variable names to filter names and variable values to filter values.
// Maybe this should be done in frontend...
filterName, ok := consts.VARIABLE_TO_FILTER[values[i].Name]
if !ok {
filterName = values[i].Name
}
ret = append(ret, FilterValue{
Name: filterName,
Value: values[i].Value,
Origin: values[i].Origin,
OriginFull: values[i].OriginFull,
})
}
return ret
}
func (g *Grammar) SearchGrammar(query *Query, tc *TokensCache, cm cache.CacheManager) (*Intent, error) {
// Check filters match, i.e., existing query filter match at least one supported grammar intent filter.
if len(query.Filters) > 0 {
common := false
for filterName, values := range query.Filters {
sort.Strings(values)
if grammarValues, ok := g.Filters[filterName]; ok {
sort.Strings(grammarValues)
if len(utils.IntersectSortedStringSlices(values, grammarValues)) > 0 {
common = true
break
}
}
}
if !common {
// No matching filter found, should not trigger intent.
log.Infof("No common filters for intent %s: %+v vs %+v", g.Intent, query.Filters, g.Filters)
return nil, nil
}
}
simpleQuery := query.Term
if simpleQuery == "" && len(query.ExactTerms) == 1 {
simpleQuery = query.ExactTerms[0]
}
// TODO: Tokenization is call to elastic. We can do this in parallel for all languages.
// Consider extracting up the generation of Tokens.
simpleQueryTokens, err := MakeTokensFromPhrase(simpleQuery, g.Language, g.Esc, tc)
if err != nil {
return nil, errors.Wrapf(err, "Error tokenizing simpleQuery: [%s] in %s.", simpleQuery, g.Language)
}
if match, values, _, err := TokensMatch(simpleQueryTokens, g.Patterns, false, g.Variables); err != nil {
return nil, err
} else if match {
vMap := make(map[string][]string)
for _, variableValue := range values {
vMap[variableValue.Name] = append(vMap[variableValue.Name], variableValue.Value)
}
if GrammarVariablesMatch(g.Intent, vMap, cm) {
// If this varibale map match any data, return intent.
// Uncomment for debug:
// log.Infof("Matched search [%s] for grammar %s, intent %s for %s. Pattern: %s", query.Original, g.HitType, g.Intent, g.Language, pattern)
return &Intent{
Type: consts.GRAMMAR_TYPE_LANDING_PAGE,
Language: g.Language,
Value: GrammarIntent{
LandingPage: g.Intent,
FilterValues: VariableValuesToFilterValues(values),
},
}, nil
}
}
return nil, nil
}