-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathtest_search.py
1812 lines (1526 loc) · 64.3 KB
/
test_search.py
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
import bz2
import csv
import os
import asyncio
from io import TextIOWrapper
import numpy as np
import pytest
import pytest_asyncio
import redis.asyncio as redis
import redis.commands.search.aggregation as aggregations
import redis.commands.search.reducers as reducers
from redis.commands.search import AsyncSearch
from redis.commands.search.field import (
GeoField,
NumericField,
TagField,
TextField,
VectorField,
)
from redis.commands.search.index_definition import IndexDefinition, IndexType
from redis.commands.search.query import GeoFilter, NumericFilter, Query
from redis.commands.search.result import Result
from redis.commands.search.suggestion import Suggestion
from tests.conftest import (
is_resp2_connection,
skip_if_redis_enterprise,
skip_if_resp_version,
skip_if_server_version_gte,
skip_if_server_version_lt,
skip_ifmodversion_lt,
)
WILL_PLAY_TEXT = os.path.abspath(
os.path.join(os.path.dirname(__file__), "testdata", "will_play_text.csv.bz2")
)
TITLES_CSV = os.path.abspath(
os.path.join(os.path.dirname(__file__), "testdata", "titles.csv")
)
@pytest_asyncio.fixture()
async def decoded_r(create_redis, stack_url):
return await create_redis(decode_responses=True, url=stack_url)
async def waitForIndex(env, idx, timeout=None):
delay = 0.1
while True:
try:
res = await env.execute_command("FT.INFO", idx)
if int(res[res.index("indexing") + 1]) == 0:
break
except ValueError:
break
except AttributeError:
try:
if int(res["indexing"]) == 0:
break
except ValueError:
break
await asyncio.sleep(delay)
if timeout is not None:
timeout -= delay
if timeout <= 0:
break
def getClient(decoded_r: redis.Redis):
"""
Gets a client client attached to an index name which is ready to be
created
"""
return decoded_r
async def createIndex(decoded_r, num_docs=100, definition=None):
try:
await decoded_r.create_index(
(TextField("play", weight=5.0), TextField("txt"), NumericField("chapter")),
definition=definition,
)
except redis.ResponseError:
await decoded_r.dropindex(delete_documents=True)
return createIndex(decoded_r, num_docs=num_docs, definition=definition)
chapters = {}
bzfp = TextIOWrapper(bz2.BZ2File(WILL_PLAY_TEXT), encoding="utf8")
r = csv.reader(bzfp, delimiter=";")
for n, line in enumerate(r):
play, chapter, _, text = line[1], line[2], line[4], line[5]
key = f"{play}:{chapter}".lower()
d = chapters.setdefault(key, {})
d["play"] = play
d["txt"] = d.get("txt", "") + " " + text
d["chapter"] = int(chapter or 0)
if len(chapters) == num_docs:
break
indexer = decoded_r.batch_indexer(chunk_size=50)
assert isinstance(indexer, AsyncSearch.BatchIndexer)
assert 50 == indexer.chunk_size
for key, doc in chapters.items():
await indexer.client.client.hset(key, mapping=doc)
await indexer.commit()
@pytest.mark.redismod
async def test_client(decoded_r: redis.Redis):
num_docs = 500
await createIndex(decoded_r.ft(), num_docs=num_docs)
await waitForIndex(decoded_r, "idx")
# verify info
info = await decoded_r.ft().info()
for k in [
"index_name",
"index_options",
"attributes",
"num_docs",
"max_doc_id",
"num_terms",
"num_records",
"inverted_sz_mb",
"offset_vectors_sz_mb",
"doc_table_size_mb",
"key_table_size_mb",
"records_per_doc_avg",
"bytes_per_record_avg",
"offsets_per_term_avg",
"offset_bits_per_record_avg",
]:
assert k in info
assert decoded_r.ft().index_name == info["index_name"]
assert num_docs == int(info["num_docs"])
res = await decoded_r.ft().search("henry iv")
if is_resp2_connection(decoded_r):
assert isinstance(res, Result)
assert 225 == res.total
assert 10 == len(res.docs)
assert res.duration > 0
for doc in res.docs:
assert doc.id
assert doc.play == "Henry IV"
assert len(doc.txt) > 0
# test no content
res = await decoded_r.ft().search(Query("king").no_content())
assert 194 == res.total
assert 10 == len(res.docs)
for doc in res.docs:
assert "txt" not in doc.__dict__
assert "play" not in doc.__dict__
# test verbatim vs no verbatim
total = (await decoded_r.ft().search(Query("kings").no_content())).total
vtotal = (
await decoded_r.ft().search(Query("kings").no_content().verbatim())
).total
assert total > vtotal
# test in fields
txt_total = (
await decoded_r.ft().search(Query("henry").no_content().limit_fields("txt"))
).total
play_total = (
await decoded_r.ft().search(
Query("henry").no_content().limit_fields("play")
)
).total
both_total = (
await decoded_r.ft().search(
Query("henry").no_content().limit_fields("play", "txt")
)
).total
assert 129 == txt_total
assert 494 == play_total
assert 494 == both_total
# test load_document
doc = await decoded_r.ft().load_document("henry vi part 3:62")
assert doc is not None
assert "henry vi part 3:62" == doc.id
assert doc.play == "Henry VI Part 3"
assert len(doc.txt) > 0
# test in-keys
ids = [x.id for x in (await decoded_r.ft().search(Query("henry"))).docs]
assert 10 == len(ids)
subset = ids[:5]
docs = await decoded_r.ft().search(Query("henry").limit_ids(*subset))
assert len(subset) == docs.total
ids = [x.id for x in docs.docs]
assert set(ids) == set(subset)
# test slop and in order
assert 193 == (await decoded_r.ft().search(Query("henry king"))).total
assert (
3
== (
await decoded_r.ft().search(Query("henry king").slop(0).in_order())
).total
)
assert (
52
== (
await decoded_r.ft().search(Query("king henry").slop(0).in_order())
).total
)
assert 53 == (await decoded_r.ft().search(Query("henry king").slop(0))).total
assert 167 == (await decoded_r.ft().search(Query("henry king").slop(100))).total
# test delete document
await decoded_r.hset("doc-5ghs2", mapping={"play": "Death of a Salesman"})
res = await decoded_r.ft().search(Query("death of a salesman"))
assert 1 == res.total
assert 1 == await decoded_r.ft().delete_document("doc-5ghs2")
res = await decoded_r.ft().search(Query("death of a salesman"))
assert 0 == res.total
assert 0 == await decoded_r.ft().delete_document("doc-5ghs2")
await decoded_r.hset("doc-5ghs2", mapping={"play": "Death of a Salesman"})
res = await decoded_r.ft().search(Query("death of a salesman"))
assert 1 == res.total
await decoded_r.ft().delete_document("doc-5ghs2")
else:
assert isinstance(res, dict)
assert 225 == res["total_results"]
assert 10 == len(res["results"])
for doc in res["results"]:
assert doc["id"]
assert doc["extra_attributes"]["play"] == "Henry IV"
assert len(doc["extra_attributes"]["txt"]) > 0
# test no content
res = await decoded_r.ft().search(Query("king").no_content())
assert 194 == res["total_results"]
assert 10 == len(res["results"])
for doc in res["results"]:
assert "extra_attributes" not in doc.keys()
# test verbatim vs no verbatim
total = (await decoded_r.ft().search(Query("kings").no_content()))[
"total_results"
]
vtotal = (await decoded_r.ft().search(Query("kings").no_content().verbatim()))[
"total_results"
]
assert total > vtotal
# test in fields
txt_total = (
await decoded_r.ft().search(Query("henry").no_content().limit_fields("txt"))
)["total_results"]
play_total = (
await decoded_r.ft().search(
Query("henry").no_content().limit_fields("play")
)
)["total_results"]
both_total = (
await decoded_r.ft().search(
Query("henry").no_content().limit_fields("play", "txt")
)
)["total_results"]
assert 129 == txt_total
assert 494 == play_total
assert 494 == both_total
# test load_document
doc = await decoded_r.ft().load_document("henry vi part 3:62")
assert doc is not None
assert "henry vi part 3:62" == doc.id
assert doc.play == "Henry VI Part 3"
assert len(doc.txt) > 0
# test in-keys
ids = [
x["id"] for x in (await decoded_r.ft().search(Query("henry")))["results"]
]
assert 10 == len(ids)
subset = ids[:5]
docs = await decoded_r.ft().search(Query("henry").limit_ids(*subset))
assert len(subset) == docs["total_results"]
ids = [x["id"] for x in docs["results"]]
assert set(ids) == set(subset)
# test slop and in order
assert (
193 == (await decoded_r.ft().search(Query("henry king")))["total_results"]
)
assert (
3
== (await decoded_r.ft().search(Query("henry king").slop(0).in_order()))[
"total_results"
]
)
assert (
52
== (await decoded_r.ft().search(Query("king henry").slop(0).in_order()))[
"total_results"
]
)
assert (
53
== (await decoded_r.ft().search(Query("henry king").slop(0)))[
"total_results"
]
)
assert (
167
== (await decoded_r.ft().search(Query("henry king").slop(100)))[
"total_results"
]
)
# test delete document
await decoded_r.hset("doc-5ghs2", mapping={"play": "Death of a Salesman"})
res = await decoded_r.ft().search(Query("death of a salesman"))
assert 1 == res["total_results"]
assert 1 == await decoded_r.ft().delete_document("doc-5ghs2")
res = await decoded_r.ft().search(Query("death of a salesman"))
assert 0 == res["total_results"]
assert 0 == await decoded_r.ft().delete_document("doc-5ghs2")
await decoded_r.hset("doc-5ghs2", mapping={"play": "Death of a Salesman"})
res = await decoded_r.ft().search(Query("death of a salesman"))
assert 1 == res["total_results"]
await decoded_r.ft().delete_document("doc-5ghs2")
@pytest.mark.redismod
@pytest.mark.onlynoncluster
@skip_if_server_version_gte("7.9.0")
async def test_scores(decoded_r: redis.Redis):
await decoded_r.ft().create_index((TextField("txt"),))
await decoded_r.hset("doc1", mapping={"txt": "foo baz"})
await decoded_r.hset("doc2", mapping={"txt": "foo bar"})
q = Query("foo ~bar").with_scores()
res = await decoded_r.ft().search(q)
if is_resp2_connection(decoded_r):
assert 2 == res.total
assert "doc2" == res.docs[0].id
assert 3.0 == res.docs[0].score
assert "doc1" == res.docs[1].id
else:
assert 2 == res["total_results"]
assert "doc2" == res["results"][0]["id"]
assert 3.0 == res["results"][0]["score"]
assert "doc1" == res["results"][1]["id"]
@pytest.mark.redismod
@pytest.mark.onlynoncluster
@skip_if_server_version_lt("7.9.0")
async def test_scores_with_new_default_scorer(decoded_r: redis.Redis):
await decoded_r.ft().create_index((TextField("txt"),))
await decoded_r.hset("doc1", mapping={"txt": "foo baz"})
await decoded_r.hset("doc2", mapping={"txt": "foo bar"})
q = Query("foo ~bar").with_scores()
res = await decoded_r.ft().search(q)
if is_resp2_connection(decoded_r):
assert 2 == res.total
assert "doc2" == res.docs[0].id
assert 0.87 == pytest.approx(res.docs[0].score, 0.01)
assert "doc1" == res.docs[1].id
else:
assert 2 == res["total_results"]
assert "doc2" == res["results"][0]["id"]
assert 0.87 == pytest.approx(res["results"][0]["score"], 0.01)
assert "doc1" == res["results"][1]["id"]
@pytest.mark.redismod
async def test_stopwords(decoded_r: redis.Redis):
stopwords = ["foo", "bar", "baz"]
await decoded_r.ft().create_index((TextField("txt"),), stopwords=stopwords)
await decoded_r.hset("doc1", mapping={"txt": "foo bar"})
await decoded_r.hset("doc2", mapping={"txt": "hello world"})
await waitForIndex(decoded_r, "idx")
q1 = Query("foo bar").no_content()
q2 = Query("foo bar hello world").no_content()
res1, res2 = await decoded_r.ft().search(q1), await decoded_r.ft().search(q2)
if is_resp2_connection(decoded_r):
assert 0 == res1.total
assert 1 == res2.total
else:
assert 0 == res1["total_results"]
assert 1 == res2["total_results"]
@pytest.mark.redismod
async def test_filters(decoded_r: redis.Redis):
await decoded_r.ft().create_index(
(TextField("txt"), NumericField("num"), GeoField("loc"))
)
await decoded_r.hset(
"doc1", mapping={"txt": "foo bar", "num": 3.141, "loc": "-0.441,51.458"}
)
await decoded_r.hset(
"doc2", mapping={"txt": "foo baz", "num": 2, "loc": "-0.1,51.2"}
)
await waitForIndex(decoded_r, "idx")
# Test numerical filter
q1 = Query("foo").add_filter(NumericFilter("num", 0, 2)).no_content()
q2 = (
Query("foo")
.add_filter(NumericFilter("num", 2, NumericFilter.INF, minExclusive=True))
.no_content()
)
res1, res2 = await decoded_r.ft().search(q1), await decoded_r.ft().search(q2)
if is_resp2_connection(decoded_r):
assert 1 == res1.total
assert 1 == res2.total
assert "doc2" == res1.docs[0].id
assert "doc1" == res2.docs[0].id
else:
assert 1 == res1["total_results"]
assert 1 == res2["total_results"]
assert "doc2" == res1["results"][0]["id"]
assert "doc1" == res2["results"][0]["id"]
# Test geo filter
q1 = Query("foo").add_filter(GeoFilter("loc", -0.44, 51.45, 10)).no_content()
q2 = Query("foo").add_filter(GeoFilter("loc", -0.44, 51.45, 100)).no_content()
res1, res2 = await decoded_r.ft().search(q1), await decoded_r.ft().search(q2)
if is_resp2_connection(decoded_r):
assert 1 == res1.total
assert 2 == res2.total
assert "doc1" == res1.docs[0].id
# Sort results, after RDB reload order may change
res = [res2.docs[0].id, res2.docs[1].id]
res.sort()
assert ["doc1", "doc2"] == res
else:
assert 1 == res1["total_results"]
assert 2 == res2["total_results"]
assert "doc1" == res1["results"][0]["id"]
# Sort results, after RDB reload order may change
res = [res2["results"][0]["id"], res2["results"][1]["id"]]
res.sort()
assert ["doc1", "doc2"] == res
@pytest.mark.redismod
async def test_sort_by(decoded_r: redis.Redis):
await decoded_r.ft().create_index(
(TextField("txt"), NumericField("num", sortable=True))
)
await decoded_r.hset("doc1", mapping={"txt": "foo bar", "num": 1})
await decoded_r.hset("doc2", mapping={"txt": "foo baz", "num": 2})
await decoded_r.hset("doc3", mapping={"txt": "foo qux", "num": 3})
# Test sort
q1 = Query("foo").sort_by("num", asc=True).no_content()
q2 = Query("foo").sort_by("num", asc=False).no_content()
res1, res2 = await decoded_r.ft().search(q1), await decoded_r.ft().search(q2)
if is_resp2_connection(decoded_r):
assert 3 == res1.total
assert "doc1" == res1.docs[0].id
assert "doc2" == res1.docs[1].id
assert "doc3" == res1.docs[2].id
assert 3 == res2.total
assert "doc1" == res2.docs[2].id
assert "doc2" == res2.docs[1].id
assert "doc3" == res2.docs[0].id
else:
assert 3 == res1["total_results"]
assert "doc1" == res1["results"][0]["id"]
assert "doc2" == res1["results"][1]["id"]
assert "doc3" == res1["results"][2]["id"]
assert 3 == res2["total_results"]
assert "doc1" == res2["results"][2]["id"]
assert "doc2" == res2["results"][1]["id"]
assert "doc3" == res2["results"][0]["id"]
@pytest.mark.redismod
@skip_ifmodversion_lt("2.0.0", "search")
async def test_drop_index(decoded_r: redis.Redis):
"""
Ensure the index gets dropped by data remains by default
"""
for x in range(20):
for keep_docs in [[True, {}], [False, {"name": "haveit"}]]:
idx = "HaveIt"
index = getClient(decoded_r)
await index.hset("index:haveit", mapping={"name": "haveit"})
idef = IndexDefinition(prefix=["index:"])
await index.ft(idx).create_index((TextField("name"),), definition=idef)
await waitForIndex(index, idx)
await index.ft(idx).dropindex(delete_documents=keep_docs[0])
i = await index.hgetall("index:haveit")
assert i == keep_docs[1]
@pytest.mark.redismod
async def test_example(decoded_r: redis.Redis):
# Creating the index definition and schema
await decoded_r.ft().create_index(
(TextField("title", weight=5.0), TextField("body"))
)
# Indexing a document
await decoded_r.hset(
"doc1",
mapping={
"title": "RediSearch",
"body": "Redisearch impements a search engine on top of redis",
},
)
# Searching with complex parameters:
q = Query("search engine").verbatim().no_content().paging(0, 5)
res = await decoded_r.ft().search(q)
assert res is not None
@pytest.mark.redismod
async def test_auto_complete(decoded_r: redis.Redis):
n = 0
with open(TITLES_CSV) as f:
cr = csv.reader(f)
for row in cr:
n += 1
term, score = row[0], float(row[1])
assert n == await decoded_r.ft().sugadd("ac", Suggestion(term, score=score))
assert n == await decoded_r.ft().suglen("ac")
ret = await decoded_r.ft().sugget("ac", "bad", with_scores=True)
assert 2 == len(ret)
assert "badger" == ret[0].string
assert isinstance(ret[0].score, float)
assert 1.0 != ret[0].score
assert "badalte rishtey" == ret[1].string
assert isinstance(ret[1].score, float)
assert 1.0 != ret[1].score
ret = await decoded_r.ft().sugget("ac", "bad", fuzzy=True, num=10)
assert 10 == len(ret)
assert 1.0 == ret[0].score
strs = {x.string for x in ret}
for sug in strs:
assert 1 == await decoded_r.ft().sugdel("ac", sug)
# make sure a second delete returns 0
for sug in strs:
assert 0 == await decoded_r.ft().sugdel("ac", sug)
# make sure they were actually deleted
ret2 = await decoded_r.ft().sugget("ac", "bad", fuzzy=True, num=10)
for sug in ret2:
assert sug.string not in strs
# Test with payload
await decoded_r.ft().sugadd("ac", Suggestion("pay1", payload="pl1"))
await decoded_r.ft().sugadd("ac", Suggestion("pay2", payload="pl2"))
await decoded_r.ft().sugadd("ac", Suggestion("pay3", payload="pl3"))
sugs = await decoded_r.ft().sugget(
"ac", "pay", with_payloads=True, with_scores=True
)
assert 3 == len(sugs)
for sug in sugs:
assert sug.payload
assert sug.payload.startswith("pl")
@pytest.mark.redismod
async def test_no_index(decoded_r: redis.Redis):
await decoded_r.ft().create_index(
(
TextField("field"),
TextField("text", no_index=True, sortable=True),
NumericField("numeric", no_index=True, sortable=True),
GeoField("geo", no_index=True, sortable=True),
TagField("tag", no_index=True, sortable=True),
)
)
await decoded_r.hset(
"doc1",
mapping={"field": "aaa", "text": "1", "numeric": "1", "geo": "1,1", "tag": "1"},
)
await decoded_r.hset(
"doc2",
mapping={"field": "aab", "text": "2", "numeric": "2", "geo": "2,2", "tag": "2"},
)
await waitForIndex(decoded_r, "idx")
if is_resp2_connection(decoded_r):
res = await decoded_r.ft().search(Query("@text:aa*"))
assert 0 == res.total
res = await decoded_r.ft().search(Query("@field:aa*"))
assert 2 == res.total
res = await decoded_r.ft().search(Query("*").sort_by("text", asc=False))
assert 2 == res.total
assert "doc2" == res.docs[0].id
res = await decoded_r.ft().search(Query("*").sort_by("text", asc=True))
assert "doc1" == res.docs[0].id
res = await decoded_r.ft().search(Query("*").sort_by("numeric", asc=True))
assert "doc1" == res.docs[0].id
res = await decoded_r.ft().search(Query("*").sort_by("geo", asc=True))
assert "doc1" == res.docs[0].id
res = await decoded_r.ft().search(Query("*").sort_by("tag", asc=True))
assert "doc1" == res.docs[0].id
else:
res = await decoded_r.ft().search(Query("@text:aa*"))
assert 0 == res["total_results"]
res = await decoded_r.ft().search(Query("@field:aa*"))
assert 2 == res["total_results"]
res = await decoded_r.ft().search(Query("*").sort_by("text", asc=False))
assert 2 == res["total_results"]
assert "doc2" == res["results"][0]["id"]
res = await decoded_r.ft().search(Query("*").sort_by("text", asc=True))
assert "doc1" == res["results"][0]["id"]
res = await decoded_r.ft().search(Query("*").sort_by("numeric", asc=True))
assert "doc1" == res["results"][0]["id"]
res = await decoded_r.ft().search(Query("*").sort_by("geo", asc=True))
assert "doc1" == res["results"][0]["id"]
res = await decoded_r.ft().search(Query("*").sort_by("tag", asc=True))
assert "doc1" == res["results"][0]["id"]
# Ensure exception is raised for non-indexable, non-sortable fields
with pytest.raises(Exception):
TextField("name", no_index=True, sortable=False)
with pytest.raises(Exception):
NumericField("name", no_index=True, sortable=False)
with pytest.raises(Exception):
GeoField("name", no_index=True, sortable=False)
with pytest.raises(Exception):
TagField("name", no_index=True, sortable=False)
@pytest.mark.redismod
async def test_explain(decoded_r: redis.Redis):
await decoded_r.ft().create_index(
(TextField("f1"), TextField("f2"), TextField("f3"))
)
res = await decoded_r.ft().explain("@f3:f3_val @f2:f2_val @f1:f1_val")
assert res
@pytest.mark.redismod
async def test_explaincli(decoded_r: redis.Redis):
with pytest.raises(NotImplementedError):
await decoded_r.ft().explain_cli("foo")
@pytest.mark.redismod
async def test_summarize(decoded_r: redis.Redis):
await createIndex(decoded_r.ft())
await waitForIndex(decoded_r, "idx")
q = Query('"king henry"').paging(0, 1)
q.highlight(fields=("play", "txt"), tags=("<b>", "</b>"))
q.summarize("txt")
if is_resp2_connection(decoded_r):
doc = sorted((await decoded_r.ft().search(q)).docs)[0]
assert "<b>Henry</b> IV" == doc.play
assert (
"ACT I SCENE I. London. The palace. Enter <b>KING</b> <b>HENRY</b>, LORD JOHN OF LANCASTER, the EARL of WESTMORELAND, SIR... " # noqa
== doc.txt
)
q = Query('"king henry"').paging(0, 1).summarize().highlight()
doc = sorted((await decoded_r.ft().search(q)).docs)[0]
assert "<b>Henry</b> ... " == doc.play
assert (
"ACT I SCENE I. London. The palace. Enter <b>KING</b> <b>HENRY</b>, LORD JOHN OF LANCASTER, the EARL of WESTMORELAND, SIR... " # noqa
== doc.txt
)
else:
doc = sorted((await decoded_r.ft().search(q))["results"])[0]
assert "<b>Henry</b> IV" == doc["extra_attributes"]["play"]
assert (
"ACT I SCENE I. London. The palace. Enter <b>KING</b> <b>HENRY</b>, LORD JOHN OF LANCASTER, the EARL of WESTMORELAND, SIR... " # noqa
== doc["extra_attributes"]["txt"]
)
q = Query('"king henry"').paging(0, 1).summarize().highlight()
doc = sorted((await decoded_r.ft().search(q))["results"])[0]
assert "<b>Henry</b> ... " == doc["extra_attributes"]["play"]
assert (
"ACT I SCENE I. London. The palace. Enter <b>KING</b> <b>HENRY</b>, LORD JOHN OF LANCASTER, the EARL of WESTMORELAND, SIR... " # noqa
== doc["extra_attributes"]["txt"]
)
@pytest.mark.redismod
@skip_ifmodversion_lt("2.0.0", "search")
async def test_alias(decoded_r: redis.Redis):
index1 = getClient(decoded_r)
index2 = getClient(decoded_r)
def1 = IndexDefinition(prefix=["index1:"])
def2 = IndexDefinition(prefix=["index2:"])
ftindex1 = index1.ft("testAlias")
ftindex2 = index2.ft("testAlias2")
await ftindex1.create_index((TextField("name"),), definition=def1)
await ftindex2.create_index((TextField("name"),), definition=def2)
await index1.hset("index1:lonestar", mapping={"name": "lonestar"})
await index2.hset("index2:yogurt", mapping={"name": "yogurt"})
if is_resp2_connection(decoded_r):
res = (await ftindex1.search("*")).docs[0]
assert "index1:lonestar" == res.id
# create alias and check for results
await ftindex1.aliasadd("spaceballs")
alias_client = getClient(decoded_r).ft("spaceballs")
res = (await alias_client.search("*")).docs[0]
assert "index1:lonestar" == res.id
# Throw an exception when trying to add an alias that already exists
with pytest.raises(Exception):
await ftindex2.aliasadd("spaceballs")
# update alias and ensure new results
await ftindex2.aliasupdate("spaceballs")
alias_client2 = getClient(decoded_r).ft("spaceballs")
res = (await alias_client2.search("*")).docs[0]
assert "index2:yogurt" == res.id
else:
res = (await ftindex1.search("*"))["results"][0]
assert "index1:lonestar" == res["id"]
# create alias and check for results
await ftindex1.aliasadd("spaceballs")
alias_client = getClient(await decoded_r).ft("spaceballs")
res = (await alias_client.search("*"))["results"][0]
assert "index1:lonestar" == res["id"]
# Throw an exception when trying to add an alias that already exists
with pytest.raises(Exception):
await ftindex2.aliasadd("spaceballs")
# update alias and ensure new results
await ftindex2.aliasupdate("spaceballs")
alias_client2 = getClient(await decoded_r).ft("spaceballs")
res = (await alias_client2.search("*"))["results"][0]
assert "index2:yogurt" == res["id"]
await ftindex2.aliasdel("spaceballs")
with pytest.raises(Exception):
(await alias_client2.search("*")).docs[0]
@pytest.mark.redismod
@pytest.mark.xfail(strict=False)
async def test_alias_basic(decoded_r: redis.Redis):
# Creating a client with one index
client = getClient(decoded_r)
await client.flushdb()
index1 = getClient(decoded_r).ft("testAlias")
await index1.create_index((TextField("txt"),))
await index1.client.hset("doc1", mapping={"txt": "text goes here"})
index2 = getClient(decoded_r).ft("testAlias2")
await index2.create_index((TextField("txt"),))
await index2.client.hset("doc2", mapping={"txt": "text goes here"})
# add the actual alias and check
await index1.aliasadd("myalias")
alias_client = getClient(decoded_r).ft("myalias")
if is_resp2_connection(decoded_r):
res = sorted((await alias_client.search("*")).docs, key=lambda x: x.id)
assert "doc1" == res[0].id
# Throw an exception when trying to add an alias that already exists
with pytest.raises(Exception):
await index2.aliasadd("myalias")
# update the alias and ensure we get doc2
await index2.aliasupdate("myalias")
alias_client2 = getClient(decoded_r).ft("myalias")
res = sorted((await alias_client2.search("*")).docs, key=lambda x: x.id)
assert "doc1" == res[0].id
else:
res = sorted((await alias_client.search("*"))["results"], key=lambda x: x["id"])
assert "doc1" == res[0]["id"]
# Throw an exception when trying to add an alias that already exists
with pytest.raises(Exception):
await index2.aliasadd("myalias")
# update the alias and ensure we get doc2
await index2.aliasupdate("myalias")
alias_client2 = getClient(client).ft("myalias")
res = sorted(
(await alias_client2.search("*"))["results"], key=lambda x: x["id"]
)
assert "doc1" == res[0]["id"]
# delete the alias and expect an error if we try to query again
await index2.aliasdel("myalias")
with pytest.raises(Exception):
_ = (await alias_client2.search("*")).docs[0]
@pytest.mark.redismod
async def test_tags(decoded_r: redis.Redis):
await decoded_r.ft().create_index((TextField("txt"), TagField("tags")))
tags = "foo,foo bar,hello;world"
tags2 = "soba,ramen"
await decoded_r.hset("doc1", mapping={"txt": "fooz barz", "tags": tags})
await decoded_r.hset("doc2", mapping={"txt": "noodles", "tags": tags2})
await waitForIndex(decoded_r, "idx")
q = Query("@tags:{foo}")
if is_resp2_connection(decoded_r):
res = await decoded_r.ft().search(q)
assert 1 == res.total
q = Query("@tags:{foo bar}")
res = await decoded_r.ft().search(q)
assert 1 == res.total
q = Query("@tags:{foo\\ bar}")
res = await decoded_r.ft().search(q)
assert 1 == res.total
q = Query("@tags:{hello\\;world}")
res = await decoded_r.ft().search(q)
assert 1 == res.total
q2 = await decoded_r.ft().tagvals("tags")
assert (tags.split(",") + tags2.split(",")).sort() == q2.sort()
else:
res = await decoded_r.ft().search(q)
assert 1 == res["total_results"]
q = Query("@tags:{foo bar}")
res = await decoded_r.ft().search(q)
assert 1 == res["total_results"]
q = Query("@tags:{foo\\ bar}")
res = await decoded_r.ft().search(q)
assert 1 == res["total_results"]
q = Query("@tags:{hello\\;world}")
res = await decoded_r.ft().search(q)
assert 1 == res["total_results"]
q2 = await decoded_r.ft().tagvals("tags")
assert set(tags.split(",") + tags2.split(",")) == set(q2)
@pytest.mark.redismod
async def test_textfield_sortable_nostem(decoded_r: redis.Redis):
# Creating the index definition with sortable and no_stem
await decoded_r.ft().create_index((TextField("txt", sortable=True, no_stem=True),))
# Now get the index info to confirm its contents
response = await decoded_r.ft().info()
if is_resp2_connection(decoded_r):
assert "SORTABLE" in response["attributes"][0]
assert "NOSTEM" in response["attributes"][0]
else:
assert "SORTABLE" in response["attributes"][0]["flags"]
assert "NOSTEM" in response["attributes"][0]["flags"]
@pytest.mark.redismod
async def test_alter_schema_add(decoded_r: redis.Redis):
# Creating the index definition and schema
await decoded_r.ft().create_index(TextField("title"))
# Using alter to add a field
await decoded_r.ft().alter_schema_add(TextField("body"))
# Indexing a document
await decoded_r.hset(
"doc1", mapping={"title": "MyTitle", "body": "Some content only in the body"}
)
# Searching with parameter only in the body (the added field)
q = Query("only in the body")
# Ensure we find the result searching on the added body field
res = await decoded_r.ft().search(q)
if is_resp2_connection(decoded_r):
assert 1 == res.total
else:
assert 1 == res["total_results"]
@pytest.mark.redismod
async def test_spell_check(decoded_r: redis.Redis):
await decoded_r.ft().create_index((TextField("f1"), TextField("f2")))
await decoded_r.hset(
"doc1", mapping={"f1": "some valid content", "f2": "this is sample text"}
)
await decoded_r.hset("doc2", mapping={"f1": "very important", "f2": "lorem ipsum"})
await waitForIndex(decoded_r, "idx")
if is_resp2_connection(decoded_r):
# test spellcheck
res = await decoded_r.ft().spellcheck("impornant")
assert "important" == res["impornant"][0]["suggestion"]
res = await decoded_r.ft().spellcheck("contnt")
assert "content" == res["contnt"][0]["suggestion"]
# test spellcheck with Levenshtein distance
res = await decoded_r.ft().spellcheck("vlis")
assert res == {}
res = await decoded_r.ft().spellcheck("vlis", distance=2)
assert "valid" == res["vlis"][0]["suggestion"]
# test spellcheck include
await decoded_r.ft().dict_add("dict", "lore", "lorem", "lorm")
res = await decoded_r.ft().spellcheck("lorm", include="dict")
assert len(res["lorm"]) == 3
assert (
res["lorm"][0]["suggestion"],
res["lorm"][1]["suggestion"],
res["lorm"][2]["suggestion"],
) == ("lorem", "lore", "lorm")
assert (res["lorm"][0]["score"], res["lorm"][1]["score"]) == ("0.5", "0")
# test spellcheck exclude
res = await decoded_r.ft().spellcheck("lorm", exclude="dict")
assert res == {}
else:
# test spellcheck
res = await decoded_r.ft().spellcheck("impornant")
assert "important" in res["results"]["impornant"][0].keys()
res = await decoded_r.ft().spellcheck("contnt")
assert "content" in res["results"]["contnt"][0].keys()
# test spellcheck with Levenshtein distance
res = await decoded_r.ft().spellcheck("vlis")
assert res == {"results": {"vlis": []}}
res = await decoded_r.ft().spellcheck("vlis", distance=2)
assert "valid" in res["results"]["vlis"][0].keys()
# test spellcheck include
await decoded_r.ft().dict_add("dict", "lore", "lorem", "lorm")
res = await decoded_r.ft().spellcheck("lorm", include="dict")
assert len(res["results"]["lorm"]) == 3
assert "lorem" in res["results"]["lorm"][0].keys()
assert "lore" in res["results"]["lorm"][1].keys()
assert "lorm" in res["results"]["lorm"][2].keys()
assert (
res["results"]["lorm"][0]["lorem"],
res["results"]["lorm"][1]["lore"],
) == (0.5, 0)
# test spellcheck exclude
res = await decoded_r.ft().spellcheck("lorm", exclude="dict")
assert res == {"results": {}}
@pytest.mark.redismod