-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathquery_validate.go
364 lines (307 loc) · 9.35 KB
/
query_validate.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
// Copyright 2024-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package cbft
import (
"encoding/json"
"fmt"
"strings"
"github.com/blevesearch/bleve/v2"
"github.com/blevesearch/bleve/v2/mapping"
"github.com/blevesearch/bleve/v2/search/query"
"github.com/couchbase/cbgt"
)
// validateSearchRequestAgainstIndex validates the search request against the index.
func validateSearchRequestAgainstIndex(mgr *cbgt.Manager,
indexName, indexUUID string, collections []string,
searchRequest *bleve.SearchRequest) error {
if mgr == nil || len(indexName) == 0 || searchRequest == nil {
return fmt.Errorf("query_validate:"+
" Invalid input parameters - indexName: %s, searchRequest: %v",
indexName, searchRequest)
}
// obtain the index definition
indexDef, _, err := mgr.GetIndexDef(indexName, false)
if err != nil || (len(indexUUID) > 0 && indexDef.UUID != indexUUID) {
return fmt.Errorf("query_validate:"+
" Unable to get index definition or match UUID, err: %v", err)
}
if indexDef.Type != "fulltext-index" {
// validation NOT supported for fulltext-aliases
return nil
}
var collectionsMap map[string]struct{}
if len(collections) > 0 {
// create a map of collections for faster lookup
collectionsMap = make(map[string]struct{})
for _, collection := range collections {
collectionsMap[collection] = struct{}{}
}
}
indexedProperties, err := processIndexDef(indexDef, collectionsMap, nil)
if err != nil {
return fmt.Errorf("query_validate:"+
" Unable to process index definition, err: %v", err)
}
queryFields, err := processSearchRequest(searchRequest)
if err != nil {
return fmt.Errorf("query_validate:"+
" Unable to process search request, err: %v", err)
}
OUTER:
for entry := range queryFields {
if _, exists := indexedProperties[entry]; exists {
// field entry for query found, all good
continue
}
if entry.Type == "geopoint" ||
entry.Type == "geoshape" ||
entry.Type == "IP" ||
entry.Type == "datetime" ||
entry.Type == "vector" {
// strict field types that require non-dynamic mappings
msg := fmt.Sprintf("query_validate:"+
" field not indexed, name: %s, type: %s", entry.Name, entry.Type)
if entry.Type == "vector" {
msg += fmt.Sprintf(", dims: %d", entry.Dims)
}
return fmt.Errorf(msg)
}
// check for dynamic mappings for other field types - "text", "number", "boolean"
if isDynamic, exists := indexedProperties[indexProperty{Name: ""}]; exists && isDynamic {
// complete dynamic mapping enabled
continue OUTER
}
queryFieldSplitOnDot := strings.Split(entry.Name, ".")
if len(queryFieldSplitOnDot) == 1 {
// no need to check for dynamic mappings
return fmt.Errorf("query_validate:"+
" field not indexed, name: %s, type: %s", entry.Name, entry.Type)
}
for i := 0; i < len(queryFieldSplitOnDot)-1; i++ {
dynamicField := strings.Join(queryFieldSplitOnDot[:i+1], ".")
if isDynamic, exists := indexedProperties[indexProperty{Name: dynamicField}]; exists && isDynamic {
// dynamic child mapping enabled
continue OUTER
}
}
return fmt.Errorf("query_validate:"+
" field not indexed, field: %s, type: %s", entry.Name, entry.Type)
}
return nil
}
// -----------------------------------------------------------------------------
// indexProperty represents a property of an index.
type indexProperty struct {
Name string
Type string
Dims int
}
// processIndexDef obtains all the indexed properties from a "fulltext-index" definition.
func processIndexDef(indexDef *cbgt.IndexDef, collections map[string]struct{},
indexedProperties map[indexProperty]bool) (map[indexProperty]bool, error) {
if indexDef == nil {
return indexedProperties, nil
}
bp := NewBleveParams()
if err := json.Unmarshal([]byte(indexDef.Params), bp); err != nil {
return nil, err
}
im, ok := bp.Mapping.(*mapping.IndexMappingImpl)
if !ok {
return nil, nil
}
if indexedProperties == nil {
indexedProperties = map[indexProperty]bool{}
}
var scopedCollectionMappings bool
if strings.HasPrefix(bp.DocConfig.Mode, "scope.collection.") {
scopedCollectionMappings = true
}
var isCollectionRequested = func(mappingName string) bool {
if len(collections) == 0 {
// request applicable to all collections
return true
}
collectionName := "_default"
if scopedCollectionMappings {
dotSplit := strings.Split(mappingName, ".")
if len(dotSplit) > 1 {
collectionName = dotSplit[1]
}
}
_, exists := collections[collectionName]
return exists
}
if isCollectionRequested("_default") {
// check within default mapping if and only if "_default" collection is requested
// or no collections are requested
if im.DefaultMapping != nil && im.DefaultMapping.Enabled {
if im.DefaultMapping.Dynamic {
// complete dynamic mapping enabled
indexedProperties[indexProperty{Name: ""}] = true
}
indexedProperties = processDocMapping(nil, im.DefaultMapping, indexedProperties)
}
}
for tmName, tm := range im.TypeMapping {
if !isCollectionRequested(tmName) {
continue
}
if tm != nil && tm.Enabled {
if tm.Dynamic {
// complete dynamic mapping enabled
indexedProperties[indexProperty{Name: ""}] = true
}
indexedProperties = processDocMapping(nil, tm, indexedProperties)
}
}
return indexedProperties, nil
}
// processSearchRequest extracts all the query fields from the search request.
func processSearchRequest(sr *bleve.SearchRequest) (map[indexProperty]struct{}, error) {
if sr == nil {
return nil, nil
}
queryFields, err := extractQueryFields(sr, nil)
if err != nil {
return nil, err
}
queryFields, err = extractKNNQueryFields(sr, queryFields)
if err != nil {
return nil, err
}
return queryFields, nil
}
// -----------------------------------------------------------------------------
func processDocMapping(path []string, mapping *mapping.DocumentMapping,
indexedProperties map[indexProperty]bool) map[indexProperty]bool {
if mapping == nil {
return indexedProperties
}
for _, f := range mapping.Fields {
if f == nil || !f.Index || len(path) <= 0 {
continue
}
fpath := append([]string(nil), path...) // Copy.
fpath[len(fpath)-1] = f.Name
ip := indexProperty{
Name: strings.Join(fpath, "."),
Type: f.Type,
Dims: f.Dims,
}
if ip.Type == "vector_base64" {
// override to vector
ip.Type = "vector"
}
indexedProperties[ip] = false
if ip.Type != "vector" {
// check if field is indexed in _all
if f.IncludeInAll {
indexedProperties[indexProperty{
Name: "_all",
Type: f.Type,
}] = false
}
}
}
for propName, propMapping := range mapping.Properties {
if propMapping == nil {
continue
}
if propMapping.Dynamic {
// dynamic child mapping enabled
indexedProperties[indexProperty{
Name: strings.Join(append(path, propName), "."),
}] = true
}
indexedProperties = processDocMapping(append(path, propName), propMapping, indexedProperties)
}
return indexedProperties
}
// extractQueryFields extracts all the query fields from the search request.
func extractQueryFields(sr *bleve.SearchRequest,
queryFields map[indexProperty]struct{}) (map[indexProperty]struct{}, error) {
if sr.Query == nil {
return nil, nil
}
var walk func(que query.Query) error
walk = func(que query.Query) error {
switch qq := que.(type) {
case *query.BooleanQuery:
walk(qq.Must)
walk(qq.MustNot)
walk(qq.Should)
case *query.ConjunctionQuery:
for _, childQ := range qq.Conjuncts {
walk(childQ)
}
case *query.DisjunctionQuery:
for _, childQ := range qq.Disjuncts {
walk(childQ)
}
case *query.QueryStringQuery:
q, err := qq.Parse()
if err != nil {
return err
}
walk(q)
default:
if fq, ok := que.(query.FieldableQuery); ok {
fieldDesc := indexProperty{
Name: fq.Field(),
}
switch fq.(type) {
case *query.BoolFieldQuery:
fieldDesc.Type = "boolean"
case *query.NumericRangeQuery:
fieldDesc.Type = "number"
case *query.DateRangeStringQuery:
fieldDesc.Type = "datetime"
case *query.GeoBoundingBoxQuery,
*query.GeoDistanceQuery,
*query.GeoBoundingPolygonQuery:
fieldDesc.Type = "geopoint"
case *query.GeoShapeQuery:
fieldDesc.Type = "geoshape"
case *query.IPRangeQuery:
fieldDesc.Type = "IP"
default:
// The rest are all of Type: "text"
// - *query.MatchQuery
// - *query.MatchPhraseQuery
// - *query.TermQuery
// - *query.PhraseQuery
// - *query.MultiPhraseQuery
// - *query.FuzzyQuery
// - *query.PrefixQuery
// - *query.RegexpQuery
// - *query.WildcardQuery
// - *query.TermRangeQuery
fieldDesc.Type = "text"
}
if queryFields == nil {
queryFields = map[indexProperty]struct{}{}
}
if len(fieldDesc.Name) == 0 {
fieldDesc.Name = "_all" // look within composite field
}
queryFields[fieldDesc] = struct{}{}
}
// The following are non-Fieldable queries:
// - *query.DocIDQuery
// - *query.MatchAllQuery
// - *query.MatchNoneQuery
}
return nil
}
err := walk(sr.Query)
if err != nil {
return nil, err
}
return queryFields, nil
}