redis 1.8.1

Redis driver for Rust.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
#![cfg(feature = "search_unfinished")]

mod support;
use crate::support::*;
use redis::Commands;
use redis::schema;
use redis::search::*;
use redis_test::server::Module;

static TEXT_FIELD_NAME: &str = "title";
static NUMERIC_FIELD_NAME: &str = "price";
static TAG_FIELD_NAME: &str = "condition";
static GEO_FIELD_NAME: &str = "location";
static VECTOR_FIELD_NAME: &str = "embedding";
static GEOSHAPE_FIELD_NAME: &str = "area";

/// One modifier applies a single setting to a field (or to the create options) and returns it.
type Modifier<T> = fn(T) -> T;

fn assert_no_index_and_index_missing_exclusivity_for_field(
    result: redis::RedisResult<String>,
    field_name: &str,
) {
    let server_error = redis::ServerError::try_from(result.unwrap_err()).unwrap();
    assert!(server_error.details().is_some_and(|details| {
        details.contains(
            format!("cannot be defined with both `NOINDEX` and `INDEXMISSING` `{field_name}`")
                .as_str(),
        )
    }));
}

fn assert_index_already_exists_error(result: redis::RedisResult<String>) {
    let server_error = redis::ServerError::try_from(result.unwrap_err()).unwrap();
    assert!(
        server_error
            .details()
            .is_some_and(|details| details.contains("already exists"))
    );
}

/// Build a single-field index whose field carries both `NOINDEX` and `INDEXMISSING`,
/// then assert the server rejects it as a conflict.
fn assert_no_index_and_index_missing_conflict<C, T>(con: &mut C, field_name: &str, field: T)
where
    C: redis::ConnectionLike,
    T: Into<FieldDefinition>,
{
    let result = con.ft_create::<_, String>(
        "invalid_index",
        &CreateOptions::new(),
        &SearchSchema::new(field_name, field),
    );
    assert_no_index_and_index_missing_exclusivity_for_field(result, field_name);
}

/// Drive the FT.CREATE modifier matrix shared by the create-options test and every field type.
///
/// It runs these blocks in order:
///   1. each portable modifier on its own,
///   2. the portable modifiers combined cumulatively,
///   3. (Redis only) each Redis-only and mutually-exclusive modifier on its own,
///   4. (Redis only) the Redis-only modifiers added onto the combined base cumulatively,
///   5. (Redis only) each mutually-exclusive modifier added onto the fully combined base.
///
/// valkey-search rejects everything past block 2, so the run stops there when `is_valkey`.
/// `base` builds a fresh value, `create` runs FT.CREATE for one accumulated value, and
/// `on_created` receives every created index name (the clustered tests use it to check
/// propagation).
#[allow(clippy::too_many_arguments)]
fn run_modifier_matrix<C, T>(
    con: &mut C,
    index_prefix: &str,
    base: impl Fn() -> T,
    portable: &[(&str, Modifier<T>)],
    redis_only: &[(&str, Modifier<T>)],
    mutually_exclusive: &[(&str, Modifier<T>)],
    is_valkey: bool,
    mut on_created: impl FnMut(&str),
    create: impl Fn(&mut C, &str, &T) -> redis::RedisResult<String>,
) where
    C: redis::ConnectionLike,
    T: Clone,
{
    // 1. Each portable modifier on a fresh base.
    for (suffix, modifier) in portable {
        let index_name = format!("index_for_{index_prefix}_with_{suffix}");
        assert_eq!(
            create(con, &index_name, &modifier(base())),
            Ok("OK".to_string())
        );
        on_created(&index_name);
    }

    // 2. Portable modifiers combined cumulatively.
    let mut combined = base();
    for (suffix, modifier) in portable {
        let index_name = format!("index_for_{index_prefix}_combined_until_{suffix}");
        combined = modifier(combined);
        assert_eq!(create(con, &index_name, &combined), Ok("OK".to_string()));
        on_created(&index_name);
    }

    // valkey-search rejects everything below, so stop here for it.
    if is_valkey {
        return;
    }

    // 3. Each Redis-only and mutually-exclusive modifier on a fresh base.
    for (suffix, modifier) in redis_only.iter().chain(mutually_exclusive) {
        let index_name = format!("index_for_{index_prefix}_with_{suffix}");
        assert_eq!(
            create(con, &index_name, &modifier(base())),
            Ok("OK".to_string())
        );
        on_created(&index_name);
    }

    // 4. Redis-only modifiers added onto the combined base cumulatively.
    for (suffix, modifier) in redis_only {
        let index_name = format!("index_for_{index_prefix}_combined_until_{suffix}");
        combined = modifier(combined);
        assert_eq!(create(con, &index_name, &combined), Ok("OK".to_string()));
        on_created(&index_name);
    }

    // 5. Each mutually-exclusive modifier added onto the fully combined base.
    for (suffix, modifier) in mutually_exclusive {
        let index_name = format!("index_for_{index_prefix}_all_combined_with_{suffix}");
        assert_eq!(
            create(con, &index_name, &modifier(combined.clone())),
            Ok("OK".to_string())
        );
        on_created(&index_name);
    }
}

// Basic create — Redis and Valkey.

#[test]
fn test_module_search_ft_create_with_an_empty_index_name() {
    let ctx = run_test_if_version_supported!(
        &[REDIS_SEARCH_8_0, VALKEY_SEARCH_ANY][..],
        &[Module::Search]
    );
    let mut con = ctx.connection();
    let empty_index_name = "";
    let options = CreateOptions::new();
    let schema = schema! {
        TEXT_FIELD_NAME => SchemaTextField::new()
    };
    // Check that the first call succeeds but the second one fails because the index already exists
    assert_eq!(
        con.ft_create(empty_index_name, &options, &schema),
        Ok("OK".to_string())
    );
    assert_index_already_exists_error(con.ft_create::<_, String>(
        empty_index_name,
        &options,
        &schema,
    ));
}

fn run_simple_ft_create<C, F>(con: &mut C, index_name: &str, mut on_created: F)
where
    C: redis::ConnectionLike,
    F: FnMut(&str),
{
    let options = CreateOptions::new();
    let schema = schema! {
        TEXT_FIELD_NAME => SchemaTextField::new()
    };
    // Check that the first call succeeds but the second one fails because the index already exists
    assert_eq!(
        con.ft_create(index_name, &options, &schema),
        Ok("OK".to_string())
    );
    on_created(index_name);
    assert_index_already_exists_error(con.ft_create::<_, String>(index_name, &options, &schema));
}

#[test]
fn test_module_search_simple_ft_create() {
    let ctx = run_test_if_version_supported!(
        &[REDIS_SEARCH_8_0, VALKEY_SEARCH_ANY][..],
        &[Module::Search]
    );
    run_simple_ft_create(&mut ctx.connection(), "index", |_| {});
}

// FT.CREATE create options and per-field-type schema coverage.

#[test]
fn test_module_search_ft_create_create_options() {
    // Portable options on both servers; the full option matrix (e.g. FILTER,
    // TEMPORARY, MAXTEXTFIELDS) on Redis only, as valkey-search rejects it.
    let ctx = run_test_if_version_supported!(
        &[REDIS_SEARCH_8_0, VALKEY_SEARCH_ANY][..],
        &[Module::Search]
    );
    let is_valkey = ctx.supports(VALKEY_SEARCH_ANY);
    let mut con = ctx.connection();
    let schema = schema! {
        TEXT_FIELD_NAME => SchemaTextField::new()
    };

    // Portable options — accepted by both Redis and valkey-search.
    let portable: Vec<(&'static str, Modifier<CreateOptions>)> = vec![
        ("on_hash", |opts| opts.on(IndexDataType::Hash)),
        ("single_prefix", |opts| opts.prefix("pref1")),
        ("multiple_prefixes", |opts| {
            opts.prefix("pref2").prefix("pref3")
        }),
        ("language", |opts| opts.language(SearchLanguage::English)),
        ("score", |opts| opts.score(1.0)),
        ("no_offsets", |opts| opts.no_offsets()),
        ("single_stopword", |opts| opts.stopword("stopword1")),
        ("multiple_stopwords", |opts| {
            opts.stopword("stopword2").stopword("stopword3")
        }),
        ("skip_initial_scan", |opts| opts.skip_initial_scan()),
    ];

    // Redis-only options.
    let redis_only: Vec<(&'static str, Modifier<CreateOptions>)> = vec![
        ("filter", |opts| opts.filter("@field: value")),
        ("language_field", |opts| {
            opts.language_field("language_field")
        }),
        ("score_field", |opts| opts.score_field("score_field")),
        ("temporary", |opts| opts.temporary(1)),
        ("no_highlight", |opts| opts.no_highlight()),
        ("no_freqs", |opts| opts.no_freqs()),
    ];

    // `max_text_fields` (MAXTEXTFIELDS) and `no_fields` (NOFIELDS) are mutually exclusive on
    // newer versions of RediSearch, so they shouldn't be combined with each other.
    let mutually_exclusive: Vec<(&'static str, Modifier<CreateOptions>)> = vec![
        ("max_text_fields", |opts| opts.max_text_fields()),
        ("no_fields", |opts| opts.no_fields()),
    ];

    run_modifier_matrix(
        &mut con,
        "options",
        CreateOptions::new,
        &portable,
        &redis_only,
        &mutually_exclusive,
        is_valkey,
        |_| {},
        |con, index_name, options: &CreateOptions| con.ft_create(index_name, options, &schema),
    );
}

fn run_ft_create_schema_text_field<C, F>(con: &mut C, is_valkey: bool, on_created: F)
where
    C: redis::ConnectionLike,
    F: FnMut(&str),
{
    // Portable modifiers — accepted by both Redis and valkey-search.
    let portable: Vec<(&'static str, Modifier<SchemaTextField>)> = vec![
        ("alias", |field| field.alias("text_alias")),
        ("sortable", |field| field.sortable(Sortable::Yes)),
        ("no_stem", |field| field.no_stem(true)),
        ("weight", |field| field.weight(1.0)),
        ("with_suffix_trie", |field| field.with_suffix_trie(true)),
    ];

    // Redis-only modifiers.
    let redis_only: Vec<(&'static str, Modifier<SchemaTextField>)> = vec![
        ("sortable_unf", |field| field.sortable(Sortable::Unf)),
        ("phonetic", |field| field.phonetic(Phonetic::DmEnglish)),
        ("index_empty", |field| field.index_empty(true)),
    ];

    // Redis-only modifiers that are mutually exclusive.
    let mutually_exclusive: Vec<(&'static str, Modifier<SchemaTextField>)> = vec![
        ("index_missing", |field| field.index_missing(true)),
        ("no_index", |field| field.no_index(true)),
    ];

    run_modifier_matrix(
        con,
        "text_field",
        SchemaTextField::new,
        &portable,
        &redis_only,
        &mutually_exclusive,
        is_valkey,
        on_created,
        |con, index_name, field: &SchemaTextField| {
            con.ft_create(
                index_name,
                &CreateOptions::new(),
                &SearchSchema::new(TEXT_FIELD_NAME, field.clone()),
            )
        },
    );

    // valkey-search never reaches the Redis-only modifiers, so only check the conflict on Redis.
    if !is_valkey {
        assert_no_index_and_index_missing_conflict(
            con,
            TEXT_FIELD_NAME,
            SchemaTextField::new().no_index(true).index_missing(true),
        );
    }
}

#[test]
fn test_module_search_ft_create_schema_text_field() {
    // Portable subset on both servers; the full matrix (e.g. SORTABLE UNF,
    // PHONETIC, INDEXMISSING) on Redis only, as valkey-search rejects it.
    let ctx = run_test_if_version_supported!(
        &[REDIS_SEARCH_8_0, VALKEY_SEARCH_ANY][..],
        &[Module::Search]
    );
    let is_valkey = ctx.supports(VALKEY_SEARCH_ANY);
    run_ft_create_schema_text_field(&mut ctx.connection(), is_valkey, |_| {});
}

fn run_ft_create_schema_tag_field<C, F>(con: &mut C, is_valkey: bool, on_created: F)
where
    C: redis::ConnectionLike,
    F: FnMut(&str),
{
    // Portable modifiers — accepted by both Redis and valkey-search.
    let portable: Vec<(&'static str, Modifier<SchemaTagField>)> = vec![
        ("alias", |field| field.alias("tag_alias")),
        ("sortable", |field| field.sortable(Sortable::Yes)),
        ("separator", |field| field.separator(',')),
        ("case_sensitive", |field| field.case_sensitive(true)),
    ];

    // Redis-only modifiers.
    let redis_only: Vec<(&'static str, Modifier<SchemaTagField>)> = vec![
        ("sortable_unf", |field| field.sortable(Sortable::Unf)),
        ("with_suffix_trie", |field| field.with_suffix_trie(true)),
        ("index_empty", |field| field.index_empty(true)),
    ];

    // Redis-only modifiers that are mutually exclusive.
    let mutually_exclusive: Vec<(&'static str, Modifier<SchemaTagField>)> = vec![
        ("index_missing", |field| field.index_missing(true)),
        ("no_index", |field| field.no_index(true)),
    ];

    run_modifier_matrix(
        con,
        "tag_field",
        SchemaTagField::new,
        &portable,
        &redis_only,
        &mutually_exclusive,
        is_valkey,
        on_created,
        |con, index_name, field: &SchemaTagField| {
            con.ft_create(
                index_name,
                &CreateOptions::new(),
                &SearchSchema::new(TAG_FIELD_NAME, field.clone()),
            )
        },
    );

    // valkey-search never reaches the Redis-only modifiers, so only check the conflict on Redis.
    if !is_valkey {
        assert_no_index_and_index_missing_conflict(
            con,
            TAG_FIELD_NAME,
            SchemaTagField::new().no_index(true).index_missing(true),
        );
    }
}

#[test]
fn test_module_search_ft_create_schema_tag_field() {
    // Portable subset on both servers; the full matrix (e.g. SORTABLE UNF,
    // WITHSUFFIXTRIE, INDEXMISSING) on Redis only, as valkey-search rejects it.
    let ctx = run_test_if_version_supported!(
        &[REDIS_SEARCH_8_0, VALKEY_SEARCH_ANY][..],
        &[Module::Search]
    );
    let is_valkey = ctx.supports(VALKEY_SEARCH_ANY);
    run_ft_create_schema_tag_field(&mut ctx.connection(), is_valkey, |_| {});
}

fn run_ft_create_schema_numeric_field<C, F>(con: &mut C, is_valkey: bool, on_created: F)
where
    C: redis::ConnectionLike,
    F: FnMut(&str),
{
    // Portable modifiers — accepted by both Redis and valkey-search.
    let portable: Vec<(&'static str, Modifier<SchemaNumericField>)> = vec![
        ("alias", |field| field.alias("numeric_alias")),
        ("sortable", |field| field.sortable(Sortable::Yes)),
    ];

    // Redis-only modifiers.
    let redis_only: Vec<(&'static str, Modifier<SchemaNumericField>)> =
        vec![("sortable_unf", |field| field.sortable(Sortable::Unf))];

    // Redis-only modifiers that are mutually exclusive.
    let mutually_exclusive: Vec<(&'static str, Modifier<SchemaNumericField>)> = vec![
        ("index_missing", |field| field.index_missing(true)),
        ("no_index", |field| field.no_index(true)),
    ];

    run_modifier_matrix(
        con,
        "numeric_field",
        SchemaNumericField::new,
        &portable,
        &redis_only,
        &mutually_exclusive,
        is_valkey,
        on_created,
        |con, index_name, field: &SchemaNumericField| {
            con.ft_create(
                index_name,
                &CreateOptions::new(),
                &SearchSchema::new(NUMERIC_FIELD_NAME, field.clone()),
            )
        },
    );

    // valkey-search never reaches the Redis-only modifiers, so only check the conflict on Redis.
    if !is_valkey {
        assert_no_index_and_index_missing_conflict(
            con,
            NUMERIC_FIELD_NAME,
            SchemaNumericField::new().no_index(true).index_missing(true),
        );
    }
}

#[test]
fn test_module_search_ft_create_schema_numeric_field() {
    // Portable subset on both servers; the full matrix (e.g. SORTABLE UNF,
    // INDEXMISSING) on Redis only, as valkey-search rejects it.
    let ctx = run_test_if_version_supported!(
        &[REDIS_SEARCH_8_0, VALKEY_SEARCH_ANY][..],
        &[Module::Search]
    );
    let is_valkey = ctx.supports(VALKEY_SEARCH_ANY);
    run_ft_create_schema_numeric_field(&mut ctx.connection(), is_valkey, |_| {});
}

fn run_ft_create_schema_geo_field<C, F>(con: &mut C, on_created: F)
where
    C: redis::ConnectionLike,
    F: FnMut(&str),
{
    // GEO is Redis-only, so every modifier runs on Redis (`is_valkey` is always false here).
    let field_modifiers: Vec<(&'static str, Modifier<SchemaGeoField>)> = vec![
        ("alias", |field| field.alias("geo_alias")),
        ("sortable", |field| field.sortable(Sortable::Yes)),
        ("sortable_unf", |field| field.sortable(Sortable::Unf)),
    ];

    // Modifiers that are mutually exclusive.
    let mutually_exclusive: Vec<(&'static str, Modifier<SchemaGeoField>)> = vec![
        ("index_missing", |field| field.index_missing(true)),
        ("no_index", |field| field.no_index(true)),
    ];

    run_modifier_matrix(
        con,
        "geo_field",
        SchemaGeoField::new,
        &field_modifiers,
        &[],
        &mutually_exclusive,
        false,
        on_created,
        |con, index_name, field: &SchemaGeoField| {
            con.ft_create(
                index_name,
                &CreateOptions::new(),
                &SearchSchema::new(GEO_FIELD_NAME, field.clone()),
            )
        },
    );

    assert_no_index_and_index_missing_conflict(
        con,
        GEO_FIELD_NAME,
        SchemaGeoField::new().no_index(true).index_missing(true),
    );
}

#[test]
fn test_module_search_ft_create_schema_geo_field() {
    // Redis-only: valkey-search has no GEO field type.
    let ctx = run_test_if_version_supported!(REDIS_SEARCH_8_0, &[Module::Search]);
    run_ft_create_schema_geo_field(&mut ctx.connection(), |_| {});
}

type VectorFieldModifier = fn(VectorField) -> VectorField;

fn run_ft_create_schema_flat_vector_field<C, F>(con: &mut C, is_valkey: bool, mut on_created: F)
where
    C: redis::ConnectionLike,
    F: FnMut(&str),
{
    const DIM: u32 = 128;

    type FlatVectorFieldBuilderModifier = fn(FlatVectorFieldBuilder) -> FlatVectorFieldBuilder;
    // FLAT-specific builder modifiers (applied before .build())
    let builder_modifiers: Vec<(&'static str, FlatVectorFieldBuilderModifier)> =
        vec![("block_size", |builder| builder.block_size(1000))];

    // INDEXMISSING is Redis-only. Alias works on both servers.
    let mut field_modifiers: Vec<(&'static str, VectorFieldModifier)> =
        vec![("alias", |field| field.alias("vector_alias"))];
    if !is_valkey {
        field_modifiers.push(("index_missing", |field| field.index_missing(true)));
    }

    // Valkey Search supports FLOAT32 only.
    let mut vector_types = vec![("float32", VectorType::Float32)];
    if !is_valkey {
        vector_types.extend([
            ("float64", VectorType::Float64),
            ("bfloat16", VectorType::BFloat16),
            ("float16", VectorType::Float16),
            ("int8", VectorType::Int8),
            ("uint8", VectorType::UInt8),
        ]);
    }
    for (vector_type_name, vector_type) in vector_types {
        // For each distance metric
        for (distance_metric_name, distance_metric) in [
            ("l2", DistanceMetric::L2),
            ("ip", DistanceMetric::IP),
            ("cosine", DistanceMetric::Cosine),
        ] {
            let base_name = format!("idx_flat_{vector_type_name}_{distance_metric_name}");

            // 1. Test each builder modifier individually
            for (builder_suffix, builder_modifier) in &builder_modifiers {
                let index_name = format!("{base_name}_builder_{builder_suffix}");
                let schema = schema! {
                    VECTOR_FIELD_NAME => builder_modifier(VectorField::flat(vector_type, DIM, distance_metric)).build()
                };
                assert_eq!(
                    con.ft_create(&index_name, &CreateOptions::new(), &schema),
                    Ok("OK".to_string())
                );
                on_created(&index_name);
            }

            // 2. Test each common field modifier individually
            for (field_suffix, field_modifier) in &field_modifiers {
                let index_name = format!("{base_name}_field_{field_suffix}");
                let schema = schema! {
                    VECTOR_FIELD_NAME => field_modifier(VectorField::flat(vector_type, DIM, distance_metric).build())
                };
                assert_eq!(
                    con.ft_create(&index_name, &CreateOptions::new(), &schema),
                    Ok("OK".to_string())
                );
                on_created(&index_name);
            }

            // 3. Test all builder modifiers combined progressively
            let mut combined_builder = VectorField::flat(vector_type, DIM, distance_metric);
            for (builder_suffix, builder_modifier) in &builder_modifiers {
                combined_builder = builder_modifier(combined_builder);
                let index_name = format!("{base_name}_builders_until_{builder_suffix}");
                let schema = schema! {
                    VECTOR_FIELD_NAME => combined_builder.clone().build()
                };
                assert_eq!(
                    con.ft_create(&index_name, &CreateOptions::new(), &schema),
                    Ok("OK".to_string())
                );
                on_created(&index_name);
            }

            // 4. Test all builder modifiers + each field modifier
            for (field_suffix, field_modifier) in &field_modifiers {
                let index_name = format!("{base_name}_all_builders_with_{field_suffix}");
                let schema = schema! {
                    VECTOR_FIELD_NAME => field_modifier(combined_builder.clone().build())
                };
                assert_eq!(
                    con.ft_create(&index_name, &CreateOptions::new(), &schema),
                    Ok("OK".to_string())
                );
                on_created(&index_name);
            }

            // 5. Test all builder modifiers + all field modifiers combined progressively
            let mut combined_field = combined_builder.build();
            for (field_suffix, field_modifier) in &field_modifiers {
                combined_field = field_modifier(combined_field);
                let index_name = format!("{base_name}_all_builders_fields_until_{field_suffix}");
                let schema = schema! {
                    VECTOR_FIELD_NAME => combined_field.clone()
                };
                assert_eq!(
                    con.ft_create(&index_name, &CreateOptions::new(), &schema),
                    Ok("OK".to_string())
                );
                on_created(&index_name);
            }
        }
    }
}

#[test]
fn test_module_search_ft_create_schema_flat_vector_field() {
    let ctx = run_test_if_version_supported!(
        &[REDIS_SEARCH_8_0, VALKEY_SEARCH_ANY][..],
        &[Module::Search]
    );
    let is_valkey = ctx.supports(VALKEY_SEARCH_ANY);
    run_ft_create_schema_flat_vector_field(&mut ctx.connection(), is_valkey, |_| {});
}

fn run_ft_create_schema_hnsw_vector_field<C, F>(con: &mut C, is_valkey: bool, mut on_created: F)
where
    C: redis::ConnectionLike,
    F: FnMut(&str),
{
    const DIM: u32 = 128;

    type HnswVectorFieldBuilderModifier = fn(HnswVectorFieldBuilder) -> HnswVectorFieldBuilder;
    // HNSW-specific builder modifiers (applied before .build())
    // EPSILON is Redis-only. The other options work on both servers.
    let mut builder_modifiers: Vec<(&'static str, HnswVectorFieldBuilderModifier)> = vec![
        ("m", |builder| builder.m(16)),
        ("ef_construction", |builder| builder.ef_construction(200)),
        ("ef_runtime", |builder| builder.ef_runtime(20)),
    ];
    if !is_valkey {
        builder_modifiers.push(("epsilon", |builder| builder.epsilon(0.01)));
    }

    // INDEXMISSING is Redis-only. Alias works on both servers.
    let mut field_modifiers: Vec<(&'static str, VectorFieldModifier)> =
        vec![("alias", |field| field.alias("vector_alias"))];
    if !is_valkey {
        field_modifiers.push(("index_missing", |field| field.index_missing(true)));
    }

    // Valkey Search supports FLOAT32 only.
    let mut vector_types = vec![("float32", VectorType::Float32)];
    if !is_valkey {
        vector_types.extend([
            ("float64", VectorType::Float64),
            ("bfloat16", VectorType::BFloat16),
            ("float16", VectorType::Float16),
            ("int8", VectorType::Int8),
            ("uint8", VectorType::UInt8),
        ]);
    }
    for (vector_type_name, vector_type) in vector_types {
        // For each distance metric
        for (distance_metric_name, distance_metric) in [
            ("l2", DistanceMetric::L2),
            ("ip", DistanceMetric::IP),
            ("cosine", DistanceMetric::Cosine),
        ] {
            let base_name = format!("idx_hnsw_{vector_type_name}_{distance_metric_name}");

            // 1. Test each builder modifier individually
            for (builder_suffix, builder_modifier) in &builder_modifiers {
                let index_name = format!("{base_name}_builder_{builder_suffix}");
                let schema = schema! {
                    VECTOR_FIELD_NAME => builder_modifier(VectorField::hnsw(vector_type, DIM, distance_metric)).build()
                };
                assert_eq!(
                    con.ft_create(&index_name, &CreateOptions::new(), &schema),
                    Ok("OK".to_string())
                );
                on_created(&index_name);
            }

            // 2. Test each common field modifier individually
            for (field_suffix, field_modifier) in &field_modifiers {
                let index_name = format!("{base_name}_field_{field_suffix}");
                let schema = schema! {
                    VECTOR_FIELD_NAME => field_modifier(VectorField::hnsw(vector_type, DIM, distance_metric).build())
                };
                assert_eq!(
                    con.ft_create(&index_name, &CreateOptions::new(), &schema),
                    Ok("OK".to_string())
                );
                on_created(&index_name);
            }

            // 3. Test all builder modifiers combined progressively
            let mut combined_builder = VectorField::hnsw(vector_type, DIM, distance_metric);
            for (builder_suffix, builder_modifier) in &builder_modifiers {
                combined_builder = builder_modifier(combined_builder);
                let index_name = format!("{base_name}_builders_until_{builder_suffix}");
                let schema = schema! {
                    VECTOR_FIELD_NAME => combined_builder.clone().build()
                };
                assert_eq!(
                    con.ft_create(&index_name, &CreateOptions::new(), &schema),
                    Ok("OK".to_string())
                );
                on_created(&index_name);
            }

            // 4. Test all builder modifiers + each field modifier
            for (field_suffix, field_modifier) in &field_modifiers {
                let index_name = format!("{base_name}_all_builders_with_{field_suffix}");
                let schema = schema! {
                    VECTOR_FIELD_NAME => field_modifier(combined_builder.clone().build())
                };
                assert_eq!(
                    con.ft_create(&index_name, &CreateOptions::new(), &schema),
                    Ok("OK".to_string())
                );
                on_created(&index_name);
            }

            // 5. Test all builder modifiers + all field modifiers combined progressively
            let mut combined_field = combined_builder.build();
            for (field_suffix, field_modifier) in &field_modifiers {
                combined_field = field_modifier(combined_field);
                let index_name = format!("{base_name}_all_builders_fields_until_{field_suffix}");
                let schema = schema! {
                    VECTOR_FIELD_NAME => combined_field.clone()
                };
                assert_eq!(
                    con.ft_create(&index_name, &CreateOptions::new(), &schema),
                    Ok("OK".to_string())
                );
                on_created(&index_name);
            }
        }
    }
}

#[test]
fn test_module_search_ft_create_schema_hnsw_vector_field() {
    let ctx = run_test_if_version_supported!(
        &[REDIS_SEARCH_8_0, VALKEY_SEARCH_ANY][..],
        &[Module::Search]
    );
    let is_valkey = ctx.supports(VALKEY_SEARCH_ANY);
    run_ft_create_schema_hnsw_vector_field(&mut ctx.connection(), is_valkey, |_| {});
}

fn run_ft_create_schema_vamana_vector_field<C, F>(con: &mut C, mut on_created: F)
where
    C: redis::ConnectionLike,
    F: FnMut(&str),
{
    const DIM: u32 = 128;

    // Common field modifiers (applied after .build()) - not mutually exclusive
    let field_modifiers: Vec<(&'static str, VectorFieldModifier)> = vec![
        ("alias", |field| field.alias("vector_alias")),
        ("index_missing", |field| field.index_missing(true)),
    ];

    // All compression types
    let compression_types: Vec<(&'static str, CompressionType)> = vec![
        ("lvq4", CompressionType::LVQ4),
        ("lvq8", CompressionType::LVQ8),
        ("lvq4x4", CompressionType::LVQ4x4),
        ("lvq4x8", CompressionType::LVQ4x8),
        ("leanvec4x8", CompressionType::LeanVec4x8),
        ("leanvec8x8", CompressionType::LeanVec8x8),
    ];

    // Note: VAMANA only supports float types (Float16, Float32)
    // Uses VamanaVectorType for compile-time type safety
    for (vector_type_name, vector_type) in [
        ("float16", VamanaVectorType::Float16),
        ("float32", VamanaVectorType::Float32),
    ] {
        // For each distance metric
        for (distance_metric_name, distance_metric) in [
            ("l2", DistanceMetric::L2),
            ("ip", DistanceMetric::IP),
            ("cosine", DistanceMetric::Cosine),
        ] {
            // For each compression type
            for (compression_name, compression_type) in &compression_types {
                let base_name = format!(
                    "idx_vamana_{vector_type_name}_{distance_metric_name}_{compression_name}"
                );

                // Build the list of builder modifiers based on compression type.
                // training_threshold needs a compression type and reduce needs LeanVec4x8 or
                // LeanVec8x8, so their modifiers set compression too.
                let is_leanvec = matches!(
                    compression_type,
                    CompressionType::LeanVec4x8 | CompressionType::LeanVec8x8
                );

                type VamanaVectorFieldBuilderModifier =
                    Box<dyn Fn(VamanaVectorFieldBuilder) -> VamanaVectorFieldBuilder>;
                let builder_modifiers: Vec<(&'static str, VamanaVectorFieldBuilderModifier)> = {
                    let compression = *compression_type;
                    let mut modifiers: Vec<(&'static str, VamanaVectorFieldBuilderModifier)> = vec![
                        (
                            "compression",
                            Box::new(move |builder| builder.compression(compression)),
                        ),
                        (
                            "construction_window_size",
                            Box::new(|builder| builder.construction_window_size(300)),
                        ),
                        (
                            "graph_max_degree",
                            Box::new(|builder| builder.graph_max_degree(128)),
                        ),
                        (
                            "search_window_size",
                            Box::new(|builder| builder.search_window_size(20)),
                        ),
                        ("epsilon", Box::new(|builder| builder.epsilon(0.02))),
                        (
                            "training_threshold",
                            Box::new(move |builder| {
                                builder.compression(compression).training_threshold(2048)
                            }),
                        ),
                    ];

                    if is_leanvec {
                        modifiers.push((
                            "reduce",
                            Box::new(move |builder| builder.compression(compression).reduce(64)),
                        ));
                    }

                    modifiers
                };

                // 1. Test each builder modifier individually
                for (builder_suffix, builder_modifier) in &builder_modifiers {
                    let index_name = format!("{base_name}_builder_{builder_suffix}");
                    let schema = schema! {
                        VECTOR_FIELD_NAME => builder_modifier(VectorField::vamana(vector_type, DIM, distance_metric)).build()
                    };
                    assert_eq!(
                        con.ft_create(&index_name, &CreateOptions::new(), &schema),
                        Ok("OK".to_string())
                    );
                    on_created(&index_name);
                }

                // 2. Test each common field modifier individually
                for (field_suffix, field_modifier) in &field_modifiers {
                    let index_name = format!("{base_name}_field_{field_suffix}");
                    let schema = schema! {
                        VECTOR_FIELD_NAME => field_modifier(VectorField::vamana(vector_type, DIM, distance_metric).build())
                    };
                    assert_eq!(
                        con.ft_create(&index_name, &CreateOptions::new(), &schema),
                        Ok("OK".to_string())
                    );
                    on_created(&index_name);
                }

                // 3. Test all builder modifiers combined progressively
                let mut combined_builder = VectorField::vamana(vector_type, DIM, distance_metric);
                for (builder_suffix, builder_modifier) in &builder_modifiers {
                    combined_builder = builder_modifier(combined_builder);
                    let index_name = format!("{base_name}_builders_until_{builder_suffix}");
                    let schema = schema! {
                        VECTOR_FIELD_NAME => combined_builder.clone().build()
                    };
                    assert_eq!(
                        con.ft_create(&index_name, &CreateOptions::new(), &schema),
                        Ok("OK".to_string())
                    );
                    on_created(&index_name);
                }

                // 4. Test all builder modifiers + each field modifier
                for (field_suffix, field_modifier) in &field_modifiers {
                    let index_name = format!("{base_name}_all_builders_with_{field_suffix}");
                    let schema = schema! {
                        VECTOR_FIELD_NAME => field_modifier(combined_builder.clone().build())
                    };
                    assert_eq!(
                        con.ft_create(&index_name, &CreateOptions::new(), &schema),
                        Ok("OK".to_string())
                    );
                    on_created(&index_name);
                }

                // 5. Test all builder modifiers + all field modifiers combined progressively
                let mut combined_field = combined_builder.build();
                for (field_suffix, field_modifier) in &field_modifiers {
                    combined_field = field_modifier(combined_field);
                    let index_name =
                        format!("{base_name}_all_builders_fields_until_{field_suffix}");
                    let schema = schema! {
                        VECTOR_FIELD_NAME => combined_field.clone()
                    };
                    assert_eq!(
                        con.ft_create(&index_name, &CreateOptions::new(), &schema),
                        Ok("OK".to_string())
                    );
                    on_created(&index_name);
                }
            }
        }
    }

    // The builder sends the conditional parameters as given, so the server rejects them
    // when their compression type is missing.
    for (name, builder) in [
        (
            "training_threshold_without_compression",
            VectorField::vamana(VamanaVectorType::Float32, DIM, DistanceMetric::L2)
                .training_threshold(2048),
        ),
        (
            "reduce_without_leanvec",
            VectorField::vamana(VamanaVectorType::Float32, DIM, DistanceMetric::L2)
                .compression(CompressionType::LVQ8)
                .reduce(64),
        ),
    ] {
        let result = con.ft_create::<_, String>(
            format!("idx_vamana_invalid_{name}"),
            &CreateOptions::new(),
            &schema! { VECTOR_FIELD_NAME => builder.build() },
        );
        let server_error = redis::ServerError::try_from(result.unwrap_err()).unwrap();
        assert!(
            server_error
                .details()
                .is_some_and(|details| details.contains("irrelevant")),
            "{name}: {server_error:?}"
        );
    }
}

#[test]
fn test_module_search_ft_create_schema_vamana_vector_field() {
    // Redis-only: valkey-search has no SVS-VAMANA algorithm. The algorithm was introduced in Redis 8.2.
    let ctx = run_test_if_version_supported!(REDIS_SEARCH_8_2, &[Module::Search]);
    run_ft_create_schema_vamana_vector_field(&mut ctx.connection(), |_| {});
}

fn run_ft_create_schema_geoshape_field<C, F>(con: &mut C, mut on_created: F)
where
    C: redis::ConnectionLike,
    F: FnMut(&str),
{
    // GEOSHAPE is Redis-only, so every modifier runs on Redis (`is_valkey` is always false here).
    let field_modifiers: Vec<(&'static str, Modifier<SchemaGeoShapeField>)> =
        vec![("alias", |field| field.alias("geo_shape_alias"))];

    // Modifiers that are mutually exclusive.
    let mutually_exclusive: Vec<(&'static str, Modifier<SchemaGeoShapeField>)> = vec![
        ("index_missing", |field| field.index_missing(true)),
        ("no_index", |field| field.no_index(true)),
    ];

    // Every index needs a coordinate system, so run the whole matrix once per system.
    for coord_system in &[CoordSystem::Spherical, CoordSystem::Flat] {
        let index_prefix = format!("geoshape_{coord_system:?}_field");
        run_modifier_matrix(
            con,
            &index_prefix,
            || SchemaGeoShapeField::new().coord_system(coord_system.clone()),
            &field_modifiers,
            &[],
            &mutually_exclusive,
            false,
            &mut on_created,
            |con, index_name, field: &SchemaGeoShapeField| {
                con.ft_create(
                    index_name,
                    &CreateOptions::new(),
                    &SearchSchema::new(GEOSHAPE_FIELD_NAME, field.clone()),
                )
            },
        );

        assert_no_index_and_index_missing_conflict(
            con,
            GEOSHAPE_FIELD_NAME,
            SchemaGeoShapeField::new()
                .coord_system(coord_system.clone())
                .no_index(true)
                .index_missing(true),
        );
    }
}

#[test]
fn test_module_search_ft_create_schema_geoshape_field() {
    // Redis-only: valkey-search has no GEOSHAPE field type.
    let ctx = run_test_if_version_supported!(REDIS_SEARCH_8_0, &[Module::Search]);
    run_ft_create_schema_geoshape_field(&mut ctx.connection(), |_| {});
}

// Redis only: `PrimaryConnections` relies on RediSearch's internal `_FT.DEBUG` command.
#[cfg(feature = "cluster")]
mod cluster {
    use super::*;

    #[test]
    fn test_module_search_simple_ft_create() {
        let ctx = setup_cluster_with_search_module();
        skip_if_context_does_not_support!(ctx, REDIS_SEARCH_8_0);
        let mut primaries = PrimaryConnections::from_cluster(&ctx);
        run_simple_ft_create(&mut ctx.connection(), "index", |name| {
            primaries.assert_index_propagated(name);
        });
    }

    #[test]
    fn test_module_search_ft_create_schema_text_field() {
        let ctx = setup_cluster_with_search_module();
        skip_if_context_does_not_support!(ctx, REDIS_SEARCH_8_0);
        let mut primaries = PrimaryConnections::from_cluster(&ctx);
        run_ft_create_schema_text_field(&mut ctx.connection(), false, |name| {
            primaries.assert_index_propagated(name);
        });
    }

    #[test]
    fn test_module_search_ft_create_schema_tag_field() {
        let ctx = setup_cluster_with_search_module();
        skip_if_context_does_not_support!(ctx, REDIS_SEARCH_8_0);
        let mut primaries = PrimaryConnections::from_cluster(&ctx);
        run_ft_create_schema_tag_field(&mut ctx.connection(), false, |name| {
            primaries.assert_index_propagated(name);
        });
    }

    #[test]
    fn test_module_search_ft_create_schema_numeric_field() {
        let ctx = setup_cluster_with_search_module();
        skip_if_context_does_not_support!(ctx, REDIS_SEARCH_8_0);
        let mut primaries = PrimaryConnections::from_cluster(&ctx);
        run_ft_create_schema_numeric_field(&mut ctx.connection(), false, |name| {
            primaries.assert_index_propagated(name);
        });
    }

    #[test]
    fn test_module_search_ft_create_schema_geo_field() {
        let ctx = setup_cluster_with_search_module();
        skip_if_context_does_not_support!(ctx, REDIS_SEARCH_8_0);
        let mut primaries = PrimaryConnections::from_cluster(&ctx);
        run_ft_create_schema_geo_field(&mut ctx.connection(), |name| {
            primaries.assert_index_propagated(name);
        });
    }

    #[test]
    fn test_module_search_ft_create_schema_geoshape_field() {
        let ctx = setup_cluster_with_search_module();
        skip_if_context_does_not_support!(ctx, REDIS_SEARCH_8_0);
        let mut primaries = PrimaryConnections::from_cluster(&ctx);
        run_ft_create_schema_geoshape_field(&mut ctx.connection(), |name| {
            primaries.assert_index_propagated(name);
        });
    }

    #[test]
    fn test_module_search_ft_create_schema_flat_vector_field() {
        let ctx = setup_cluster_with_search_module();
        skip_if_context_does_not_support!(ctx, REDIS_SEARCH_8_0);
        let mut primaries = PrimaryConnections::from_cluster(&ctx);
        run_ft_create_schema_flat_vector_field(&mut ctx.connection(), false, |name| {
            primaries.assert_index_propagated(name);
        });
    }

    #[test]
    fn test_module_search_ft_create_schema_hnsw_vector_field() {
        let ctx = setup_cluster_with_search_module();
        skip_if_context_does_not_support!(ctx, REDIS_SEARCH_8_0);
        let mut primaries = PrimaryConnections::from_cluster(&ctx);
        run_ft_create_schema_hnsw_vector_field(&mut ctx.connection(), false, |name| {
            primaries.assert_index_propagated(name);
        });
    }

    #[test]
    fn test_module_search_ft_create_schema_vamana_vector_field() {
        // The VAMANA index was introduced in Redis 8.2.
        let ctx = setup_cluster_with_search_module();
        skip_if_context_does_not_support!(ctx, REDIS_SEARCH_8_2);
        let mut primaries = PrimaryConnections::from_cluster(&ctx);
        run_ft_create_schema_vamana_vector_field(&mut ctx.connection(), |name| {
            primaries.assert_index_propagated(name);
        });
    }
}