-
Notifications
You must be signed in to change notification settings - Fork 28
/
pindex_bleve.go
3864 lines (3302 loc) · 110 KB
/
pindex_bleve.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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014-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 (
"container/heap"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/mux"
bleveMappingUI "github.com/blevesearch/bleve-mapping-ui"
"github.com/blevesearch/bleve/v2"
_ "github.com/blevesearch/bleve/v2/config"
"github.com/blevesearch/bleve/v2/index/scorch"
"github.com/blevesearch/bleve/v2/mapping"
bleveRegistry "github.com/blevesearch/bleve/v2/registry"
"github.com/blevesearch/bleve/v2/search"
"github.com/blevesearch/bleve/v2/search/query"
ftsHttp "github.com/couchbase/cbft/http"
"github.com/couchbase/cbgt"
"github.com/couchbase/cbgt/rest"
log "github.com/couchbase/clog"
)
const (
featureIndexType = "indexType"
FeatureScorchIndex = featureIndexType + ":" + scorch.Name
FeatureCollections = cbgt.SOURCE_GOCBCORE + ":collections"
FeatureGeoSpatial = "geoSpatial"
featureVectorSearch = "vectors"
FeatureXattrs = "xattrs"
FeatureIndexCustomFilters = "indexCustomFilters"
FeatureSynonyms = "synonyms"
// bleveLegacyZapVersion represents the default zap version.
// This version is expected to remain a constant as all the
// future indexes are going to have a default segment version.
// Only pre CC indexes are expected to have an empty segment version
// which would be treated like the default zap version.
bleveLegacyZapVersion = int(11)
// ZapVersion where Collections support was introduced.
bleveCollectionsZapVersion = int(15)
// ZapVersion where Vector support was introduced.
bleveVectorZapVersion = int(16)
// blevePreferredZapVersion is the recommended zap version for newer indexes.
// This version needs to be bumped to reflect the latest recommended zap
// version in any given release.
blevePreferredZapVersion = int(16)
xattrsMappingName = "_$xattrs"
DefaultBleveMaxClauseCount = 1024
)
var (
FeatureBlevePreferredSegmentVersion = fmt.Sprintf("segmentVersion:%d", blevePreferredZapVersion)
// Use sync/atomic to access these stats
BatchBytesAdded uint64
BatchBytesRemoved uint64
NumBatchesIntroduced uint64
TotBatchesFlushedOnMaxOps uint64
TotBatchesFlushedOnTimer uint64
TotBatchesNew uint64
TotBatchesMerged uint64
TotRollbackPartial uint64
TotRollbackFull uint64
BleveMaxOpsPerBatch = 200 // Unlimited when <= 0.
BleveBatchFlushDuration = time.Duration(100 * time.Millisecond)
// represents the number of async batch workers per pindex
asyncBatchWorkerCount = 4 // need to make it configurable,
TotBleveDestOpened uint64
TotBleveDestClosed uint64
defaultLimitingMinTime = 500
defaultLimitingMaxTime = 120000
)
// BleveParams represents the bleve index params. See also
// cbgt.IndexDef.Params. A JSON'ified BleveParams looks like...
//
// {
// "mapping": {
// // See bleve.mapping.IndexMapping.
// },
// "store": {
// // See BleveParamsStore.
// },
// "doc_config": {
// // See BleveDocumentConfig.
// }
// }
type BleveParams struct {
Mapping mapping.IndexMapping `json:"mapping"`
Store map[string]interface{} `json:"store"`
DocConfig BleveDocumentConfig `json:"doc_config"`
}
// BleveParamsStore represents some of the publically available
// options in the "store" part of a bleve index params. See also the
// BleveParams.Store field.
type BleveParamsStore struct {
// The indexType defaults to bleve.Config.DefaultIndexType.
// Example: "scorch". See bleve.index.scorch.Name and
// bleve.registry.RegisterIndexType().
IndexType string `json:"indexType"`
// The kvStoreName defaults to bleve.Config.DefaultKVStore.
// See also bleve.registry.RegisterKVStore().
KvStoreName string `json:"kvStoreName"`
}
func NewBleveParams() *BleveParams {
rv := &BleveParams{
Mapping: bleve.NewIndexMapping(),
Store: map[string]interface{}{
"indexType": bleve.Config.DefaultIndexType,
"kvStoreName": bleve.Config.DefaultKVStore,
},
DocConfig: BleveDocumentConfig{
Mode: "type_field",
TypeField: "type",
},
}
return rv
}
func (sr *SearchRequest) decorateQuery(indexName string, q query.Query,
cache *collMetaFieldCache) (query.Query, query.Query) {
var docIDQuery *query.DocIDQuery
var ok bool
// bail out early if the query is not a docID one and there are
// no target collections requested in search request.
if docIDQuery, ok = q.(*query.DocIDQuery); !ok && len(sr.Collections) == 0 {
return nil, q
}
if cache == nil {
cache = metaFieldValCache
}
// bail out early if the index is a single collection index as there
// won't be any docID decorations done during indexing as well as the
// collection scoping during the querying also redundant.
var sdm *sourceDetails
if sdm, ok = cache.getSourceDetailsMap(indexName); !ok ||
len(sdm.collUIDNameMap) <= 1 {
return nil, q
}
// if this is a multi collection index and the query is for docID,
// then decorate the target docIDs with cuid prefixes.
if docIDQuery != nil {
decoratedQuery := *docIDQuery
hash := make(map[string]struct{})
for _, cname := range sr.Collections {
hash[cname] = struct{}{}
}
newIDs := make([]string, 0, len(decoratedQuery.IDs))
for cuid, cname := range sdm.collUIDNameMap {
if _, ok := hash[cname]; !ok && len(hash) > 0 {
continue
}
cBytes := make([]byte, 4)
binary.LittleEndian.PutUint32(cBytes, cuid)
for _, docID := range decoratedQuery.IDs {
newIDs = append(newIDs, string(append(cBytes,
[]byte(docID)...)))
}
}
decoratedQuery.IDs = newIDs
return q, &decoratedQuery
}
// if the search is scoped to specific collections then add
// collection specific conjunctions with multi collection indexes.
cjnq := query.NewConjunctionQuery([]query.Query{q})
djnq := query.NewDisjunctionQuery(nil)
for _, col := range sr.Collections {
queryStr := cache.getMetaFieldValue(indexName, col)
mq := query.NewMatchQuery(queryStr)
mq.Analyzer = "keyword"
mq.SetField(CollMetaFieldName)
djnq.AddQuery(mq)
}
djnq.SetMin(1)
cjnq.AddQuery(djnq)
return q, cjnq
}
type SearchRequest struct {
Q json.RawMessage `json:"query"`
Size *int `json:"size"`
From *int `json:"from"`
Highlight *bleve.HighlightRequest `json:"highlight"`
Fields []string `json:"fields"`
Facets bleve.FacetsRequest `json:"facets"`
Explain bool `json:"explain"`
Sort []json.RawMessage `json:"sort"`
IncludeLocations bool `json:"includeLocations"`
Score string `json:"score,omitempty"`
SearchAfter []string `json:"search_after,omitempty"`
SearchBefore []string `json:"search_before,omitempty"`
Limit *int `json:"limit,omitempty"`
Offset *int `json:"offset,omitempty"`
Collections []string `json:"collections,omitempty"`
KNN json.RawMessage `json:"knn,omitempty"`
KNNOperator json.RawMessage `json:"knn_operator,omitempty"`
PreSearchData json.RawMessage `json:"pre_search_data,omitempty"`
}
func (sr *SearchRequest) ConvertToBleveSearchRequest() (*bleve.SearchRequest, error) {
// size/from take precedence, but if not specified, overwrite with
// limit/offset settings
r := &bleve.SearchRequest{
Highlight: sr.Highlight,
Fields: sr.Fields,
Facets: sr.Facets,
Explain: sr.Explain,
IncludeLocations: sr.IncludeLocations,
Score: sr.Score,
SearchAfter: sr.SearchAfter,
SearchBefore: sr.SearchBefore,
}
var err error
r.Query, err = query.ParseQuery(sr.Q)
if err != nil {
return nil, err
}
if sr.PreSearchData != nil {
r.PreSearchData, err = query.ParsePreSearchData(sr.PreSearchData)
if err != nil {
return nil, err
}
}
if sr.Size == nil {
if sr.Limit == nil || *sr.Limit < 0 {
r.Size = 10
} else {
r.Size = *sr.Limit
}
} else if *sr.Size < 0 {
r.Size = 10
} else {
r.Size = *sr.Size
}
if sr.From == nil {
if sr.Offset == nil || *sr.Offset < 0 {
r.From = 0
} else {
r.From = *sr.Offset
}
} else if *sr.From < 0 {
r.From = 0
} else {
r.From = *sr.From
}
if sr.Sort == nil {
r.Sort = search.SortOrder{&search.SortScore{Desc: true}}
} else {
r.Sort, err = search.ParseSortOrderJSON(sr.Sort)
if err != nil {
return nil, err
}
}
if r, err = interpretKNNForRequest(sr.KNN, sr.KNNOperator, r); err != nil {
return nil, err
}
return r, r.Validate()
}
type RollbackInfo struct {
partition string
vBucketUUID uint64
rollbackSeq uint64
}
type BleveDest struct {
path string
sourceName string
bleveDocConfig BleveDocumentConfig
// Invoked when mgr should rollback this BleveDest
rollback func()
rollbackInfo *RollbackInfo
stats *cbgt.PIndexStoreStats
copyStats *CopyPartitionStats
m sync.RWMutex // Protects the fields that follow.
bindex bleve.Index
partitions map[string]*BleveDestPartition
rev uint64 // Incremented whenever bindex changes.
batchReqChs []chan *batchRequest
stopCh chan struct{}
removeCh chan struct{}
isRollbackInProgress bool
}
// Used to track state for a single partition.
type BleveDestPartition struct {
bdest *BleveDest
bindex bleve.Index
partition string
partitionBytes []byte
partitionOpaque []byte // Key used to implement OpaqueSet/OpaqueGet().
seqMax uint64 // Max seq # we've seen for this partition.
seqMaxBatch uint64 // Max seq # that got through batch apply/commit.
lastUUID atomic.Value // type: string; Cache most recent partition UUID from lastOpaque.
m sync.Mutex // Protects the fields that follow.
seqSnapEnd uint64 // To track snapshot end seq # for this partition.
osoSnapshot bool // Flag to track if current seq # is within an OSO Snapshot.
osoSeqMax uint64 // Max seq # received within an OSO Snapshot.
batch *bleve.Batch // Batch applied when we hit seqSnapEnd.
lastOpaque []byte // Cache most recent value for OpaqueSet()/OpaqueGet().
cwrQueue cbgt.CwrQueue
lastAsyncBatchErr error // for returning async batch err on next call
}
type batchRequest struct {
bdp *BleveDestPartition
bindex bleve.Index
batch *bleve.Batch
seqMax uint64 // a local copy of seqMax
}
func NewBleveDestEx(path string, bindex bleve.Index,
rollback func(), bleveDocConfig BleveDocumentConfig, sourceName string) *BleveDest {
bleveDest := &BleveDest{
path: path,
bleveDocConfig: bleveDocConfig,
rollback: rollback,
bindex: bindex,
partitions: make(map[string]*BleveDestPartition),
stats: cbgt.NewPIndexStoreStats(),
copyStats: &CopyPartitionStats{},
stopCh: make(chan struct{}),
removeCh: make(chan struct{}),
sourceName: sourceName,
}
bleveDest.batchReqChs = make([]chan *batchRequest, asyncBatchWorkerCount)
bleveDest.startBatchWorkers()
atomic.AddUint64(&TotBleveDestOpened, 1)
return bleveDest
}
func NewBleveDest(path string, bindex bleve.Index,
rollback func(), bleveDocConfig BleveDocumentConfig) *BleveDest {
bleveDest := &BleveDest{
path: path,
bleveDocConfig: bleveDocConfig,
rollback: rollback,
bindex: bindex,
partitions: make(map[string]*BleveDestPartition),
stats: cbgt.NewPIndexStoreStats(),
copyStats: &CopyPartitionStats{},
stopCh: make(chan struct{}),
removeCh: make(chan struct{}),
}
bleveDest.batchReqChs = make([]chan *batchRequest, asyncBatchWorkerCount)
bleveDest.startBatchWorkers()
atomic.AddUint64(&TotBleveDestOpened, 1)
return bleveDest
}
func (t *BleveDest) startBatchWorkers() {
for i := 0; i < asyncBatchWorkerCount; i++ {
t.batchReqChs[i] = make(chan *batchRequest, 1)
go runBatchWorker(t.batchReqChs[i], t.stopCh, t.bindex, i)
}
}
func (t *BleveDest) stopBatchWorkers() {
t.m.Lock()
ch := t.stopCh
t.stopCh = make(chan struct{})
t.m.Unlock()
close(ch)
}
// ---------------------------------------------------------
var CurrentNodeDefsFetcher *NodeDefsFetcher
type NodeDefsFetcher struct {
mgr *cbgt.Manager
}
func (ndf *NodeDefsFetcher) SetManager(mgr *cbgt.Manager) {
ndf.mgr = mgr
}
func (ndf *NodeDefsFetcher) GetManager() *cbgt.Manager {
return ndf.mgr
}
func (ndf *NodeDefsFetcher) Get() (*cbgt.NodeDefs, error) {
if ndf.mgr != nil {
return ndf.mgr.GetNodeDefs(cbgt.NODE_DEFS_WANTED, true)
}
return nil, fmt.Errorf("NodeDefsFetcher Get(): mgr is nil!")
}
// ---------------------------------------------------------
const bleveQueryHelp = `
<a href="https://docs.couchbase.com/server/7.6/fts/fts-supported-queries.html"
target="_blank">
query syntax help
</a>
`
func init() {
cbgt.RegisterPIndexImplType("fulltext-index", &cbgt.PIndexImplType{
Prepare: PrepareIndexDef,
Validate: ValidateBleve,
OnDelete: OnDeleteIndex,
New: NewBlevePIndexImpl,
NewEx: NewBlevePIndexImplEx,
Rollback: RollbackBleve,
Open: OpenBlevePIndexImpl,
OpenUsing: OpenBlevePIndexImplUsing,
Count: CountBleve,
Query: QueryBleve,
Description: "general/fulltext-index " +
" - a full text index powered by the bleve engine",
StartSample: NewBleveParams(),
QuerySamples: BleveQuerySamples,
QueryHelp: bleveQueryHelp,
InitRouter: BleveInitRouter,
DiagHandlers: []cbgt.DiagHandler{
{Name: "/api/pindex-bleve", Handler: ftsHttp.NewListIndexesHandler(),
HandlerFunc: nil},
},
MetaExtra: BleveMetaExtra,
UI: map[string]string{
"controllerInitName": "blevePIndexInitController",
"controllerDoneName": "blevePIndexDoneController",
},
AnalyzeIndexDefUpdates: RestartOnIndexDefChanges,
SubmitTaskRequest: SubmitTaskRequest,
})
}
func PrepareIndexDef(mgr *cbgt.Manager, indexDef *cbgt.IndexDef) (
*cbgt.IndexDef, error) {
if indexDef == nil {
return nil, cbgt.NewBadRequestError("PrepareIndex, indexDef is nil")
}
if CurrentNodeDefsFetcher == nil {
rv, err := LimitIndexDef(mgr, indexDef)
if err != nil {
return rv, cbgt.NewBadRequestError("%v", err)
}
return rv, nil
}
nodeDefs, err := CurrentNodeDefsFetcher.Get()
if err != nil {
return nil, cbgt.NewInternalServerError("PrepareIndex, nodeDefs unavailable: err: %v", err)
}
var collectionsSupported, s2SpatialSupported bool
if isClusterCompatibleFor(FeatureGeoSpatialVersion) {
s2SpatialSupported =
cbgt.IsFeatureSupportedByCluster(FeatureGeoSpatial, nodeDefs)
// check whether the spatial plugin usage is disabled for geo points.
if v := mgr.GetOption("disableGeoPointSpatialPlugin"); v == "true" {
s2SpatialSupported = false
}
// as its implicit since spatial is already on an advanced version.
collectionsSupported = true
} else if isClusterCompatibleFor(FeatureCollectionVersion) {
collectionsSupported =
cbgt.IsFeatureSupportedByCluster(FeatureCollections, nodeDefs)
}
if collectionsSupported {
// Use "gocbcore" for DCP streaming if cluster is 7.0+
indexDef.SourceType = cbgt.SOURCE_GOCBCORE
}
vectorSearchSupported := isClusterCompatibleFor(FeatureVectorSearchSupportVersion) &&
cbgt.IsFeatureSupportedByCluster(featureVectorSearch, nodeDefs)
var indexVectorPicture vectorPicture
bp := NewBleveParams()
if len(indexDef.Params) > 0 {
b, err := bleveMappingUI.CleanseJSON([]byte(indexDef.Params))
if err != nil {
return nil, cbgt.NewBadRequestError("PrepareIndex, CleanseJSON err: %v", err)
}
err = json.Unmarshal(b, bp)
if err != nil {
if typeErr, ok := err.(*json.UnmarshalTypeError); ok {
if typeErr.Type.String() == "map[string]json.RawMessage" {
return nil, cbgt.NewBadRequestError("PrepareIndex,"+
" JSON parse was expecting a string key/field-name"+
" but instead saw a %s", typeErr.Value)
}
}
return nil, cbgt.NewBadRequestError("bleve: Prepare, err: %v", err)
}
if indexType, ok := bp.Store["indexType"].(string); ok {
if indexType == "scorch" {
// If indexType were "scorch", the "kvStoreName" setting isn't
// really applicable, so drop the setting.
delete(bp.Store, "kvStoreName")
// insert spatial config only if geopoint field exists in the mapping.
if s2SpatialSupported && isGeoPointFieldInMapping(bp) {
bp.Store["spatialPlugin"] = "s2"
} else {
delete(bp.Store, "spatialPlugin")
}
}
}
// check if the index definition has a mapping with synonym sources present.
var synonymsAvailable bool
if im, ok := bp.Mapping.(*mapping.IndexMappingImpl); ok {
synonymsAvailable = im.SynonymCount() > 0
}
// check if the cluster supports synonym search
if synonymsAvailable && !cbgt.IsFeatureSupportedByCluster(FeatureSynonyms, nodeDefs) {
// Synonym Search is NOT supported on this cluster
// (lower version or mixed lower version)
return nil, cbgt.NewBadRequestError("PrepareIndex, err: synonym search " +
"not supported in this cluster")
}
scopeDotCollMode := strings.HasPrefix(bp.DocConfig.Mode, ConfigModeCollPrefix)
// figure out the scope/collection details from mappings
// and perform the validation checks.
if scopeDotCollMode || synonymsAvailable {
if !collectionsSupported {
return nil, cbgt.NewBadRequestError("PrepareIndex, collections not supported" +
" across all nodes in the cluster")
}
if im, ok := bp.Mapping.(*mapping.IndexMappingImpl); ok {
scope, err := validateScopeCollFromMappings(indexDef.SourceName,
im, false, scopeDotCollMode)
if err != nil {
return nil, cbgt.NewBadRequestError("%v", err)
}
bucketName, scopeName := getKeyspaceFromScopedIndexName(indexDef.Name)
if len(bucketName) > 0 && len(scopeName) > 0 {
if !isClusterCompatibleFor(FeatureScopedIndexNamesVersion) {
return nil, cbgt.NewBadRequestError("PrepareIndex, scoped indexes NOT" +
" supported in mixed version cluster")
}
if bucketName != indexDef.SourceName || scopeName != scope.Name {
return nil, cbgt.NewBadRequestError("PrepareIndex, validation of bucket" +
" and/or scope names against index definition failed")
}
}
}
} else {
bucketName, scopeName := getKeyspaceFromScopedIndexName(indexDef.Name)
if len(bucketName) > 0 && len(scopeName) > 0 {
if bucketName != indexDef.SourceName || scopeName != "_default" {
return nil, cbgt.NewBadRequestError("PrepareIndex, changing a scoped index's" +
" bucket/scope name is NOT allowed")
}
}
}
if bp.DocConfig.Mode == "scope.collection.custom" || bp.DocConfig.Mode == "custom" {
if !cbgt.IsFeatureSupportedByCluster(FeatureIndexCustomFilters, nodeDefs) {
// Document Filters are NOT supported on this cluster
// (lower version or mixed lower version)
return nil, cbgt.NewBadRequestError("PrepareIndex, err: custom index filters " +
"not supported in this cluster")
}
}
indexVectorPicture = vectorPictureFromIndexMapping(bp.Mapping)
if indexVectorPicture.fields != noVectorFields && !vectorSearchSupported {
// Vector indexing & search is NOT supported on this cluster
// (lower version or mixed lower version)
return nil, cbgt.NewBadRequestError("PrepareIndex, err: vector typed fields " +
"not supported in this cluster")
}
if mappingContainsXAttrs(bp) {
if !cbgt.IsFeatureSupportedByCluster(FeatureXattrs, nodeDefs) {
// XAttrs is NOT supported on this cluster
// (lower version or mixed lower version)
return nil, cbgt.NewBadRequestError("PrepareIndex, err: xattr fields " +
"and properties not supported in this cluster")
}
sourceParams := make(map[string]interface{})
if len(indexDef.SourceParams) > 0 && indexDef.SourceParams != "null" {
err = UnmarshalJSON([]byte(indexDef.SourceParams), &sourceParams)
if err != nil {
return nil, cbgt.NewBadRequestError("PrepareIndex, unable to unmarshal source params"+
", err: %v", err)
}
}
sourceParams["includeXAttrs"] = true
updatedSourceParams, err := MarshalJSON(sourceParams)
if err != nil {
return nil, cbgt.NewBadRequestError("PrepareIndex, unable to marshal source params"+
", err: %v", err)
}
indexDef.SourceParams = string(updatedSourceParams)
}
if indexVectorPicture.fields == vectorAndBase64Fields &&
(len(featuresVectorBase64Dims4096) == 0 ||
!cbgt.IsFeatureSupportedByCluster(featuresVectorBase64Dims4096, nodeDefs)) {
return nil, cbgt.NewBadRequestError("PrepareIndex, err: vector_base64 typed fields " +
"not supported in this cluster")
}
featureFlagToCheckForDims := featureFlagForDims(indexVectorPicture.maxDims)
if len(featureFlagToCheckForDims) > 0 &&
!cbgt.IsFeatureSupportedByCluster(featureFlagToCheckForDims, nodeDefs) {
return nil, cbgt.NewBadRequestError(fmt.Sprintf("PrepareIndex, err: vector typed fields "+
"with dims %v not supported in this cluster", indexVectorPicture.maxDims))
}
if indexVectorPicture.cosine &&
(len(featureVectorCosineSimilarity) == 0 ||
!cbgt.IsFeatureSupportedByCluster(featureVectorCosineSimilarity, nodeDefs)) {
return nil, cbgt.NewBadRequestError("PrepareIndex, err: cosine similarity metric for vectors " +
"not supported in this cluster")
}
}
segmentVersionSupported := cbgt.IsFeatureSupportedByCluster(
FeatureBlevePreferredSegmentVersion, nodeDefs)
// if segment version is specified then perform the validations.
if v, ok := bp.Store["segmentVersion"]; ok {
if z, ok := v.(float64); ok {
zv := int(z)
if !segmentVersionSupported && zv >= blevePreferredZapVersion {
// if the cluster isn't advanced enough then err out
// on latest zap version request for new indexes.
return nil, cbgt.NewBadRequestError("PrepareIndex, err: zap version %d isn't "+
"supported in mixed version cluster", zv)
}
if zv > blevePreferredZapVersion || zv < bleveLegacyZapVersion {
return nil, cbgt.NewBadRequestError("PrepareIndex, err: zap version %d isn't "+
"supported", zv)
}
if indexVectorPicture.fields != noVectorFields && zv < bleveVectorZapVersion {
// overrride segmentVersion to minimum version needed to support vector mappings
versionToUse := bleveVectorZapVersion
if segmentVersionSupported {
versionToUse = blevePreferredZapVersion
}
bp.Store["segmentVersion"] = versionToUse
}
} else {
return nil, cbgt.NewBadRequestError("PrepareIndex, err: segmentVersion %v "+
"should be a numeric value", v)
}
} else {
// if no zap version is specified then assume the preferred
// zap version for newer indexes in a sufficiently advanced
// cluster, else consider the default zap version.
if segmentVersionSupported {
bp.Store["segmentVersion"] = blevePreferredZapVersion
} else if vectorSearchSupported {
bp.Store["segmentVersion"] = bleveVectorZapVersion
} else if collectionsSupported {
bp.Store["segmentVersion"] = bleveCollectionsZapVersion
} else {
bp.Store["segmentVersion"] = bleveLegacyZapVersion
}
}
updatedParams, err := json.Marshal(bp)
if err != nil {
return nil, cbgt.NewBadRequestError("PrepareIndex, Marshal err: %v", err)
}
indexDef.Params = string(updatedParams)
if err := checkSourceCompatability(mgr, indexDef.SourceName); err != nil {
return nil, cbgt.NewInternalServerError("PrepareIndex, err: %v", err)
}
rv, err := LimitIndexDef(mgr, indexDef)
if err != nil {
return rv, cbgt.NewInternalServerError("%v", err)
}
return rv, nil
}
func ValidateBleve(indexType, indexName, indexParams string) error {
if len(indexParams) <= 0 {
return nil
}
validateBleveIndexType := func(content interface{}) error {
if CurrentNodeDefsFetcher == nil {
return nil
}
nodeDefs, err := CurrentNodeDefsFetcher.Get()
if err != nil {
return cbgt.NewInternalServerError("ValidateIndex, nodeDefs unavailable: err: %v", err)
}
indexType := ""
if entries, ok := content.(map[string]interface{}); ok {
indexType = entries["indexType"].(string)
}
// Validate indexType
if !cbgt.IsFeatureSupportedByCluster(featureIndexType+":"+indexType, nodeDefs) {
return cbgt.NewBadRequestError("ValidateIndex, index validation failed:"+
" indexType: %v not supported on all nodes in"+
" cluster", indexType)
}
return nil
}
// Validate token filters in indexParams
validateIndexParams := func() error {
var iParams map[string]interface{}
err := json.Unmarshal([]byte(indexParams), &iParams)
if err != nil {
// Ignore the JSON unmarshalling error, if in the case
// indexParams isn't JSON.
return nil
}
store, found := iParams["store"]
if found {
err = validateBleveIndexType(store)
if err != nil {
return err
}
}
mapping, found := iParams["mapping"]
if !found {
// Entry for mapping not found
return nil
}
analysis, found := mapping.(map[string]interface{})["analysis"]
if !found {
// No sub entry with the name analysis within mapping
return nil
}
tokenfilters, found := analysis.(map[string]interface{})["token_filters"]
if !found {
// No entry for token_filters within mapping/analysis
return nil
}
for _, val := range tokenfilters.(map[string]interface{}) {
param := val.(map[string]interface{})
switch param["type"] {
case "edge_ngram", "length", "ngram", "shingle":
if param["min"].(float64) > param["max"].(float64) {
return cbgt.NewBadRequestError("bleve: token_filter validation failed"+
" for %v => min(%v) > max(%v)", param["type"],
param["min"], param["max"])
}
case "truncate_token":
if param["length"].(float64) < 0 {
return cbgt.NewBadRequestError("bleve: token_filter validation failed"+
" for %v => length(%v) < 0", param["type"], param["length"])
}
default:
break
}
}
return nil
}
err := validateIndexParams()
if err != nil {
return cbgt.NewBadRequestError("ValidateIndex, err: %v", err)
}
b, err := bleveMappingUI.CleanseJSON([]byte(indexParams))
if err != nil {
return cbgt.NewBadRequestError("ValidateIndex, CleanseJSON err: %v", err)
}
bp := NewBleveParams()
err = json.Unmarshal(b, bp)
if err != nil {
if typeErr, ok := err.(*json.UnmarshalTypeError); ok {
if typeErr.Type.String() == "map[string]json.RawMessage" {
return cbgt.NewBadRequestError("ValidateIndex, Params:"+
" JSON parse was expecting a string key/field-name"+
" but instead saw a %s", typeErr.Value)
}
}
return cbgt.NewBadRequestError("ValidateIndex, Params err: %v", err)
}
// err out if there are no active type mapping.
if im, ok := bp.Mapping.(*mapping.IndexMappingImpl); ok {
var found bool
for tp, dm := range im.TypeMapping {
if !dm.Enabled || len(tp) == 0 {
continue
}
found = true
break
}
if !im.DefaultMapping.Enabled && !found {
return cbgt.NewBadRequestError("ValidateIndex, Params: no valid type mappings found")
}
}
err = bp.Mapping.Validate()
if err != nil {
return cbgt.NewBadRequestError("ValidateIndex, Mapping err: %v", err)
}
err = bp.DocConfig.Validate(bp.Mapping)
if err != nil {
return fmt.Errorf("ValidateIndex, DocConfig err: %v", err)
}
return nil
}
func OnDeleteIndex(indexDef *cbgt.IndexDef) {
if indexDef == nil {
return
}
// Reset focusStats of the index
for k := range queryPaths {
if indexQueryPathStats, exists := MapRESTPathStats[k]; exists {
indexQueryPathStats.ResetFocusStats(indexDef.Name)
}
}
// Reset gRPC focusStats of the index
GrpcPathStats.ResetFocusStats(indexDef.Name)
// Reset the metaFieldValCache
metaFieldValCache.reset(indexDef.Name)
// Reset QuerySupervisor's entry for last_access_time
querySupervisor.deleteEntryForIndex(indexDef.Name)
// Clear out source partition seqs cache for this index
DropSourcePartitionSeqs(indexDef.SourceName, indexDef.SourceUUID)
// Refresh the regulator stats. For eg, Deletion of a bucket leads
// to index deletions, in which case the stale regulator stats
// needs to be removed.
RefreshRegulatorStats()
// When deleting an index, remove the corresponding bucket from the manifest cache.
// If other indexes still use the same bucket, the cache will be refreshed as needed.
// Otherwise, unnecessary monitoring of the bucket can be avoided.
removeBucketFromManifestCache(indexDef.SourceName)
}
func parseIndexParams(indexParams string) (
bleveParams *BleveParams, kvConfig map[string]interface{},
bleveIndexType string, kvStoreName string, err error) {
var ip cbgt.IndexPrepParams
err = json.Unmarshal([]byte(indexParams), &ip)
if err != nil {
return nil, nil, "", "",
fmt.Errorf("bleve: new index, json marshal"+
" err: %v", err)
}
indexParams = ip.Params
bleveParams = NewBleveParams()
if len(indexParams) > 0 {
buf, err := bleveMappingUI.CleanseJSON([]byte(indexParams))
if err != nil {
return nil, nil, "", "",
fmt.Errorf("bleve: cleanse params, err: %v", err)
}
err = json.Unmarshal(buf, bleveParams)
if err != nil {
return nil, nil, "", "",
fmt.Errorf("bleve: parse params, err: %v", err)
}
err = bleveParams.DocConfig.Validate(bleveParams.Mapping)
if err != nil {
return nil, nil, "", "",
fmt.Errorf("bleve: doc config, err: %v", err)
}
}
// check if the index definition has a mapping with synonym sources present.
var synonymsAvailable bool
if im, ok := bleveParams.Mapping.(*mapping.IndexMappingImpl); ok {
synonymsAvailable = im.SynonymCount() > 0
}
scopeDotCollMode := strings.HasPrefix(bleveParams.DocConfig.Mode, ConfigModeCollPrefix)
if scopeDotCollMode || synonymsAvailable {
if im, ok := bleveParams.Mapping.(*mapping.IndexMappingImpl); ok {
scope, err := validateScopeCollFromMappings(ip.SourceName,
im, false, scopeDotCollMode)
if err != nil {
return nil, nil, "", "", err
}
// if there are more than 1 collection then need to
// insert $scope#$collection field into the mappings
if multiCollection(scope.Collections) {
err = enhanceMappingsWithCollMetaField(im.TypeMapping)
if err != nil {
return nil, nil, "", "", err
}
ipBytes, err := json.Marshal(bleveParams)
if err != nil {
return nil, nil, "", "",
fmt.Errorf("bleve: new , json marshal,"+
" err: %v", err)
}
indexParams = string(ipBytes)
}
bleveParams.DocConfig.CollPrefixLookup =
initMetaFieldValCache(ip.IndexName, ip.SourceName, im, scope)
}
}
kvConfig, bleveIndexType, kvStoreName = bleveRuntimeConfigMap(bleveParams)
return bleveParams, kvConfig, bleveIndexType, kvStoreName, nil