-
Notifications
You must be signed in to change notification settings - Fork 509
/
spec.c
3070 lines (2668 loc) · 107 KB
/
spec.c
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 Redis Ltd. 2016 - present
* Licensed under your choice of the Redis Source Available License 2.0 (RSALv2) or
* the Server Side Public License v1 (SSPLv1).
*/
#include "spec.h"
#include <math.h>
#include <ctype.h>
#include "util/logging.h"
#include "util/misc.h"
#include "rmutil/vector.h"
#include "rmutil/util.h"
#include "rmutil/rm_assert.h"
#include "trie/trie_type.h"
#include "rmalloc.h"
#include "config.h"
#include "cursor.h"
#include "tag_index.h"
#include "redis_index.h"
#include "indexer.h"
#include "suffix.h"
#include "alias.h"
#include "module.h"
#include "aggregate/expr/expression.h"
#include "rules.h"
#include "dictionary.h"
#include "doc_types.h"
#include "rdb.h"
#include "commands.h"
#include "util/workers.h"
#define INITIAL_DOC_TABLE_SIZE 1000
///////////////////////////////////////////////////////////////////////////////////////////////
static int FieldSpec_RdbLoad(RedisModuleIO *rdb, FieldSpec *f, StrongRef sp_ref, int encver);
const char *(*IndexAlias_GetUserTableName)(RedisModuleCtx *, const char *) = NULL;
RedisModuleType *IndexSpecType;
static uint64_t spec_unique_ids = 1;
dict *specDict_g;
IndexesScanner *global_spec_scanner = NULL;
size_t pending_global_indexing_ops = 0;
dict *legacySpecDict;
dict *legacySpecRules;
// Pending or in-progress index drops
uint16_t pendingIndexDropCount_g = 0;
Version redisVersion;
Version rlecVersion;
bool isCrdt;
bool isTrimming = false;
// Default values make no limits.
size_t memoryLimit = -1;
size_t used_memory = 0;
static redisearch_threadpool cleanPool = NULL;
//---------------------------------------------------------------------------------------------
static void setMemoryInfo(RedisModuleCtx *ctx) {
#define MIN_NOT_0(a,b) (((a)&&(b))?MIN((a),(b)):MAX((a),(b)))
RedisModuleServerInfoData *info = RedisModule_GetServerInfo(ctx, "memory");
size_t maxmemory = RedisModule_ServerInfoGetFieldUnsigned(info, "maxmemory", NULL);
size_t max_process_mem = RedisModule_ServerInfoGetFieldUnsigned(info, "max_process_mem", NULL); // Enterprise limit
maxmemory = MIN_NOT_0(maxmemory, max_process_mem);
size_t total_system_memory = RedisModule_ServerInfoGetFieldUnsigned(info, "total_system_memory", NULL);
memoryLimit = MIN_NOT_0(maxmemory, total_system_memory);
used_memory = RedisModule_ServerInfoGetFieldUnsigned(info, "used_memory", NULL);
RedisModule_FreeServerInfo(ctx, info);
}
/*
* Initialize the spec's fields that are related to the cursors.
*/
static void Cursors_initSpec(IndexSpec *spec, size_t capacity) {
spec->activeCursors = 0;
spec->cursorsCap = capacity;
}
/*
* Get a field spec by field name. Case sensetive!
* Return the field spec if found, NULL if not.
* Assuming the spec is properly locked before calling this function.
*/
const FieldSpec *IndexSpec_GetField(const IndexSpec *spec, const char *name, size_t len) {
for (size_t i = 0; i < spec->numFields; i++) {
if (len != strlen(spec->fields[i].name)) {
continue;
}
const FieldSpec *fs = spec->fields + i;
if (!strncmp(fs->name, name, len)) {
return fs;
}
}
return NULL;
}
// Assuming the spec is properly locked before calling this function.
t_fieldMask IndexSpec_GetFieldBit(IndexSpec *spec, const char *name, size_t len) {
const FieldSpec *fs = IndexSpec_GetField(spec, name, len);
if (!fs || !FIELD_IS(fs, INDEXFLD_T_FULLTEXT) || !FieldSpec_IsIndexable(fs)) return 0;
return FIELD_BIT(fs);
}
// Assuming the spec is properly locked before calling this function.
int IndexSpec_CheckPhoneticEnabled(const IndexSpec *sp, t_fieldMask fm) {
if (!(sp->flags & Index_HasPhonetic)) {
return 0;
}
if (fm == 0 || fm == (t_fieldMask)-1) {
// No fields -- implicit phonetic match!
return 1;
}
for (size_t ii = 0; ii < sp->numFields; ++ii) {
if (fm & ((t_fieldMask)1 << ii)) {
const FieldSpec *fs = sp->fields + ii;
if (FIELD_IS(fs, INDEXFLD_T_FULLTEXT) && (FieldSpec_IsPhonetics(fs))) {
return 1;
}
}
}
return 0;
}
// Assuming the spec is properly locked before calling this function.
int IndexSpec_CheckAllowSlopAndInorder(const IndexSpec *spec, t_fieldMask fm, QueryError *status) {
for (size_t ii = 0; ii < spec->numFields; ++ii) {
if (fm & ((t_fieldMask)1 << ii)) {
const FieldSpec *fs = spec->fields + ii;
if (FIELD_IS(fs, INDEXFLD_T_FULLTEXT) && (FieldSpec_IsUndefinedOrder(fs))) {
QueryError_SetErrorFmt(status, QUERY_EBADORDEROPTION,
"slop/inorder are not supported for field `%s` since it has undefined ordering", fs->name);
return 0;
}
}
}
return 1;
}
// Assuming the spec is properly locked before calling this function.
const FieldSpec *IndexSpec_GetFieldBySortingIndex(const IndexSpec *sp, uint16_t idx) {
for (size_t ii = 0; ii < sp->numFields; ++ii) {
if (sp->fields[ii].options & FieldSpec_Sortable && sp->fields[ii].sortIdx == idx) {
return sp->fields + ii;
}
}
return NULL;
}
// Assuming the spec is properly locked before calling this function.
const char *IndexSpec_GetFieldNameByBit(const IndexSpec *sp, t_fieldMask id) {
for (int i = 0; i < sp->numFields; i++) {
if (FIELD_BIT(&sp->fields[i]) == id && FIELD_IS(&sp->fields[i], INDEXFLD_T_FULLTEXT) &&
FieldSpec_IsIndexable(&sp->fields[i])) {
return sp->fields[i].name;
}
}
return NULL;
}
//---------------------------------------------------------------------------------------------
/*
* Parse an index spec from redis command arguments.
* Returns REDISMODULE_ERR if there's a parsing error.
* The command only receives the relevant part of argv.
*
* The format currently is FT.CREATE {index} [NOOFFSETS] [NOFIELDS] [NOFREQS]
SCHEMA {field} [TEXT [WEIGHT {weight}]] | [NUMERIC]
*/
StrongRef IndexSpec_ParseRedisArgs(RedisModuleCtx *ctx, RedisModuleString *name,
RedisModuleString **argv, int argc, QueryError *status) {
const char *args[argc];
for (int i = 0; i < argc; i++) {
args[i] = RedisModule_StringPtrLen(argv[i], NULL);
}
return IndexSpec_Parse(RedisModule_StringPtrLen(name, NULL), args, argc, status);
}
arrayof(FieldSpec *) getFieldsByType(IndexSpec *spec, FieldType type) {
#define FIELDS_ARRAY_CAP 2
arrayof(FieldSpec *) fields = array_new(FieldSpec *, FIELDS_ARRAY_CAP);
for (int i = 0; i < spec->numFields; ++i) {
if (FIELD_IS(spec->fields + i, type)) {
fields = array_append(fields, &(spec->fields[i]));
}
}
return fields;
}
/* Check if Redis is currently loading from RDB. Our thread starts before RDB loading is finished */
int isRdbLoading(RedisModuleCtx *ctx) {
long long isLoading = 0;
RMUtilInfo *info = RMUtil_GetRedisInfo(ctx);
if (!info) {
return 0;
}
if (!RMUtilInfo_GetInt(info, "loading", &isLoading)) {
isLoading = 0;
}
RMUtilRedisInfo_Free(info);
return isLoading == 1;
}
//---------------------------------------------------------------------------------------------
void IndexSpec_LegacyFree(void *spec) {
// free legacy index do nothing, it will be called only
// when the index key will be deleted and we keep the legacy
// index pointer in the legacySpecDict so we will free it when needed
}
static void IndexSpec_TimedOutProc(RedisModuleCtx *ctx, WeakRef w_ref) {
// we need to delete the spec from the specDict_g, as far as the user see it,
// this spec was deleted and its memory will be freed in a background thread.
// attempt to promote the weak ref to a strong ref
StrongRef spec_ref = WeakRef_Promote(w_ref);
WeakRef_Release(w_ref);
IndexSpec *sp = StrongRef_Get(spec_ref);
if (!sp) {
// the spec was already deleted, nothing to do here
return;
}
RedisModule_Log(RSDummyContext, REDISMODULE_LOGLEVEL_VERBOSE, "Freeing index %s by timer", sp->name);
sp->isTimerSet = false;
if (RS_IsMock) {
IndexSpec_Free(sp);
} else {
// called on master shard for temporary indexes and deletes all documents by defaults
// pass FT.DROPINDEX with "DD" flag to self.
RedisModuleCallReply *rep = RedisModule_Call(RSDummyContext, RS_DROP_INDEX_CMD, "cc!", sp->name, "DD");
if (rep) {
RedisModule_FreeCallReply(rep);
}
}
RedisModule_Log(RSDummyContext, REDISMODULE_LOGLEVEL_VERBOSE, "Freeing index %s by timer: done", sp->name);
StrongRef_Release(spec_ref);
}
// Assuming the GIL is held.
// This can be done without locking the spec for write, since the timer is not modified or read by any other thread.
static void IndexSpec_SetTimeoutTimer(IndexSpec *sp, WeakRef spec_ref) {
if (sp->isTimerSet) {
WeakRef old_timer_ref;
if (RedisModule_StopTimer(RSDummyContext, sp->timerId, (void **)&old_timer_ref) == REDISMODULE_OK) {
WeakRef_Release(old_timer_ref);
}
}
sp->timerId = RedisModule_CreateTimer(RSDummyContext, sp->timeout,
(RedisModuleTimerProc)IndexSpec_TimedOutProc, spec_ref.rm);
sp->isTimerSet = true;
}
// Assuming the spec is properly guarded before calling this function (GIL or write lock).
static void IndexSpec_ResetTimeoutTimer(IndexSpec *sp) {
if (sp->isTimerSet) {
WeakRef old_timer_ref;
if (RedisModule_StopTimer(RSDummyContext, sp->timerId, (void **)&old_timer_ref) == REDISMODULE_OK) {
WeakRef_Release(old_timer_ref);
}
}
sp->timerId = 0;
sp->isTimerSet = false;
}
// Assuming the GIL is locked before calling this function.
void Indexes_SetTempSpecsTimers(TimerOp op) {
dictIterator *iter = dictGetIterator(specDict_g);
dictEntry *entry = NULL;
while ((entry = dictNext(iter))) {
StrongRef spec_ref = dictGetRef(entry);
IndexSpec *sp = StrongRef_Get(spec_ref);
if (sp->flags & Index_Temporary) {
switch (op) {
case TimerOp_Add: IndexSpec_SetTimeoutTimer(sp, StrongRef_Demote(spec_ref)); break;
case TimerOp_Del: IndexSpec_ResetTimeoutTimer(sp); break;
}
}
}
dictReleaseIterator(iter);
}
//---------------------------------------------------------------------------------------------
double IndexesScanner_IndexedPercent(IndexesScanner *scanner, IndexSpec *sp) {
if (scanner || sp->scan_in_progress) {
if (scanner) {
return scanner->totalKeys > 0 ? (double)scanner->scannedKeys / scanner->totalKeys : 0;
} else {
return 0;
}
} else {
return 1.0;
}
}
//---------------------------------------------------------------------------------------------
/* Create a new index spec from a redis command */
// TODO: multithreaded: use global metadata locks to protect global data structures
IndexSpec *IndexSpec_CreateNew(RedisModuleCtx *ctx, RedisModuleString **argv, int argc,
QueryError *status) {
const char *specName = RedisModule_StringPtrLen(argv[1], NULL);
setMemoryInfo(ctx);
if (dictFetchValue(specDict_g, specName)) {
QueryError_SetCode(status, QUERY_EINDEXEXISTS);
return NULL;
}
StrongRef spec_ref = IndexSpec_ParseRedisArgs(ctx, argv[1], &argv[2], argc - 2, status);
IndexSpec *sp = StrongRef_Get(spec_ref);
if (sp == NULL) {
return NULL;
}
// Sets weak and strong references to the spec, then pass it to the spec dictionary
dictAdd(specDict_g, (char *)specName, spec_ref.rm);
sp->uniqueId = spec_unique_ids++;
// Start the garbage collector
IndexSpec_StartGC(ctx, spec_ref, sp);
Cursors_initSpec(sp, RSCURSORS_DEFAULT_CAPACITY);
// Create the indexer
sp->indexer = NewIndexer(sp);
// set timeout for temporary index on master
if ((sp->flags & Index_Temporary) && IsMaster()) {
IndexSpec_SetTimeoutTimer(sp, StrongRef_Demote(spec_ref));
}
if (!(sp->flags & Index_SkipInitialScan)) {
IndexSpec_ScanAndReindex(ctx, spec_ref);
}
return sp;
}
//---------------------------------------------------------------------------------------------
static bool checkPhoneticAlgorithmAndLang(const char *matcher) {
if (strlen(matcher) != 5) {
return false;
}
if (matcher[0] != 'd' || matcher[1] != 'm' || matcher[2] != ':') {
return false;
}
#define LANGUAGES_SIZE 4
char *languages[] = {"en", "pt", "fr", "es"};
bool langauge_found = false;
for (int i = 0; i < LANGUAGES_SIZE; ++i) {
if (matcher[3] == languages[i][0] && matcher[4] == languages[i][1]) {
langauge_found = true;
}
}
return langauge_found;
}
static int parseTextField(FieldSpec *fs, ArgsCursor *ac, QueryError *status) {
int rc;
// this is a text field
// init default weight and type
while (!AC_IsAtEnd(ac)) {
if (AC_AdvanceIfMatch(ac, SPEC_NOSTEM_STR)) {
fs->options |= FieldSpec_NoStemming;
continue;
} else if (AC_AdvanceIfMatch(ac, SPEC_WEIGHT_STR)) {
double d;
if ((rc = AC_GetDouble(ac, &d, 0)) != AC_OK) {
QERR_MKBADARGS_AC(status, "weight", rc);
return 0;
}
fs->ftWeight = d;
continue;
} else if (AC_AdvanceIfMatch(ac, SPEC_PHONETIC_STR)) {
if (AC_IsAtEnd(ac)) {
QueryError_SetError(status, QUERY_EPARSEARGS, SPEC_PHONETIC_STR " requires an argument");
return 0;
}
const char *matcher = AC_GetStringNC(ac, NULL);
// try and parse the matcher
// currently we just make sure algorithm is double metaphone (dm)
// and language is one of the following : English (en), French (fr), Portuguese (pt) and
// Spanish (es)
// in the future we will support more algorithms and more languages
if (!checkPhoneticAlgorithmAndLang(matcher)) {
QueryError_SetError(
status, QUERY_EINVAL,
"Matcher Format: <2 chars algorithm>:<2 chars language>. Support algorithms: "
"double metaphone (dm). Supported languages: English (en), French (fr), "
"Portuguese (pt) and Spanish (es)");
return 0;
}
fs->options |= FieldSpec_Phonetics;
continue;
} else if(AC_AdvanceIfMatch(ac, SPEC_WITHSUFFIXTRIE_STR)) {
fs->options |= FieldSpec_WithSuffixTrie;
} else {
break;
}
}
return 1;
}
// Tries to get vector data type from ac. This function need to stay updated with
// the supported vector data types list of VecSim.
static int parseVectorField_GetType(ArgsCursor *ac, VecSimType *type) {
const char *typeStr;
size_t len;
int rc;
if ((rc = AC_GetString(ac, &typeStr, &len, 0)) != AC_OK) {
return rc;
}
// Uncomment these when support for other type is added.
if (!strncasecmp(VECSIM_TYPE_FLOAT32, typeStr, len))
*type = VecSimType_FLOAT32;
else if (!strncasecmp(VECSIM_TYPE_FLOAT64, typeStr, len))
*type = VecSimType_FLOAT64;
// else if (!strncasecmp(VECSIM_TYPE_INT32, typeStr, len))
// *type = VecSimType_INT32;
// else if (!strncasecmp(VECSIM_TYPE_INT64, typeStr, len))
// *type = VecSimType_INT64;
else
return AC_ERR_ENOENT;
return AC_OK;
}
// Tries to get distance metric from ac. This function need to stay updated with
// the supported distance metric functions list of VecSim.
static int parseVectorField_GetMetric(ArgsCursor *ac, VecSimMetric *metric) {
const char *metricStr;
size_t len;
int rc;
if ((rc = AC_GetString(ac, &metricStr, &len, 0)) != AC_OK) {
return rc;
}
if (!strncasecmp(VECSIM_METRIC_IP, metricStr, len))
*metric = VecSimMetric_IP;
else if (!strncasecmp(VECSIM_METRIC_L2, metricStr, len))
*metric = VecSimMetric_L2;
else if (!strncasecmp(VECSIM_METRIC_COSINE, metricStr, len))
*metric = VecSimMetric_Cosine;
else
return AC_ERR_ENOENT;
return AC_OK;
}
// memoryLimit / 10 - default is 10% of global memory limit
#define BLOCK_MEMORY_LIMIT ((RSGlobalConfig.vssMaxResize) ? RSGlobalConfig.vssMaxResize : memoryLimit / 10)
static int parseVectorField_validate_hnsw(VecSimParams *params, QueryError *status) {
// Calculating max block size (in # of vectors), according to memory limits
size_t maxBlockSize = BLOCK_MEMORY_LIMIT / VecSimIndex_EstimateElementSize(params);
// if Block size was not set by user, sets the default to min(maxBlockSize, DEFAULT_BLOCK_SIZE)
if (params->algoParams.hnswParams.blockSize == 0) { // indicates that block size was not set by the user
params->algoParams.hnswParams.blockSize = MIN(DEFAULT_BLOCK_SIZE, maxBlockSize);
}
if (params->algoParams.hnswParams.initialCapacity == SIZE_MAX) { // indicates that initial capacity was not set by the user
params->algoParams.hnswParams.initialCapacity = params->algoParams.hnswParams.blockSize;
}
size_t index_size_estimation = VecSimIndex_EstimateInitialSize(params);
size_t free_memory = memoryLimit - used_memory;
if (params->algoParams.hnswParams.initialCapacity > maxBlockSize) {
QueryError_SetErrorFmt(status, QUERY_ELIMIT, "Vector index initial capacity %zu exceeded server limit (%zu with the given parameters)", params->algoParams.hnswParams.initialCapacity, maxBlockSize);
return 0;
}
if (params->algoParams.hnswParams.blockSize > maxBlockSize) {
// TODO: uncomment when BLOCK_SIZE is added to FT.CREATE on HNSW
// QueryError_SetErrorFmt(status, QUERY_ELIMIT, "Vector index block size %zu exceeded server limit (%zu with the given parameters)", fs->vectorOpts.vecSimParams.bfParams.blockSize, maxBlockSize);
// return 0;
}
RedisModule_Log(RSDummyContext, "warning", "creating vector index. Server memory limit: %zuB, required memory: %zuB, available memory: %zuB", memoryLimit, index_size_estimation, free_memory);
return 1;
}
static int parseVectorField_validate_flat(VecSimParams *params, QueryError *status) {
size_t elementSize = VecSimIndex_EstimateElementSize(params);
// Calculating max block size (in # of vectors), according to memory limits
size_t maxBlockSize = BLOCK_MEMORY_LIMIT / elementSize;
// if Block size was not set by user, sets the default to min(maxBlockSize, DEFAULT_BLOCK_SIZE)
if (params->algoParams.bfParams.blockSize == 0) { // indicates that block size was not set by the user
params->algoParams.bfParams.blockSize = MIN(DEFAULT_BLOCK_SIZE, maxBlockSize);
}
if (params->algoParams.bfParams.initialCapacity == SIZE_MAX) { // indicates that initial capacity was not set by the user
params->algoParams.bfParams.initialCapacity = params->algoParams.bfParams.blockSize;
}
// Calculating index size estimation, after first vector block was allocated.
size_t index_size_estimation = VecSimIndex_EstimateInitialSize(params);
index_size_estimation += elementSize * params->algoParams.bfParams.blockSize;
size_t free_memory = memoryLimit - used_memory;
if (params->algoParams.bfParams.initialCapacity > maxBlockSize) {
QueryError_SetErrorFmt(status, QUERY_ELIMIT, "Vector index initial capacity %zu exceeded server limit (%zu with the given parameters)", params->algoParams.bfParams.initialCapacity, maxBlockSize);
return 0;
}
if (params->algoParams.bfParams.blockSize > maxBlockSize) {
QueryError_SetErrorFmt(status, QUERY_ELIMIT, "Vector index block size %zu exceeded server limit (%zu with the given parameters)", params->algoParams.bfParams.blockSize, maxBlockSize);
return 0;
}
RedisModule_Log(RSDummyContext, "warning", "creating vector index. Server memory limit: %zuB, required memory: %zuB, available memory: %zuB", memoryLimit, index_size_estimation, free_memory);
return 1;
}
int VecSimIndex_validate_params(RedisModuleCtx *ctx, VecSimParams *params, QueryError *status) {
setMemoryInfo(ctx);
bool valid = false;
if (VecSimAlgo_HNSWLIB == params->algo) {
valid = parseVectorField_validate_hnsw(params, status);
} else if (VecSimAlgo_BF == params->algo) {
valid = parseVectorField_validate_flat(params, status);
} else if (VecSimAlgo_TIERED == params->algo) {
return VecSimIndex_validate_params(ctx, params->algoParams.tieredParams.primaryIndexParams, status);
}
return valid ? REDISMODULE_OK : REDISMODULE_ERR;
}
static int parseVectorField_hnsw(FieldSpec *fs, VecSimParams *params, ArgsCursor *ac, QueryError *status) {
int rc;
// HNSW mandatory params.
bool mandtype = false;
bool mandsize = false;
bool mandmetric = false;
// Get number of parameters
size_t expNumParam, numParam = 0;
if ((rc = AC_GetSize(ac, &expNumParam, 0)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity number of parameters", rc);
return 0;
} else if (expNumParam % 2) {
QERR_MKBADARGS_FMT(status, "Bad number of arguments for vector similarity index: got %d but expected even number (as algorithm parameters should be submitted as named arguments)", expNumParam);
return 0;
} else {
expNumParam /= 2;
}
while (expNumParam > numParam && !AC_IsAtEnd(ac)) {
if (AC_AdvanceIfMatch(ac, VECSIM_TYPE)) {
if ((rc = parseVectorField_GetType(ac, ¶ms->algoParams.hnswParams.type)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity HNSW index type", rc);
return 0;
}
mandtype = true;
} else if (AC_AdvanceIfMatch(ac, VECSIM_DIM)) {
if ((rc = AC_GetSize(ac, ¶ms->algoParams.hnswParams.dim, AC_F_GE1)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity HNSW index dim", rc);
return 0;
}
mandsize = true;
} else if (AC_AdvanceIfMatch(ac, VECSIM_DISTANCE_METRIC)) {
if ((rc = parseVectorField_GetMetric(ac, ¶ms->algoParams.hnswParams.metric)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity HNSW index metric", rc);
return 0;
}
mandmetric = true;
} else if (AC_AdvanceIfMatch(ac, VECSIM_INITIAL_CAP)) {
if ((rc = AC_GetSize(ac, ¶ms->algoParams.hnswParams.initialCapacity, 0)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity HNSW index initial cap", rc);
return 0;
}
} else if (AC_AdvanceIfMatch(ac, VECSIM_M)) {
if ((rc = AC_GetSize(ac, ¶ms->algoParams.hnswParams.M, AC_F_GE1)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity HNSW index m", rc);
return 0;
}
} else if (AC_AdvanceIfMatch(ac, VECSIM_EFCONSTRUCTION)) {
if ((rc = AC_GetSize(ac, ¶ms->algoParams.hnswParams.efConstruction, AC_F_GE1)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity HNSW index efConstruction", rc);
return 0;
}
} else if (AC_AdvanceIfMatch(ac, VECSIM_EFRUNTIME)) {
if ((rc = AC_GetSize(ac, ¶ms->algoParams.hnswParams.efRuntime, AC_F_GE1)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity HNSW index efRuntime", rc);
return 0;
}
} else if (AC_AdvanceIfMatch(ac, VECSIM_EPSILON)) {
if ((rc = AC_GetDouble(ac, ¶ms->algoParams.hnswParams.epsilon, AC_F_GE0)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity HNSW index epsilon", rc);
return 0;
}
} else {
QERR_MKBADARGS_FMT(status, "Bad arguments for algorithm %s: %s", VECSIM_ALGORITHM_HNSW, AC_GetStringNC(ac, NULL));
return 0;
}
numParam++;
}
if (expNumParam > numParam) {
QERR_MKBADARGS_FMT(status, "Expected %d parameters but got %d", expNumParam * 2, numParam * 2);
return 0;
}
if (!mandtype) {
VECSIM_ERR_MANDATORY(status, VECSIM_ALGORITHM_HNSW, VECSIM_TYPE);
return 0;
}
if (!mandsize) {
VECSIM_ERR_MANDATORY(status, VECSIM_ALGORITHM_HNSW, VECSIM_DIM);
return 0;
}
if (!mandmetric) {
VECSIM_ERR_MANDATORY(status, VECSIM_ALGORITHM_HNSW, VECSIM_DISTANCE_METRIC);
return 0;
}
// Calculating expected blob size of a vector in bytes.
fs->vectorOpts.expBlobSize = params->algoParams.hnswParams.dim * VecSimType_sizeof(params->algoParams.hnswParams.type);
return parseVectorField_validate_hnsw(params, status);
}
static int parseVectorField_flat(FieldSpec *fs, VecSimParams *params, ArgsCursor *ac, QueryError *status) {
int rc;
// BF mandatory params.
bool mandtype = false;
bool mandsize = false;
bool mandmetric = false;
// Get number of parameters
size_t expNumParam, numParam = 0;
if ((rc = AC_GetSize(ac, &expNumParam, 0)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity number of parameters", rc);
return 0;
} else if (expNumParam % 2) {
QERR_MKBADARGS_FMT(status, "Bad number of arguments for vector similarity index: got %d but expected even number as algorithm parameters (should be submitted as named arguments)", expNumParam);
return 0;
} else {
expNumParam /= 2;
}
while (expNumParam > numParam && !AC_IsAtEnd(ac)) {
if (AC_AdvanceIfMatch(ac, VECSIM_TYPE)) {
if ((rc = parseVectorField_GetType(ac, ¶ms->algoParams.bfParams.type)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity FLAT index type", rc);
return 0;
}
mandtype = true;
} else if (AC_AdvanceIfMatch(ac, VECSIM_DIM)) {
if ((rc = AC_GetSize(ac, ¶ms->algoParams.bfParams.dim, AC_F_GE1)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity FLAT index dim", rc);
return 0;
}
mandsize = true;
} else if (AC_AdvanceIfMatch(ac, VECSIM_DISTANCE_METRIC)) {
if ((rc = parseVectorField_GetMetric(ac, ¶ms->algoParams.bfParams.metric)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity FLAT index metric", rc);
return 0;
}
mandmetric = true;
} else if (AC_AdvanceIfMatch(ac, VECSIM_INITIAL_CAP)) {
if ((rc = AC_GetSize(ac, ¶ms->algoParams.bfParams.initialCapacity, 0)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity FLAT index initial cap", rc);
return 0;
}
} else if (AC_AdvanceIfMatch(ac, VECSIM_BLOCKSIZE)) {
if ((rc = AC_GetSize(ac, ¶ms->algoParams.bfParams.blockSize, AC_F_GE1)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity FLAT index blocksize", rc);
return 0;
}
} else {
QERR_MKBADARGS_FMT(status, "Bad arguments for algorithm %s: %s", VECSIM_ALGORITHM_BF, AC_GetStringNC(ac, NULL));
return 0;
}
numParam++;
}
if (expNumParam > numParam) {
QERR_MKBADARGS_FMT(status, "Expected %d parameters but got %d", expNumParam * 2, numParam * 2);
return 0;
}
if (!mandtype) {
VECSIM_ERR_MANDATORY(status, VECSIM_ALGORITHM_BF, VECSIM_TYPE);
return 0;
}
if (!mandsize) {
VECSIM_ERR_MANDATORY(status, VECSIM_ALGORITHM_BF, VECSIM_DIM);
return 0;
}
if (!mandmetric) {
VECSIM_ERR_MANDATORY(status, VECSIM_ALGORITHM_BF, VECSIM_DISTANCE_METRIC);
return 0;
}
// Calculating expected blob size of a vector in bytes.
fs->vectorOpts.expBlobSize = params->algoParams.bfParams.dim * VecSimType_sizeof(params->algoParams.bfParams.type);
return parseVectorField_validate_flat(&fs->vectorOpts.vecSimParams, status);
}
static int parseVectorField(IndexSpec *sp, StrongRef sp_ref, FieldSpec *fs, ArgsCursor *ac, QueryError *status) {
// this is a vector field
// init default type, size, distance metric and algorithm
memset(&fs->vectorOpts.vecSimParams, 0, sizeof(VecSimParams));
// If the index is on JSON and the given path is dynamic, create a multi-value index.
bool multi = false;
if (isSpecJson(sp)) {
RedisModuleString *err_msg;
JSONPath jsonPath = pathParse(fs->path, &err_msg);
if (!jsonPath) {
if (err_msg) {
JSONParse_error(status, err_msg, fs->path, fs->name, sp->name);
}
return 0;
}
multi = !(pathIsSingle(jsonPath));
pathFree(jsonPath);
}
// parse algorithm
const char *algStr;
size_t len;
int rc;
if ((rc = AC_GetString(ac, &algStr, &len, 0)) != AC_OK) {
QERR_MKBADARGS_AC(status, "vector similarity algorithm", rc);
return 0;
}
VecSimLogCtx *logCtx = rm_new(VecSimLogCtx);
logCtx->index_field_name = fs->name;
fs->vectorOpts.vecSimParams.logCtx = logCtx;
if (!strncasecmp(VECSIM_ALGORITHM_BF, algStr, len)) {
fs->vectorOpts.vecSimParams.algo = VecSimAlgo_BF;
fs->vectorOpts.vecSimParams.algoParams.bfParams.initialCapacity = SIZE_MAX;
fs->vectorOpts.vecSimParams.algoParams.bfParams.blockSize = 0;
fs->vectorOpts.vecSimParams.algoParams.bfParams.multi = multi;
return parseVectorField_flat(fs, &fs->vectorOpts.vecSimParams, ac, status);
} else if (!strncasecmp(VECSIM_ALGORITHM_HNSW, algStr, len)) {
fs->vectorOpts.vecSimParams.algo = VecSimAlgo_TIERED;
VecSim_TieredParams_Init(&fs->vectorOpts.vecSimParams.algoParams.tieredParams, sp_ref);
fs->vectorOpts.vecSimParams.algoParams.tieredParams.specificParams.tieredHnswParams.swapJobThreshold = 0; // Will be set to default value.
VecSimParams *params = fs->vectorOpts.vecSimParams.algoParams.tieredParams.primaryIndexParams;
params->algo = VecSimAlgo_HNSWLIB;
params->algoParams.hnswParams.initialCapacity = SIZE_MAX;
params->algoParams.hnswParams.blockSize = 0;
params->algoParams.hnswParams.M = HNSW_DEFAULT_M;
params->algoParams.hnswParams.efConstruction = HNSW_DEFAULT_EF_C;
params->algoParams.hnswParams.efRuntime = HNSW_DEFAULT_EF_RT;
params->algoParams.hnswParams.multi = multi;
// Point to the same logCtx as the external wrapping VecSimParams object, which is the owner.
params->logCtx = logCtx;
return parseVectorField_hnsw(fs, params, ac, status);
} else {
QERR_MKBADARGS_AC(status, "vector similarity algorithm", AC_ERR_ENOENT);
return 0;
}
}
/* Parse a field definition from argv, at *offset. We advance offset as we progress.
* Returns 1 on successful parse, 0 otherwise */
static int parseFieldSpec(ArgsCursor *ac, IndexSpec *sp, StrongRef sp_ref, FieldSpec *fs, QueryError *status) {
if (AC_IsAtEnd(ac)) {
QueryError_SetErrorFmt(status, QUERY_EPARSEARGS, "Field `%s` does not have a type", fs->name);
return 0;
}
if (AC_AdvanceIfMatch(ac, SPEC_TEXT_STR)) { // text field
fs->types |= INDEXFLD_T_FULLTEXT;
if (!parseTextField(fs, ac, status)) {
goto error;
}
} else if (AC_AdvanceIfMatch(ac, SPEC_NUMERIC_STR)) { // numeric field
fs->types |= INDEXFLD_T_NUMERIC;
} else if (AC_AdvanceIfMatch(ac, SPEC_GEO_STR)) { // geo field
fs->types |= INDEXFLD_T_GEO;
} else if (AC_AdvanceIfMatch(ac, SPEC_VECTOR_STR)) { // vector field
sp->flags |= Index_HasVecSim;
fs->types |= INDEXFLD_T_VECTOR;
if (!parseVectorField(sp, sp_ref, fs, ac, status)) {
goto error;
}
return 1;
} else if (AC_AdvanceIfMatch(ac, SPEC_TAG_STR)) { // tag field
fs->types |= INDEXFLD_T_TAG;
while (!AC_IsAtEnd(ac)) {
if (AC_AdvanceIfMatch(ac, SPEC_TAG_SEPARATOR_STR)) {
if (AC_IsAtEnd(ac)) {
QueryError_SetError(status, QUERY_EPARSEARGS, SPEC_TAG_SEPARATOR_STR " requires an argument");
goto error;
}
const char *sep = AC_GetStringNC(ac, NULL);
if (strlen(sep) != 1) {
QueryError_SetErrorFmt(status, QUERY_EPARSEARGS,
"Tag separator must be a single character. Got `%s`", sep);
goto error;
}
fs->tagOpts.tagSep = *sep;
} else if (AC_AdvanceIfMatch(ac, SPEC_TAG_CASE_SENSITIVE_STR)) {
fs->tagOpts.tagFlags |= TagField_CaseSensitive;
} else if (AC_AdvanceIfMatch(ac, SPEC_WITHSUFFIXTRIE_STR)) {
fs->options |= FieldSpec_WithSuffixTrie;
} else {
break;
}
}
} else if (AC_AdvanceIfMatch(ac, SPEC_GEOMETRY_STR)) { // geometry field
sp->flags |= Index_HasGeometry;
fs->types |= INDEXFLD_T_GEOMETRY;
if (AC_AdvanceIfMatch(ac, SPEC_GEOMETRY_FLAT_STR)) {
fs->geometryOpts.geometryCoords = GEOMETRY_COORDS_Cartesian;
} else if (AC_AdvanceIfMatch(ac, SPEC_GEOMETRY_SPHERE_STR)) {
fs->geometryOpts.geometryCoords = GEOMETRY_COORDS_Geographic;
} else {
fs->geometryOpts.geometryCoords = GEOMETRY_COORDS_Geographic;
}
} else { // nothing more supported currently
QueryError_SetErrorFmt(status, QUERY_EPARSEARGS, "Invalid field type for field `%s`", fs->name);
goto error;
}
while (!AC_IsAtEnd(ac)) {
if (AC_AdvanceIfMatch(ac, SPEC_SORTABLE_STR)) {
FieldSpec_SetSortable(fs);
if (AC_AdvanceIfMatch(ac, SPEC_UNF_STR) || // Explicitly requested UNF
FIELD_IS(fs, INDEXFLD_T_NUMERIC) || // We don't normalize numeric fields. Implicit UNF
TAG_FIELD_IS(fs, TagField_CaseSensitive)) { // We don't normalize case sensitive tags. Implicit UNF
fs->options |= FieldSpec_UNF;
}
continue;
} else if (AC_AdvanceIfMatch(ac, SPEC_NOINDEX_STR)) {
fs->options |= FieldSpec_NotIndexable;
continue;
} else {
break;
}
}
return 1;
error:
if (!QueryError_HasError(status)) {
QueryError_SetErrorFmt(status, QUERY_EPARSEARGS, "Could not parse schema for field `%s`",
fs->name);
}
return 0;
}
// Assuming the spec is properly locked before calling this function.
size_t IndexSpec_VectorIndexSize(IndexSpec *sp) {
size_t total_memory = 0;
for (size_t i = 0; i < sp->numFields; ++i) {
const FieldSpec *fs = sp->fields + i;
if (FIELD_IS(fs, INDEXFLD_T_VECTOR)) {
RedisModuleString *vecsim_name = IndexSpec_GetFormattedKey(sp, fs, INDEXFLD_T_VECTOR);
VecSimIndex *vecsim = OpenVectorIndex(sp, vecsim_name);
total_memory += VecSimIndex_Info(vecsim).commonInfo.memory;
}
}
return total_memory;
}
// Assuming the spec is properly locked before calling this function.
int IndexSpec_CreateTextId(const IndexSpec *sp) {
int maxId = -1;
for (size_t ii = 0; ii < sp->numFields; ++ii) {
const FieldSpec *fs = sp->fields + ii;
if (FIELD_IS(fs, INDEXFLD_T_FULLTEXT)) {
if (fs->ftId == (t_fieldId)-1) {
// ignore
continue;
}
maxId = MAX(fs->ftId, maxId);
}
}
if (maxId + 1 >= SPEC_MAX_FIELD_ID) {
return -1;
}
return maxId + 1;
}
static IndexSpecCache *IndexSpec_BuildSpecCache(const IndexSpec *spec);
/**
* Add fields to an existing (or newly created) index. If the addition fails,
*/
static int IndexSpec_AddFieldsInternal(IndexSpec *sp, StrongRef spec_ref, ArgsCursor *ac,
QueryError *status, int isNew) {
if (ac->offset == ac->argc) {
QueryError_SetErrorFmt(status, QUERY_EPARSEARGS, "Fields arguments are missing");
return 0;
}
const size_t prevNumFields = sp->numFields;
const size_t prevSortLen = sp->sortables->len;
const IndexFlags prevFlags = sp->flags;
while (!AC_IsAtEnd(ac)) {
if (sp->numFields == SPEC_MAX_FIELDS) {
QueryError_SetErrorFmt(status, QUERY_ELIMIT, "Schema is limited to %d fields",
SPEC_MAX_FIELDS);
goto reset;
}
// Parse path and name of field
size_t pathlen, namelen;
const char *fieldPath = AC_GetStringNC(ac, &pathlen);
const char *fieldName = fieldPath;
if (AC_AdvanceIfMatch(ac, SPEC_AS_STR)) {
if (AC_IsAtEnd(ac)) {
QueryError_SetError(status, QUERY_EPARSEARGS, SPEC_AS_STR " requires an argument");
goto reset;
}
fieldName = AC_GetStringNC(ac, &namelen);
sp->flags |= Index_HasFieldAlias;
} else {
// if `AS` is not used, set the path as name
namelen = pathlen;
fieldPath = NULL;
}
if (IndexSpec_GetField(sp, fieldName, namelen)) {
QueryError_SetErrorFmt(status, QUERY_EINVAL, "Duplicate field in schema - %s", fieldName);
goto reset;
}
FieldSpec *fs = IndexSpec_CreateField(sp, fieldName, fieldPath);
if (!parseFieldSpec(ac, sp, spec_ref, fs, status)) {
goto reset;
}
if (FIELD_IS(fs, INDEXFLD_T_FULLTEXT) && FieldSpec_IsIndexable(fs)) {
int textId = IndexSpec_CreateTextId(sp);
if (textId < 0) {
QueryError_SetErrorFmt(status, QUERY_ELIMIT, "Schema is limited to %d TEXT fields",
SPEC_MAX_FIELD_ID);
goto reset;
}
// If we need to store field flags and we have over 32 fields, we need to switch to wide
// schema encoding
if (textId >= SPEC_WIDEFIELD_THRESHOLD && (sp->flags & Index_StoreFieldFlags)) {
if (isNew) {
sp->flags |= Index_WideSchema;
} else if ((sp->flags & Index_WideSchema) == 0) {
QueryError_SetError(
status, QUERY_ELIMIT,
"Cannot add more fields. Declare index with wide fields to allow adding "
"unlimited fields");
goto reset;
}
}
fs->ftId = textId;
if isSpecJson (sp) {
if ((sp->flags & Index_HasFieldAlias) && (sp->flags & Index_StoreTermOffsets)) {
RedisModuleString *err_msg;
JSONPath jsonPath = pathParse(fs->path, &err_msg);
if (jsonPath && pathHasDefinedOrder(jsonPath)) {
// Ordering is well defined
fs->options &= ~FieldSpec_UndefinedOrder;
} else {
// Mark FieldSpec
fs->options |= FieldSpec_UndefinedOrder;
// Mark IndexSpec
sp->flags |= Index_HasUndefinedOrder;
}
if (jsonPath) {
pathFree(jsonPath);
} else if (err_msg) {
JSONParse_error(status, err_msg, fs->path, fs->name, sp->name);
goto reset;
} /* else {
RedisModule_Log(RSDummyContext, "info",
"missing RedisJSON API to parse JSONPath '%s' in attribute '%s' in index '%s', assuming undefined ordering",
fs->path, fs->name, sp->name);
} */
}
}
}
if (FieldSpec_IsSortable(fs)) {
if (isSpecJson(sp)) {
// SORTABLE JSON field is always UNF