-
Notifications
You must be signed in to change notification settings - Fork 950
/
search_family_test.cc
1215 lines (946 loc) · 48.2 KB
/
search_family_test.cc
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 2023, DragonflyDB authors. All rights reserved.
// See LICENSE for licensing terms.
//
#include "server/search/search_family.h"
#include "base/gtest.h"
#include "base/logging.h"
#include "facade/facade_test.h"
#include "server/command_registry.h"
#include "server/test_utils.h"
using namespace testing;
using namespace std;
using namespace util;
namespace dfly {
class SearchFamilyTest : public BaseFamilyTest {
protected:
};
const auto kNoResults = IntArg(0); // tests auto destruct single element arrays
/* Asserts that response is array of two arrays. Used to test FT.PROFILE response */
::testing::AssertionResult AssertArrayOfTwoArrays(const RespExpr& resp) {
if (resp.GetVec().size() != 2) {
return ::testing::AssertionFailure()
<< "Expected response array length to be 2, but was " << resp.GetVec().size();
}
const auto& vec = resp.GetVec();
if (vec[0].type != RespExpr::ARRAY) {
return ::testing::AssertionFailure()
<< "Expected resp[0] to be an array, but was " << vec[0].type;
}
if (vec[1].type != RespExpr::ARRAY) {
return ::testing::AssertionFailure()
<< "Expected resp[1] to be an array, but was " << vec[1].type;
}
return ::testing::AssertionSuccess();
}
#define ASSERT_ARRAY_OF_TWO_ARRAYS(resp) ASSERT_PRED1(AssertArrayOfTwoArrays, resp)
MATCHER_P2(DocIds, total, arg_ids, "") {
if (arg_ids.empty()) {
if (auto res = arg.GetInt(); !res || *res != 0) {
*result_listener << "Expected single zero";
return false;
}
return true;
}
if (arg.type != RespExpr::ARRAY) {
*result_listener << "Wrong response type: " << int(arg.type);
return false;
}
auto results = arg.GetVec();
if (results.size() != arg_ids.size() * 2 + 1) {
*result_listener << "Wrong resp vec size: " << results.size();
return false;
}
if (auto num_results = results[0].GetInt(); !num_results || size_t(*num_results) != total) {
*result_listener << "Bad total count in reply: " << num_results.value_or(-1);
return false;
}
vector<string> received_ids;
for (size_t i = 1; i < results.size(); i += 2)
received_ids.push_back(results[i].GetString());
vector<string> expected_ids = arg_ids;
sort(received_ids.begin(), received_ids.end());
sort(expected_ids.begin(), expected_ids.end());
return expected_ids == received_ids;
}
template <typename... Args> auto AreDocIds(Args... args) {
return DocIds(sizeof...(args), vector<string>{args...});
}
template <typename... Args> auto IsArray(Args... args) {
return RespArray(ElementsAre(std::forward<Args>(args)...));
}
template <typename... Args> auto IsUnordArray(Args... args) {
return RespArray(UnorderedElementsAre(std::forward<Args>(args)...));
}
MATCHER_P(IsMapMatcher, expected, "") {
if (arg.type != RespExpr::ARRAY) {
*result_listener << "Wrong response type: " << arg.type;
return false;
}
auto result = arg.GetVec();
if (result.size() != expected.size()) {
*result_listener << "Wrong resp array size: " << result.size();
return false;
}
using KeyValueArray = std::vector<std::pair<std::string, std::string>>;
KeyValueArray received_pairs;
for (size_t i = 0; i < result.size(); i += 2) {
received_pairs.emplace_back(result[i].GetString(), result[i + 1].GetString());
}
KeyValueArray expected_pairs;
for (size_t i = 0; i < expected.size(); i += 2) {
expected_pairs.emplace_back(expected[i], expected[i + 1]);
}
// Custom unordered comparison
std::sort(received_pairs.begin(), received_pairs.end());
std::sort(expected_pairs.begin(), expected_pairs.end());
return received_pairs == expected_pairs;
}
template <typename... Matchers> auto IsMap(Matchers... matchers) {
return IsMapMatcher(std::vector<std::string>{std::forward<Matchers>(matchers)...});
}
MATCHER_P(IsUnordArrayWithSizeMatcher, expected, "") {
if (arg.type != RespExpr::ARRAY) {
*result_listener << "Wrong response type: " << arg.type;
return false;
}
auto result = arg.GetVec();
size_t expected_size = std::tuple_size<decltype(expected)>::value;
if (result.size() != expected_size + 1) {
*result_listener << "Wrong resp array size: " << result.size();
return false;
}
if (result[0].GetInt() != expected_size) {
*result_listener << "Wrong elements count: " << result[0].GetInt().value_or(-1);
return false;
}
std::vector<RespExpr> received_elements(result.begin() + 1, result.end());
// Create a vector of matchers from the tuple
std::vector<Matcher<RespExpr>> matchers;
std::apply([&matchers](auto&&... args) { ((matchers.push_back(args)), ...); }, expected);
return ExplainMatchResult(UnorderedElementsAreArray(matchers), received_elements,
result_listener);
}
template <typename... Matchers> auto IsUnordArrayWithSize(Matchers... matchers) {
return IsUnordArrayWithSizeMatcher(std::make_tuple(matchers...));
}
template <typename Expected, size_t... Is>
void BuildKvMatchers(std::vector<Matcher<std::pair<std::string, RespExpr>>>& kv_matchers,
const Expected& expected, std::index_sequence<Is...>) {
std::initializer_list<int>{
(kv_matchers.emplace_back(Pair(std::get<Is * 2>(expected), std::get<Is * 2 + 1>(expected))),
0)...};
}
MATCHER_P(IsMapWithSizeMatcher, expected, "") {
if (arg.type != RespExpr::ARRAY) {
*result_listener << "Wrong response type: " << arg.type;
return false;
}
constexpr size_t expected_size = std::tuple_size<decltype(expected)>::value;
constexpr size_t exprected_pairs_number = expected_size / 2;
auto result = arg.GetVec();
if (result.size() != expected_size + 1 || result.size() % 2 != 1) {
*result_listener << "Wrong resp array size: " << result.size();
return false;
}
if (result[0].GetInt() != exprected_pairs_number) {
*result_listener << "Wrong pairs count: " << result[0].GetInt().value_or(-1);
return false;
}
std::vector<std::pair<std::string, RespExpr>> received_pairs;
for (size_t i = 1; i < result.size(); i += 2) {
received_pairs.emplace_back(result[i].GetString(), result[i + 1]);
}
std::vector<Matcher<std::pair<std::string, RespExpr>>> kv_matchers;
BuildKvMatchers(kv_matchers, expected, std::make_index_sequence<exprected_pairs_number>{});
return ExplainMatchResult(UnorderedElementsAreArray(kv_matchers), received_pairs,
result_listener);
}
template <typename... Args> auto IsMapWithSize(Args... args) {
return IsMapWithSizeMatcher(std::make_tuple(args...));
}
TEST_F(SearchFamilyTest, CreateDropListIndex) {
EXPECT_EQ(Run({"ft.create", "idx-1", "ON", "HASH", "PREFIX", "1", "prefix-1"}), "OK");
EXPECT_EQ(Run({"ft.create", "idx-2", "ON", "JSON", "PREFIX", "1", "prefix-2"}), "OK");
EXPECT_EQ(Run({"ft.create", "idx-3", "ON", "JSON", "PREFIX", "1", "prefix-3"}), "OK");
EXPECT_THAT(Run({"ft._list"}).GetVec(), testing::UnorderedElementsAre("idx-1", "idx-2", "idx-3"));
EXPECT_EQ(Run({"ft.dropindex", "idx-2"}), "OK");
EXPECT_THAT(Run({"ft._list"}).GetVec(), testing::UnorderedElementsAre("idx-1", "idx-3"));
EXPECT_THAT(Run({"ft.create", "idx-1"}), ErrArg("Index already exists"));
EXPECT_THAT(Run({"ft.dropindex", "idx-100"}), ErrArg("Unknown Index name"));
EXPECT_EQ(Run({"ft.dropindex", "idx-1"}), "OK");
EXPECT_EQ(Run({"ft._list"}), "idx-3");
}
TEST_F(SearchFamilyTest, CreateDropDifferentDatabases) {
// Create index on db 0
auto resp =
Run({"ft.create", "idx-1", "ON", "HASH", "PREFIX", "1", "doc-", "SCHEMA", "name", "TEXT"});
EXPECT_EQ(resp, "OK");
EXPECT_EQ(Run({"select", "1"}), "OK"); // change database
// Creating an index on non zero database must fail
resp = Run({"ft.create", "idx-2", "ON", "JSON", "PREFIX", "1", "prefix-2"});
EXPECT_THAT(resp, ErrArg("ERR Cannot create index on db != 0"));
// Add some data to the index
Run({"hset", "doc-0", "name", "Name of 0"});
// ft.search must work on the another database
resp = Run({"ft.search", "idx-1", "*"});
EXPECT_THAT(resp, IsMapWithSize("doc-0", IsMap("name", "Name of 0")));
// ft.dropindex must work on the another database
EXPECT_EQ(Run({"ft.dropindex", "idx-1"}), "OK");
EXPECT_THAT(Run({"ft.info", "idx-1"}), ErrArg("ERR Unknown Index name"));
EXPECT_EQ(Run({"select", "0"}), "OK");
EXPECT_THAT(Run({"ft.info", "idx-1"}), ErrArg("ERR Unknown Index name"));
}
TEST_F(SearchFamilyTest, AlterIndex) {
Run({"hset", "d:1", "color", "blue", "cost", "150"});
Run({"hset", "d:2", "color", "green", "cost", "200"});
Run({"ft.create", "idx-1", "ON", "HASH"});
EXPECT_EQ(Run({"ft.alter", "idx-1", "schema", "add", "color", "tag"}), "OK");
EXPECT_THAT(Run({"ft.search", "idx-1", "@color:{blue}"}), AreDocIds("d:1"));
EXPECT_THAT(Run({"ft.search", "idx-1", "@color:{green}"}), AreDocIds("d:2"));
EXPECT_EQ(Run({"ft.alter", "idx-1", "schema", "add", "cost", "numeric"}), "OK");
EXPECT_THAT(Run({"ft.search", "idx-1", "@cost:[0 100]"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "idx-1", "@cost:[100 300]"}), AreDocIds("d:1", "d:2"));
EXPECT_THAT(Run({"ft.alter", "idx-2", "schema", "add", "price", "numeric"}),
ErrArg("Index not found"));
}
TEST_F(SearchFamilyTest, InfoIndex) {
EXPECT_EQ(
Run({"ft.create", "idx-1", "ON", "HASH", "PREFIX", "1", "doc-", "SCHEMA", "name", "TEXT"}),
"OK");
for (size_t i = 0; i < 15; i++) {
Run({"hset", absl::StrCat("doc-", i), "name", absl::StrCat("Name of", i)});
}
auto info = Run({"ft.info", "idx-1"});
EXPECT_THAT(info,
IsArray(_, _, _, IsArray("key_type", "HASH", "prefix", "doc-"), "attributes",
IsArray(IsArray("identifier", "name", "attribute", "name", "type", "TEXT")),
"num_docs", IntArg(15)));
}
TEST_F(SearchFamilyTest, Stats) {
EXPECT_EQ(
Run({"ft.create", "idx-1", "ON", "HASH", "PREFIX", "1", "doc1-", "SCHEMA", "name", "TEXT"}),
"OK");
EXPECT_EQ(
Run({"ft.create", "idx-2", "ON", "HASH", "PREFIX", "1", "doc2-", "SCHEMA", "name", "TEXT"}),
"OK");
for (size_t i = 0; i < 50; i++) {
Run({"hset", absl::StrCat("doc1-", i), "name", absl::StrCat("Name of", i)});
Run({"hset", absl::StrCat("doc2-", i), "name", absl::StrCat("Name of", i)});
}
auto metrics = GetMetrics();
EXPECT_EQ(metrics.search_stats.num_indices, 2);
EXPECT_EQ(metrics.search_stats.num_entries, 50 * 2);
size_t expected_usage = 2 * (50 + 3 /* number of distinct words*/) * (24 + 48 /* kv size */) +
50 * 2 * 1 /* posting list entries */;
EXPECT_GE(metrics.search_stats.used_memory, expected_usage);
EXPECT_LE(metrics.search_stats.used_memory, 3 * expected_usage);
}
// todo: ASAN fails heres on arm
#ifndef SANITIZERS
TEST_F(SearchFamilyTest, Simple) {
Run({"hset", "d:1", "foo", "baz", "k", "v"});
Run({"hset", "d:2", "foo", "bar", "k", "v"});
Run({"hset", "d:3", "foo", "bad", "k", "v"});
EXPECT_EQ(Run({"ft.create", "i1", "PREFIX", "1", "d:", "SCHEMA", "foo", "TEXT", "k", "TEXT"}),
"OK");
EXPECT_THAT(Run({"ft.search", "i1", "@foo:bar"}), AreDocIds("d:2"));
EXPECT_THAT(Run({"ft.search", "i1", "@foo:bar | @foo:baz"}), AreDocIds("d:1", "d:2"));
EXPECT_THAT(Run({"ft.search", "i1", "@foo:(bar|baz|bad)"}), AreDocIds("d:1", "d:2", "d:3"));
EXPECT_THAT(Run({"ft.search", "i1", "@foo:none"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "iNone", "@foo:bar"}), ErrArg("iNone: no such index"));
EXPECT_THAT(Run({"ft.search", "i1", "@@NOTAQUERY@@"}), ErrArg("Query syntax error"));
// w: prefix is not part of index
Run({"hset", "w:2", "foo", "this", "k", "v"});
EXPECT_THAT(Run({"ft.search", "i1", "@foo:this"}), kNoResults);
}
#endif
TEST_F(SearchFamilyTest, Errors) {
Run({"ft.create", "i1", "PREFIX", "1", "d:", "SCHEMA", "foo", "TAG", "bar", "TEXT"});
// Wrong field
EXPECT_THAT(Run({"ft.search", "i1", "@whoami:lol"}), ErrArg("Invalid field: whoami"));
// Wrong field type
EXPECT_THAT(Run({"ft.search", "i1", "@foo:lol"}), ErrArg("Wrong access type for field: foo"));
}
TEST_F(SearchFamilyTest, NoPrefix) {
Run({"hset", "d:1", "a", "one", "k", "v"});
Run({"hset", "d:2", "a", "two", "k", "v"});
Run({"hset", "d:3", "a", "three", "k", "v"});
EXPECT_EQ(Run({"ft.create", "i1", "schema", "a", "text", "k", "text"}), "OK");
EXPECT_THAT(Run({"ft.search", "i1", "one | three"}), AreDocIds("d:1", "d:3"));
}
TEST_F(SearchFamilyTest, Json) {
Run({"json.set", "k1", ".", R"({"a": "small test", "b": "some details"})"});
Run({"json.set", "k2", ".", R"({"a": "another test", "b": "more details"})"});
Run({"json.set", "k3", ".", R"({"a": "last test", "b": "secret details"})"});
EXPECT_EQ(Run({"ft.create", "i1", "on", "json", "schema", "$.a", "as", "a", "text", "$.b", "as",
"b", "text"}),
"OK");
EXPECT_THAT(Run({"ft.search", "i1", "some|more"}), AreDocIds("k1", "k2"));
EXPECT_THAT(Run({"ft.search", "i1", "some|more|secret"}), AreDocIds("k1", "k2", "k3"));
EXPECT_THAT(Run({"ft.search", "i1", "@a:last @b:details"}), AreDocIds("k3"));
EXPECT_THAT(Run({"ft.search", "i1", "@a:(another|small)"}), AreDocIds("k1", "k2"));
EXPECT_THAT(Run({"ft.search", "i1", "@a:(another|small|secret)"}), AreDocIds("k1", "k2"));
EXPECT_THAT(Run({"ft.search", "i1", "none"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "i1", "@a:small @b:secret"}), kNoResults);
}
TEST_F(SearchFamilyTest, JsonAttributesPaths) {
Run({"json.set", "k1", ".", R"( {"nested": {"value": "no"}} )"});
Run({"json.set", "k2", ".", R"( {"nested": {"value": "yes"}} )"});
Run({"json.set", "k3", ".", R"( {"nested": {"value": "maybe"}} )"});
EXPECT_EQ(
Run({"ft.create", "i1", "on", "json", "schema", "$.nested.value", "as", "value", "text"}),
"OK");
EXPECT_THAT(Run({"ft.search", "i1", "yes"}), AreDocIds("k2"));
}
TEST_F(SearchFamilyTest, JsonIdentifierWithBrackets) {
Run({"json.set", "k1", ".", R"({"name":"London","population":8.8,"continent":"Europe"})"});
Run({"json.set", "k2", ".", R"({"name":"Athens","population":3.1,"continent":"Europe"})"});
Run({"json.set", "k3", ".", R"({"name":"Tel-Aviv","population":1.3,"continent":"Asia"})"});
Run({"json.set", "k4", ".", R"({"name":"Hyderabad","population":9.8,"continent":"Asia"})"});
EXPECT_EQ(Run({"ft.create", "i1", "on", "json", "schema", "$[\"name\"]", "as", "name", "tag",
"$[\"population\"]", "as", "population", "numeric", "sortable", "$[\"continent\"]",
"as", "continent", "tag"}),
"OK");
EXPECT_THAT(Run({"ft.search", "i1", "(@continent:{Europe})"}), AreDocIds("k1", "k2"));
}
// todo: fails on arm build
#ifndef SANITIZERS
TEST_F(SearchFamilyTest, JsonArrayValues) {
string_view D1 = R"(
{
"name": "Alex",
"plays" : [
{"game": "Pacman", "score": 10},
{"game": "Tetris", "score": 15}
],
"areas": ["EU-west", "EU-central"]
}
)";
string_view D2 = R"(
{
"name": "Bob",
"plays" : [
{"game": "Pacman", "score": 15},
{"game": "Mario", "score": 7}
],
"areas": ["US-central"]
}
)";
string_view D3 = R"(
{
"name": "Caren",
"plays" : [
{"game": "Mario", "score": 9},
{"game": "Doom", "score": 20}
],
"areas": ["EU-central", "EU-east"]
}
)";
Run({"json.set", "k1", ".", D1});
Run({"json.set", "k2", ".", D2});
Run({"json.set", "k3", ".", D3});
Run({"ft.create", "i1",
"on", "json",
"schema", "$.name",
"as", "name",
"text", "$.plays[*].game",
"as", "games",
"tag", "$.plays[*].score",
"as", "scores",
"numeric", "$.areas[*]",
"as", "areas",
"tag"});
EXPECT_THAT(Run({"ft.search", "i1", "*"}), AreDocIds("k1", "k2", "k3"));
// Find players by games
EXPECT_THAT(Run({"ft.search", "i1", "@games:{Tetris | Mario | Doom}"}),
AreDocIds("k1", "k2", "k3"));
EXPECT_THAT(Run({"ft.search", "i1", "@games:{Pacman}"}), AreDocIds("k1", "k2"));
EXPECT_THAT(Run({"ft.search", "i1", "@games:{Mario}"}), AreDocIds("k2", "k3"));
// Find players by scores
EXPECT_THAT(Run({"ft.search", "i1", "@scores:[15 15]"}), AreDocIds("k1", "k2"));
EXPECT_THAT(Run({"ft.search", "i1", "@scores:[0 (10]"}), AreDocIds("k2", "k3"));
EXPECT_THAT(Run({"ft.search", "i1", "@scores:[(15 20]"}), AreDocIds("k3"));
// Find platers by areas
EXPECT_THAT(Run({"ft.search", "i1", "@areas:{'EU-central'}"}), AreDocIds("k1", "k3"));
EXPECT_THAT(Run({"ft.search", "i1", "@areas:{'US-central'}"}), AreDocIds("k2"));
// Test complicated RETURN expression
auto res = Run(
{"ft.search", "i1", "@name:bob", "return", "1", "max($.plays[*].score)", "as", "max-score"});
EXPECT_THAT(res, IsMapWithSize("k2", IsMap("max-score", "15")));
// Test invalid json path expression omits that field
res = Run({"ft.search", "i1", "@name:alex", "return", "1", "::??INVALID??::", "as", "retval"});
EXPECT_THAT(res, IsMapWithSize("k1", IsMap()));
}
#endif
TEST_F(SearchFamilyTest, Tags) {
Run({"hset", "d:1", "color", "red, green"});
Run({"hset", "d:2", "color", "green, blue"});
Run({"hset", "d:3", "color", "blue, red"});
Run({"hset", "d:4", "color", "red"});
Run({"hset", "d:5", "color", "green"});
Run({"hset", "d:6", "color", "blue"});
EXPECT_EQ(Run({"ft.create", "i1", "on", "hash", "schema", "color", "tag", "dummy", "numeric"}),
"OK");
EXPECT_THAT(Run({"ft.tagvals", "i2", "color"}), ErrArg("Unknown Index name"));
EXPECT_THAT(Run({"ft.tagvals", "i1", "foo"}), ErrArg("No such field"));
EXPECT_THAT(Run({"ft.tagvals", "i1", "dummy"}), ErrArg("Not a tag field"));
auto resp = Run({"ft.tagvals", "i1", "color"});
ASSERT_THAT(resp, IsUnordArray("red", "blue", "green"));
// Tags don't participate in full text search
EXPECT_THAT(Run({"ft.search", "i1", "red"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "i1", "@color:{ red }"}), AreDocIds("d:1", "d:3", "d:4"));
EXPECT_THAT(Run({"ft.search", "i1", "@color:{green}"}), AreDocIds("d:1", "d:2", "d:5"));
EXPECT_THAT(Run({"ft.search", "i1", "@color:{blue}"}), AreDocIds("d:2", "d:3", "d:6"));
EXPECT_THAT(Run({"ft.search", "i1", "@color:{red | green}"}),
AreDocIds("d:1", "d:2", "d:3", "d:4", "d:5"));
EXPECT_THAT(Run({"ft.search", "i1", "@color:{blue | green}"}),
AreDocIds("d:1", "d:2", "d:3", "d:5", "d:6"));
EXPECT_EQ(Run({"ft.create", "i2", "on", "hash", "schema", "c1", "as", "c2", "tag"}), "OK");
// TODO: there is a discrepancy here between redis stack and Dragonfly,
// we accept the original field when it has alias, while redis stack does not.
//
// EXPECT_THAT(Run({"ft.tagvals", "i2", "c1"}), ErrArg("No such field"));
EXPECT_THAT(Run({"ft.tagvals", "i2", "c2"}), ArrLen(0));
}
TEST_F(SearchFamilyTest, TagOptions) {
Run({"hset", "d:1", "color", " red/ green // bLUe "});
Run({"hset", "d:2", "color", "blue /// GReeN "});
Run({"hset", "d:3", "color", "grEEn // yellow //"});
Run({"hset", "d:4", "color", " /blue/green/ "});
EXPECT_EQ(Run({"ft.create", "i1", "on", "hash", "schema", "color", "tag", "casesensitive",
"separator", "/"}),
"OK");
EXPECT_THAT(Run({"ft.search", "i1", "@color:{green}"}), AreDocIds("d:1", "d:4"));
EXPECT_THAT(Run({"ft.search", "i1", "@color:{GReeN}"}), AreDocIds("d:2"));
EXPECT_THAT(Run({"ft.search", "i1", "@color:{blue}"}), AreDocIds("d:2", "d:4"));
}
TEST_F(SearchFamilyTest, TagNumbers) {
Run({"hset", "d:1", "number", "1"});
Run({"hset", "d:2", "number", "2"});
Run({"hset", "d:3", "number", "3"});
EXPECT_EQ(Run({"ft.create", "i1", "on", "hash", "schema", "number", "tag"}), "OK");
EXPECT_THAT(Run({"ft.search", "i1", "@number:{1}"}), AreDocIds("d:1"));
EXPECT_THAT(Run({"ft.search", "i1", "@number:{1|2}"}), AreDocIds("d:1", "d:2"));
EXPECT_THAT(Run({"ft.search", "i1", "@number:{1|2|3}"}), AreDocIds("d:1", "d:2", "d:3"));
EXPECT_THAT(Run({"ft.search", "i1", "@number:{1.0|2|3.0}"}), AreDocIds("d:2"));
EXPECT_THAT(Run({"ft.search", "i1", "@number:{1|2|3.0}"}), AreDocIds("d:1", "d:2"));
EXPECT_THAT(Run({"ft.search", "i1", "@number:{1|hello|2}"}), AreDocIds("d:1", "d:2"));
}
TEST_F(SearchFamilyTest, Numbers) {
for (unsigned i = 0; i <= 10; i++) {
for (unsigned j = 0; j <= 10; j++) {
auto key = absl::StrCat("i", i, "j", j);
Run({"hset", key, "i", absl::StrCat(i), "j", absl::StrCat(j)});
}
}
EXPECT_EQ(Run({"ft.create", "i1", "schema", "i", "numeric", "j", "numeric"}), "OK");
// Test simple ranges:
EXPECT_THAT(Run({"ft.search", "i1", "@i:[5 5] @j:[5 5]"}), AreDocIds("i5j5"));
EXPECT_THAT(Run({"ft.search", "i1", "@i:[0 1] @j:[9 10]"}),
AreDocIds("i0j9", "i0j10", "i1j9", "i1j10"));
EXPECT_THAT(Run({"ft.search", "i1", "@i:[7 8] @j:[2 3]"}),
AreDocIds("i7j2", "i7j3", "i8j2", "i8j3"));
// Test union of ranges:
EXPECT_THAT(Run({"ft.search", "i1", "(@i:[1 2] | @i:[6 6]) @j:[7 7]"}),
AreDocIds("i1j7", "i2j7", "i6j7"));
EXPECT_THAT(Run({"ft.search", "i1", "(@i:[1 5] | @i:[1 3] | @i:[3 5]) @j:[7 7]"}),
AreDocIds("i1j7", "i2j7", "i3j7", "i4j7", "i5j7"));
// Test intersection of ranges:
EXPECT_THAT(Run({"ft.search", "i1", "(@i:[9 9]) (@j:[5 7] @j:[6 8])"}),
AreDocIds("i9j6", "i9j7"));
EXPECT_THAT(Run({"ft.search", "i1", "@i:[9 9] (@j:[4 6] @j:[1 5] @j:[5 10])"}),
AreDocIds("i9j5"));
EXPECT_THAT(Run({"ft.search", "i1", "@i:[9 9] (@j:[4 6] @j:[1 5] @j:[5 10])"}),
AreDocIds("i9j5"));
// Test negation of ranges:
EXPECT_THAT(Run({"ft.search", "i1", "@i:[9 9] -@j:[1 10]"}), AreDocIds("i9j0"));
EXPECT_THAT(Run({"ft.search", "i1", "-@i:[0 9] -@j:[1 10]"}), AreDocIds("i10j0"));
// Test empty range
EXPECT_THAT(Run({"ft.search", "i1", "@i:[9 1]"}), AreDocIds());
EXPECT_THAT(Run({"ft.search", "i1", "@j:[5 0]"}), AreDocIds());
EXPECT_THAT(Run({"ft.search", "i1", "@i:[7 1] @j:[6 2]"}), AreDocIds());
}
TEST_F(SearchFamilyTest, TestLimit) {
for (unsigned i = 0; i < 20; i++)
Run({"hset", to_string(i), "match", "all"});
Run({"ft.create", "i1", "SCHEMA", "match", "text"});
// Default limit is 10
auto resp = Run({"ft.search", "i1", "all"});
EXPECT_THAT(resp, ArrLen(10 * 2 + 1));
resp = Run({"ft.search", "i1", "all", "limit", "0", "0"});
EXPECT_THAT(resp, IntArg(20));
resp = Run({"ft.search", "i1", "all", "limit", "0", "5"});
EXPECT_THAT(resp, ArrLen(5 * 2 + 1));
resp = Run({"ft.search", "i1", "all", "limit", "17", "5"});
EXPECT_THAT(resp, ArrLen(3 * 2 + 1));
}
TEST_F(SearchFamilyTest, TestReturn) {
auto floatsv = [](const float* f) -> string_view {
return {reinterpret_cast<const char*>(f), sizeof(float)};
};
for (unsigned i = 0; i < 20; i++) {
const float score = i;
Run({"hset", "k"s + to_string(i), "longA", to_string(i), "longB", to_string(i + 1), "longC",
to_string(i + 2), "secret", to_string(i + 3), "vector", floatsv(&score)});
}
Run({"ft.create", "i1", "SCHEMA", "longA", "AS", "justA", "TEXT",
"longB", "AS", "justB", "NUMERIC", "longC", "AS", "justC",
"NUMERIC", "vector", "VECTOR", "FLAT", "2", "DIM", "1"});
auto MatchEntry = [](string key, auto... fields) { return IsMapWithSize(key, IsMap(fields...)); };
// Check all fields are returned
auto resp = Run({"ft.search", "i1", "@justA:0"});
EXPECT_THAT(resp, MatchEntry("k0", "longA", "0", "longB", "1", "longC", "2", "secret", "3",
"vector", "[0]"));
// Check no fields are returned
resp = Run({"ft.search", "i1", "@justA:0", "return", "0"});
EXPECT_THAT(resp, RespArray(ElementsAre(IntArg(1), "k0")));
resp = Run({"ft.search", "i1", "@justA:0", "nocontent"});
EXPECT_THAT(resp, RespArray(ElementsAre(IntArg(1), "k0")));
// Check only one field is returned (and with original identifier)
resp = Run({"ft.search", "i1", "@justA:0", "return", "1", "longA"});
EXPECT_THAT(resp, MatchEntry("k0", "longA", "0"));
// Check only one field is returned with right alias
resp = Run({"ft.search", "i1", "@justA:0", "return", "1", "longB", "as", "madeupname"});
EXPECT_THAT(resp, MatchEntry("k0", "madeupname", "1"));
// Check two fields
resp = Run({"ft.search", "i1", "@justA:0", "return", "2", "longB", "as", "madeupname", "longC"});
EXPECT_THAT(resp, MatchEntry("k0", "madeupname", "1", "longC", "2"));
// Check non-existing field
resp = Run({"ft.search", "i1", "@justA:0", "return", "1", "nothere"});
EXPECT_THAT(resp, MatchEntry("k0", "nothere", ""));
// Checl implcit __vector_score is provided
float score = 20;
resp = Run({"ft.search", "i1", "@justA:0 => [KNN 20 @vector $vector]", "SORTBY", "__vector_score",
"DESC", "RETURN", "1", "longA", "PARAMS", "2", "vector", floatsv(&score)});
EXPECT_THAT(resp, MatchEntry("k0", "longA", "0"));
// Check sort doesn't shadow knn return alias
score = 20;
resp = Run({"ft.search", "i1", "@justA:0 => [KNN 20 @vector $vector AS vec_return]", "SORTBY",
"vec_return", "DESC", "RETURN", "1", "vec_return", "PARAMS", "2", "vector",
floatsv(&score)});
EXPECT_THAT(resp, MatchEntry("k0", "vec_return", "20"));
}
TEST_F(SearchFamilyTest, TestStopWords) {
Run({"ft.create", "i1", "STOPWORDS", "3", "red", "green", "blue", "SCHEMA", "title", "TEXT"});
Run({"hset", "d:1", "title", "ReD? parrot flies away"});
Run({"hset", "d:2", "title", "GrEEn crocodile eats you"});
Run({"hset", "d:3", "title", "BLUe. Whale surfes the sea"});
EXPECT_THAT(Run({"ft.search", "i1", "red"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "i1", "green"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "i1", "blue"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "i1", "parrot"}), AreDocIds("d:1"));
EXPECT_THAT(Run({"ft.search", "i1", "crocodile"}), AreDocIds("d:2"));
EXPECT_THAT(Run({"ft.search", "i1", "whale"}), AreDocIds("d:3"));
}
TEST_F(SearchFamilyTest, SimpleUpdates) {
EXPECT_EQ(Run({"ft.create", "i1", "schema", "title", "text", "visits", "numeric"}), "OK");
Run({"hset", "d:1", "title", "Dragonfly article", "visits", "100"});
Run({"hset", "d:2", "title", "Butterfly observations", "visits", "50"});
Run({"hset", "d:3", "title", "Bumblebee studies", "visits", "30"});
// Check values above were added to the index
EXPECT_THAT(Run({"ft.search", "i1", "article | observations | studies"}),
AreDocIds("d:1", "d:2", "d:3"));
// Update title - text value
{
Run({"hset", "d:2", "title", "Butterfly studies"});
EXPECT_THAT(Run({"ft.search", "i1", "observations"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "i1", "studies"}), AreDocIds("d:2", "d:3"));
Run({"hset", "d:1", "title", "Upcoming Dragonfly presentation"});
EXPECT_THAT(Run({"ft.search", "i1", "article"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "i1", "upcoming presentation"}), AreDocIds("d:1"));
Run({"hset", "d:3", "title", "Secret bumblebee research"});
EXPECT_THAT(Run({"ft.search", "i1", "studies"}), AreDocIds("d:2"));
EXPECT_THAT(Run({"ft.search", "i1", "secret research"}), AreDocIds("d:3"));
}
// Update visits - numeric value
{
EXPECT_THAT(Run({"ft.search", "i1", "@visits:[50 1000]"}), AreDocIds("d:1", "d:2"));
Run({"hset", "d:3", "visits", "75"});
EXPECT_THAT(Run({"ft.search", "i1", "@visits:[0 49]"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "i1", "@visits:[50 1000]"}), AreDocIds("d:1", "d:2", "d:3"));
Run({"hset", "d:1", "visits", "125"});
Run({"hset", "d:2", "visits", "150"});
EXPECT_THAT(Run({"ft.search", "i1", "@visits:[100 1000]"}), AreDocIds("d:1", "d:2"));
Run({"hset", "d:3", "visits", "175"});
EXPECT_THAT(Run({"ft.search", "i1", "@visits:[0 100]"}), kNoResults);
EXPECT_THAT(Run({"ft.search", "i1", "@visits:[150 1000]"}), AreDocIds("d:2", "d:3"));
}
// Delete documents
{
Run({"del", "d:2", "d:3"});
EXPECT_THAT(Run({"ft.search", "i1", "dragonfly"}), AreDocIds("d:1"));
EXPECT_THAT(Run({"ft.search", "i1", "butterfly | bumblebee"}), kNoResults);
}
}
TEST_F(SearchFamilyTest, Unicode) {
EXPECT_EQ(Run({"ft.create", "i1", "schema", "title", "text", "visits", "numeric"}), "OK");
// Explicitly using screaming uppercase to check utf-8 to lowercase functionality
Run({"hset", "d:1", "title", "Веселая СТРЕКОЗА Иван", "visits", "400"});
Run({"hset", "d:2", "title", "Die fröhliche Libelle Günther", "visits", "300"});
Run({"hset", "d:3", "title", "השפירית המהירה יעקב", "visits", "200"});
Run({"hset", "d:4", "title", "πανίσχυρη ΛΙΒΕΛΛΟΎΛΗ Δίας", "visits", "100"});
// Check we find our dragonfly in all languages
EXPECT_THAT(Run({"ft.search", "i1", "стРекоЗа|liBellE|השפירית|λΙβελλοΎλη"}),
AreDocIds("d:1", "d:2", "d:3", "d:4"));
// Check the result is valid
auto resp = Run({"ft.search", "i1", "λιβελλούλη"});
EXPECT_THAT(resp,
IsMapWithSize("d:4", IsMap("visits", "100", "title", "πανίσχυρη ΛΙΒΕΛΛΟΎΛΗ Δίας")));
}
TEST_F(SearchFamilyTest, UnicodeWords) {
EXPECT_EQ(Run({"ft.create", "i1", "schema", "title", "text"}), "OK");
Run({"hset", "d:1", "title",
"WORD!!! Одно слово? Zwei Wörter. Comma before ,sentence, "
"Τρεις λέξεις: χελώνα-σκύλου-γάτας. !זה עובד",
"visits", "400"});
// Make sure it includes ALL those words
EXPECT_THAT(Run({"ft.search", "i1", "word слово wörter sentence λέξεις γάτας עובד"}),
AreDocIds("d:1"));
}
TEST_F(SearchFamilyTest, BasicSort) {
auto AreRange = [](size_t total, size_t l, size_t r, string_view prefix) {
vector<string> out;
for (size_t i = min(l, r); i < max(l, r); i++)
out.push_back(absl::StrCat(prefix, i));
if (l > r)
reverse(out.begin(), out.end());
return DocIds(total, out);
};
// max_memory_limit = INT_MAX;
Run({"ft.create", "i1", "prefix", "1", "d:", "schema", "ord", "numeric", "sortable"});
for (size_t i = 0; i < 100; i++)
Run({"hset", absl::StrCat("d:", i), "ord", absl::StrCat(i)});
// Sort ranges of 23 elements
for (size_t i = 0; i < 77; i++)
EXPECT_THAT(Run({"ft.search", "i1", "*", "SORTBY", "ord", "LIMIT", to_string(i), "23"}),
AreRange(100, i, i + 23, "d:"));
// Sort ranges of 27 elements in reverse
for (size_t i = 0; i < 73; i++)
EXPECT_THAT(Run({"ft.search", "i1", "*", "SORTBY", "ord", "DESC", "LIMIT", to_string(i), "27"}),
AreRange(100, 100 - i, 100 - i - 27, "d:"));
Run({"ft.create", "i2", "prefix", "1", "d2:", "schema", "name", "text", "sortable"});
absl::InsecureBitGen gen;
vector<string> random_strs;
for (size_t i = 0; i < 10; i++)
random_strs.emplace_back(dfly::GetRandomHex(gen, 7));
sort(random_strs.begin(), random_strs.end());
for (size_t i = 0; i < 10; i++)
Run({"hset", absl::StrCat("d2:", i), "name", random_strs[i]});
for (size_t i = 0; i < 7; i++)
EXPECT_THAT(Run({"ft.search", "i2", "*", "SORTBY", "name", "DESC", "LIMIT", to_string(i), "3"}),
AreRange(10, 10 - i, 10 - i - 3, "d2:"));
}
TEST_F(SearchFamilyTest, FtProfile) {
Run({"ft.create", "i1", "schema", "name", "text"});
auto resp = Run({"ft.profile", "i1", "search", "query", "(a | b) c d"});
ASSERT_ARRAY_OF_TWO_ARRAYS(resp);
const auto& top_level = resp.GetVec();
EXPECT_THAT(top_level[0], IsMapWithSize());
const auto& profile_result = top_level[1].GetVec();
EXPECT_EQ(profile_result.size(), shard_set->size() + 1);
EXPECT_THAT(profile_result[0].GetVec(), ElementsAre("took", _, "hits", _, "serialized", _));
for (size_t sid = 0; sid < shard_set->size(); sid++) {
const auto& shard_resp = profile_result[sid + 1].GetVec();
EXPECT_THAT(shard_resp, ElementsAre("took", _, "tree", _));
const auto& tree = shard_resp[3].GetVec();
EXPECT_THAT(tree[0].GetString(), HasSubstr("Logical{n=3,o=and}"sv));
EXPECT_EQ(tree[1].GetVec().size(), 3);
}
// Test LIMITED throws no errors
resp = Run({"ft.profile", "i1", "search", "limited", "query", "(a | b) c d"});
ASSERT_ARRAY_OF_TWO_ARRAYS(resp);
}
TEST_F(SearchFamilyTest, FtProfileInvalidQuery) {
Run({"json.set", "j1", ".", R"({"id":"1"})"});
Run({"ft.create", "i1", "on", "json", "schema", "$.id", "as", "id", "tag"});
auto resp = Run({"ft.profile", "i1", "search", "query", "@id:[1 1]"});
ASSERT_ARRAY_OF_TWO_ARRAYS(resp);
EXPECT_THAT(resp.GetVec()[0], IsMapWithSize());
resp = Run({"ft.profile", "i1", "search", "query", "@{invalid13289}"});
EXPECT_THAT(resp, ErrArg("query syntax error"));
}
TEST_F(SearchFamilyTest, FtProfileErrorReply) {
Run({"ft.create", "i1", "schema", "name", "text"});
;
auto resp = Run({"ft.profile", "i1", "not_search", "query", "(a | b) c d"});
EXPECT_THAT(resp, ErrArg("no `SEARCH` or `AGGREGATE` provided"));
resp = Run({"ft.profile", "i1", "search", "not_query", "(a | b) c d"});
EXPECT_THAT(resp, ErrArg("syntax error"));
resp = Run({"ft.profile", "non_existent_key", "search", "query", "(a | b) c d"});
EXPECT_THAT(resp, ErrArg("non_existent_key: no such index"));
}
TEST_F(SearchFamilyTest, SimpleExpiry) {
EXPECT_EQ(Run({"ft.create", "i1", "schema", "title", "text", "expires-in", "numeric"}), "OK");
Run({"hset", "d:1", "title", "never to expire", "expires-in", "100500"});
Run({"hset", "d:2", "title", "first to expire", "expires-in", "50"});
Run({"pexpire", "d:2", "50"});
Run({"hset", "d:3", "title", "second to expire", "expires-in", "100"});
Run({"pexpire", "d:3", "100"});
EXPECT_THAT(Run({"ft.search", "i1", "*"}), AreDocIds("d:1", "d:2", "d:3"));
AdvanceTime(60);
ThisFiber::SleepFor(5ms); // Give heartbeat time to delete expired doc
EXPECT_THAT(Run({"ft.search", "i1", "*"}), AreDocIds("d:1", "d:3"));
AdvanceTime(60);
Run({"HGETALL", "d:3"}); // Trigger expiry by access
EXPECT_THAT(Run({"ft.search", "i1", "*"}), AreDocIds("d:1"));
Run({"flushall"});
}
TEST_F(SearchFamilyTest, DocsEditing) {
auto resp = Run({"JSON.SET", "k1", ".", R"({"a":"1"})"});
EXPECT_EQ(resp, "OK");
resp = Run({"FT.CREATE", "index", "ON", "JSON", "SCHEMA", "$.a", "AS", "a", "TEXT"});
EXPECT_EQ(resp, "OK");
resp = Run({"FT.SEARCH", "index", "*"});
EXPECT_THAT(resp, IsMapWithSize("k1", IsMap("$", R"({"a":"1"})")));
// Test dump and restore
resp = Run({"DUMP", "k1"});
auto dump = resp.GetBuf();
resp = Run({"DEL", "k1"});
EXPECT_THAT(resp, IntArg(1));
resp = Run({"RESTORE", "k1", "0", ToSV(dump)});
EXPECT_EQ(resp, "OK");
resp = Run({"FT.SEARCH", "index", "*"});
EXPECT_THAT(resp, IsMapWithSize("k1", IsMap("$", R"({"a":"1"})")));
// Test renaming a key
EXPECT_EQ(Run({"RENAME", "k1", "new_k1"}), "OK");
resp = Run({"FT.SEARCH", "index", "*"});
EXPECT_THAT(resp, IsMapWithSize("new_k1", IsMap("$", R"({"a":"1"})")));
EXPECT_EQ(Run({"RENAME", "new_k1", "k1"}), "OK");
resp = Run({"FT.SEARCH", "index", "*"});
EXPECT_THAT(resp, IsMapWithSize("k1", IsMap("$", R"({"a":"1"})")));
}
TEST_F(SearchFamilyTest, AggregateGroupBy) {
Run({"hset", "key:1", "word", "item1", "foo", "10", "text", "\"first key\"", "non_indexed_value",
"1"});
Run({"hset", "key:2", "word", "item2", "foo", "20", "text", "\"second key\"", "non_indexed_value",
"2"});
Run({"hset", "key:3", "word", "item1", "foo", "40", "text", "\"third key\"", "non_indexed_value",
"3"});
auto resp = Run(
{"ft.create", "i1", "ON", "HASH", "SCHEMA", "word", "TAG", "foo", "NUMERIC", "text", "TEXT"});
EXPECT_EQ(resp, "OK");
resp = Run(
{"ft.aggregate", "i1", "*", "GROUPBY", "1", "@word", "REDUCE", "COUNT", "0", "AS", "count"});
EXPECT_THAT(resp, IsUnordArrayWithSize(IsMap("count", "2", "word", "item1"),
IsMap("word", "item2", "count", "1")));
resp = Run({"ft.aggregate", "i1", "*", "GROUPBY", "1", "@word", "REDUCE", "SUM", "1", "@foo",
"AS", "foo_total"});
EXPECT_THAT(resp, IsUnordArrayWithSize(IsMap("foo_total", "50", "word", "item1"),
IsMap("foo_total", "20", "word", "item2")));
resp = Run({"ft.aggregate", "i1", "*", "GROUPBY", "1", "@word", "REDUCE", "AVG", "1", "@foo",
"AS", "foo_average"});
EXPECT_THAT(resp, IsUnordArrayWithSize(IsMap("foo_average", "20", "word", "item2"),
IsMap("foo_average", "25", "word", "item1")));
resp = Run({"ft.aggregate", "i1", "*", "GROUPBY", "2", "@word", "@text", "REDUCE", "SUM", "1",
"@foo", "AS", "foo_total"});
EXPECT_THAT(resp, IsUnordArrayWithSize(
IsMap("foo_total", "10", "word", "item1", "text", "\"first key\""),
IsMap("foo_total", "40", "word", "item1", "text", "\"third key\""),
IsMap("foo_total", "20", "word", "item2", "text", "\"second key\"")));
resp = Run({"ft.aggregate", "i1", "*", "LOAD", "2", "foo", "word", "GROUPBY", "1", "@word",
"REDUCE", "SUM", "1", "@foo", "AS", "foo_total"});
EXPECT_THAT(resp, IsUnordArrayWithSize(IsMap("foo_total", "20", "word", "item2"),
IsMap("foo_total", "50", "word", "item1")));
/*
Temporary not supported
resp = Run({"ft.aggregate", "i1", "*", "LOAD", "2", "foo", "text", "GROUPBY", "2", "@word",
"@text", "REDUCE", "SUM", "1", "@foo", "AS", "foo_total"}); EXPECT_THAT(resp,
IsUnordArrayWithSize(IsMap("foo_total", "20", "word", ArgType(RespExpr::NIL), "text", "\"second
key\""), IsMap("foo_total", "40", "word", ArgType(RespExpr::NIL), "text", "\"third key\""),
IsMap({"foo_total", "10", "word", ArgType(RespExpr::NIL), "text", "\"first key"})));
*/
}
TEST_F(SearchFamilyTest, JsonAggregateGroupBy) {
Run({"JSON.SET", "product:1", "$", R"({"name": "Product A", "price": 10, "quantity": 2})"});
Run({"JSON.SET", "product:2", "$", R"({"name": "Product B", "price": 20, "quantity": 3})"});
Run({"JSON.SET", "product:3", "$", R"({"name": "Product C", "price": 30, "quantity": 5})"});
auto resp =
Run({"FT.CREATE", "json_index", "ON", "JSON", "SCHEMA", "$.name", "AS", "name", "TEXT",
"$.price", "AS", "price", "NUMERIC", "$.quantity", "AS", "quantity", "NUMERIC"});
EXPECT_EQ(resp, "OK");
resp = Run({"FT.AGGREGATE", "json_index", "*", "GROUPBY", "0", "REDUCE", "SUM", "1", "price",
"AS", "total_price"});
EXPECT_THAT(resp, IsUnordArrayWithSize(IsMap("total_price", "60")));
resp = Run({"FT.AGGREGATE", "json_index", "*", "GROUPBY", "0", "REDUCE", "AVG", "1", "price",
"AS", "avg_price"});
EXPECT_THAT(resp, IsUnordArrayWithSize(IsMap("avg_price", "20")));
}
TEST_F(SearchFamilyTest, JsonAggregateGroupByWithoutAtSign) {
Run({"HSET", "h1", "group", "first", "value", "1"});
Run({"HSET", "h2", "group", "second", "value", "2"});
Run({"HSET", "h3", "group", "first", "value", "3"});
auto resp =
Run({"FT.CREATE", "index", "ON", "HASH", "SCHEMA", "group", "TAG", "value", "NUMERIC"});
EXPECT_EQ(resp, "OK");