-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathtest_document_store.py
More file actions
1342 lines (1149 loc) · 58.8 KB
/
test_document_store.py
File metadata and controls
1342 lines (1149 loc) · 58.8 KB
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
# SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
#
# SPDX-License-Identifier: Apache-2.0
# ruff: noqa: S110
import struct
from dataclasses import replace
from unittest.mock import MagicMock, patch
import pytest
from glide_shared.commands.server_modules.ft_options.ft_create_options import DistanceMetricType
from glide_shared.commands.server_modules.ft_options.ft_search_options import FtSearchOptions
from haystack.dataclasses import Document
from haystack.dataclasses.byte_stream import ByteStream
from haystack.document_stores.types import DuplicatePolicy
from haystack.errors import FilterError
from haystack.testing.document_store import (
CountDocumentsByFilterTest,
CountDocumentsTest,
CountUniqueMetadataByFilterTest,
DeleteAllTest,
DeleteByFilterTest,
DeleteDocumentsTest,
FilterableDocsFixtureMixin,
GetMetadataFieldMinMaxTest,
GetMetadataFieldsInfoTest,
GetMetadataFieldUniqueValuesTest,
UpdateByFilterTest,
WriteDocumentsTest,
create_filterable_docs,
)
from haystack.utils import Secret
from haystack_integrations.document_stores.valkey import ValkeyDocumentStore
from haystack_integrations.document_stores.valkey import document_store as ds_module
from haystack_integrations.document_stores.valkey.document_store import ValkeyDocumentStoreError
def _filterable_docs_embedding_dim_3() -> list[Document]:
"""Filterable docs with 3-dim embeddings for Valkey (store uses embedding_dim=3)."""
docs = create_filterable_docs()
return [
replace(
d,
embedding=d.embedding[:3] if d.embedding and len(d.embedding) >= 3 else [0.0, 0.0, 0.0],
)
for d in docs
]
@pytest.mark.integration
class TestValkeyDocumentStore(
CountDocumentsTest,
WriteDocumentsTest,
DeleteAllTest,
DeleteByFilterTest,
DeleteDocumentsTest,
FilterableDocsFixtureMixin,
UpdateByFilterTest,
CountDocumentsByFilterTest,
CountUniqueMetadataByFilterTest,
GetMetadataFieldsInfoTest,
GetMetadataFieldMinMaxTest,
GetMetadataFieldUniqueValuesTest,
):
@pytest.fixture
def document_store(self):
store = ValkeyDocumentStore(
index_name="test_haystack_document",
embedding_dim=3,
metadata_fields={
"category": str,
"priority": int,
"status": str,
"score": int,
"timestamp": int,
"quality": str,
"year": int,
"featured": int, # for base-class test_update_by_filter_advanced_filters (meta.featured)
"rating": float, # for GetMetadataFieldMinMaxTest (float field)
"age": int, # for GetMetadataFieldMinMaxTest meta_prefix test
# for base-class UpdateByFilterTest.filterable_docs and filter tests:
"name": str,
"page": str,
"chapter": str,
"number": int,
"date": str,
"updated": int, # bool from update_by_filter tests
"extra_field": str,
},
)
yield store
try:
store._client.flushdb()
store.close()
except Exception:
pass
@pytest.fixture
def filterable_docs(self) -> list[Document]:
"""Filterable docs with 3-dim embeddings (Valkey store uses embedding_dim=3)."""
return _filterable_docs_embedding_dim_3()
def test_write_documents(self, document_store):
"""Test default write_documents() behavior (OVERWRITE by default)."""
docs = [Document(id="1", content="test doc 1")]
assert document_store.write_documents(docs) == 1
# Valkey overwrites by default
assert document_store.write_documents(docs) == 1
assert document_store.count_documents() == 1
def test_get_metadata_fields_info_empty_collection(self, document_store):
"""Valkey pre-configures metadata fields at init, so they're always present even when empty."""
pytest.skip("Valkey metadata fields are pre-configured at init, not discovered from documents")
def test_write_documents_duplicate_fail(self, document_store):
"""Valkey only supports OVERWRITE policy, skip FAIL test."""
pytest.skip("Valkey only supports DuplicatePolicy.OVERWRITE")
def test_write_documents_duplicate_skip(self, document_store):
"""Valkey only supports OVERWRITE policy, skip SKIP test."""
pytest.skip("Valkey only supports DuplicatePolicy.OVERWRITE")
def test_search_by_embedding_no_limit(self, document_store):
docs = [
Document(
id="search1",
content="similar content",
embedding=[0.1, 0.2, 0.3],
meta={"category": "test", "priority": 1},
blob=ByteStream(data=b"binary_data", mime_type="application/octet-stream"),
score=0.95,
),
Document(
id="search2",
content="different content",
embedding=[0.9, 0.8, 0.7],
meta={"category": "other", "priority": 2},
score=0.85,
),
Document(
id="search3",
content="another content",
embedding=[0.2, 0.3, 0.4],
meta={"category": "test", "priority": 3},
),
Document(id="search4", content="another content", meta={"category": "test", "priority": 3}),
]
document_store.write_documents(docs)
# Verify documents are written
assert document_store.count_documents() == 4
# Search with embedding similar to first document
query_embedding = [0.1, 0.2, 0.3]
results = document_store._embedding_retrieval(query_embedding, limit=100)
assert len(results) == 4, f"Expected 2 results, got {len(results)}"
assert results[0].id == "search1" # Most similar should be first
assert results[3].id == "search4" # Document without embedding should be last
def test_search_by_embedding_with_limit(self, document_store):
docs = [
Document(
id="search1",
content="similar content",
embedding=[0.1, 0.2, 0.3],
meta={"category": "test", "priority": 1},
blob=ByteStream(data=b"binary_data", mime_type="application/octet-stream"),
score=0.95,
),
Document(
id="search2",
content="different content",
embedding=[0.9, 0.8, 0.7],
meta={"category": "other", "priority": 2},
score=0.85,
),
Document(
id="search3",
content="another content",
embedding=[0.2, 0.3, 0.4],
meta={"category": "test", "priority": 3},
),
Document(id="search4", content="another content", meta={"category": "test", "priority": 3}),
]
document_store.write_documents(docs)
# Verify documents are written
assert document_store.count_documents() == 4
# Search with embedding similar to first document
query_embedding = [0.1, 0.2, 0.3]
results = document_store._embedding_retrieval(query_embedding, limit=2)
assert len(results) == 2, f"Expected 2 results, got {len(results)}"
assert results[0].id == "search1" # Most similar should be first
assert results[1].id == "search3" # Document without embedding should be last
def test_search_by_embedding_with_category_filter(self, document_store):
docs = [
Document(
id="search1",
content="similar content",
embedding=[0.1, 0.2, 0.3],
meta={"category": "test", "priority": 1},
blob=ByteStream(data=b"binary_data", mime_type="application/octet-stream"),
score=0.95,
),
Document(
id="search2",
content="different content",
embedding=[0.9, 0.8, 0.7],
meta={"category": "other", "priority": 2},
score=0.85,
),
Document(
id="search3",
content="another content",
embedding=[0.2, 0.3, 0.4],
meta={"category": "test2", "priority": 3},
),
Document(id="search4", content="another content", meta={"category": "test3", "priority": 3}),
]
document_store.write_documents(docs)
# Verify documents are written
assert document_store.count_documents() == 4
# Search with embedding similar to first document
query_embedding = [0.1, 0.2, 0.3]
filters = {"operator": "AND", "conditions": [{"field": "meta.category", "operator": "==", "value": "test"}]}
results = document_store._embedding_retrieval(query_embedding, filters, limit=2)
assert len(results) == 1, f"Expected 1 result, got {len(results)}"
assert results[0].id == "search1" # Most similar should be first
def test_search_by_embedding_with_numeric_filter(self, document_store):
docs = [
Document(id="n1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"priority": 1, "score": 0.8}),
Document(id="n2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"priority": 5, "score": 0.9}),
Document(id="n3", content="doc 3", embedding=[0.3, 0.4, 0.5], meta={"priority": 10, "score": 0.7}),
]
document_store.write_documents(docs)
query_embedding = [0.1, 0.2, 0.3]
filters = {"operator": "AND", "conditions": [{"field": "meta.priority", "operator": ">=", "value": 5}]}
results = document_store._embedding_retrieval(query_embedding, filters, limit=10)
assert len(results) == 2
assert {doc.id for doc in results} == {"n2", "n3"}
# Results should be ordered by similarity to query
assert results[0].id == "n2" # Closer to query embedding
def test_search_by_embedding_with_or_filter(self, document_store):
docs = [
Document(
id="o1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"status": "active", "category": "news"}
),
Document(
id="o2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"status": "pending", "category": "sports"}
),
Document(
id="o3", content="doc 3", embedding=[0.9, 0.8, 0.7], meta={"status": "inactive", "category": "news"}
),
]
document_store.write_documents(docs)
query_embedding = [0.1, 0.2, 0.3]
filters = {
"operator": "OR",
"conditions": [
{"field": "meta.status", "operator": "==", "value": "active"},
{"field": "meta.category", "operator": "==", "value": "sports"},
],
}
results = document_store._embedding_retrieval(query_embedding, filters, limit=10)
assert len(results) == 2
assert {doc.id for doc in results} == {"o1", "o2"}
# Results should be ordered by similarity
assert results[0].id == "o1" # Closer to query embedding
def test_search_by_embedding_with_in_filter(self, document_store):
docs = [
Document(id="i1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"status": "active"}),
Document(id="i2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"status": "pending"}),
Document(id="i3", content="doc 3", embedding=[0.3, 0.4, 0.5], meta={"status": "inactive"}),
Document(id="i4", content="doc 4", embedding=[0.9, 0.8, 0.7], meta={"status": "archived"}),
]
document_store.write_documents(docs)
query_embedding = [0.1, 0.2, 0.3]
filters = {
"operator": "AND",
"conditions": [{"field": "meta.status", "operator": "in", "value": ["active", "pending"]}],
}
results = document_store._embedding_retrieval(query_embedding, filters, limit=10)
assert len(results) == 2
assert {doc.id for doc in results} == {"i1", "i2"}
# Results should be ordered by similarity
assert results[0].id == "i1" # Closest to query
def test_search_by_embedding_with_complex_nested_filter(self, document_store):
docs = [
Document(
id="c1",
content="doc 1",
embedding=[0.1, 0.2, 0.3],
meta={"category": "news", "priority": 1, "status": "active"},
),
Document(
id="c2",
content="doc 2",
embedding=[0.2, 0.3, 0.4],
meta={"category": "news", "priority": 5, "status": "pending"},
),
Document(
id="c3",
content="doc 3",
embedding=[0.3, 0.4, 0.5],
meta={"category": "sports", "priority": 3, "status": "active"},
),
Document(
id="c4",
content="doc 4",
embedding=[0.9, 0.8, 0.7],
meta={"category": "sports", "priority": 8, "status": "inactive"},
),
]
document_store.write_documents(docs)
query_embedding = [0.1, 0.2, 0.3]
filters = {
"operator": "AND",
"conditions": [
{"field": "meta.category", "operator": "==", "value": "news"},
{
"operator": "OR",
"conditions": [
{"field": "meta.priority", "operator": ">", "value": 3},
{"field": "meta.status", "operator": "==", "value": "active"},
],
},
],
}
results = document_store._embedding_retrieval(query_embedding, filters, limit=10)
assert len(results) == 2
assert {doc.id for doc in results} == {"c1", "c2"}
# Results should be ordered by similarity
assert results[0].id == "c1" # Closest to query
def test_search_by_embedding_with_not_equal_filter(self, document_store):
docs = [
Document(id="ne1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"category": "news"}),
Document(id="ne2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"category": "sports"}),
Document(id="ne3", content="doc 3", embedding=[0.3, 0.4, 0.5], meta={"category": "spam"}),
]
document_store.write_documents(docs)
query_embedding = [0.1, 0.2, 0.3]
filters = {"operator": "AND", "conditions": [{"field": "meta.category", "operator": "!=", "value": "spam"}]}
results = document_store._embedding_retrieval(query_embedding, filters, limit=10)
assert len(results) == 2
assert {doc.id for doc in results} == {"ne1", "ne2"}
# Results should be ordered by similarity
assert results[0].id == "ne1" # Closest to query
def test_search_by_embedding_with_range_filter(self, document_store):
docs = [
Document(id="r1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"timestamp": 100, "priority": 1}),
Document(id="r2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"timestamp": 800, "priority": 5}),
Document(id="r3", content="doc 3", embedding=[0.3, 0.4, 0.5], meta={"timestamp": 900, "priority": 10}),
Document(id="r4", content="doc 4", embedding=[0.9, 0.8, 0.7], meta={"timestamp": 300, "priority": 2}),
]
document_store.write_documents(docs)
query_embedding = [0.1, 0.2, 0.3]
filters = {
"operator": "AND",
"conditions": [
{"field": "meta.timestamp", "operator": ">=", "value": 700},
{"field": "meta.priority", "operator": "<=", "value": 8},
],
}
results = document_store._embedding_retrieval(query_embedding, filters, limit=10)
assert len(results) == 1
assert {doc.id for doc in results} == {"r2"}
# Results should be ordered by similarity
assert results[0].id == "r2" # Only r2 matches: timestamp=800>=700 AND priority=5<=8
def test_search_by_embedding_no_filter_matches(self, document_store):
docs = [
Document(id="nm1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"category": "news"}),
Document(id="nm2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"category": "sports"}),
]
document_store.write_documents(docs)
query_embedding = [0.1, 0.2, 0.3]
filters = {
"operator": "AND",
"conditions": [{"field": "meta.category", "operator": "==", "value": "nonexistent"}],
}
results = document_store._embedding_retrieval(query_embedding, filters, limit=10)
assert len(results) == 0
def test_filter_documents_by_category(self, document_store):
docs = [
Document(id="f1", content="doc 1", meta={"category": "news", "priority": 1}),
Document(id="f2", content="doc 2", meta={"category": "sports", "priority": 2}),
Document(id="f3", content="doc 3", meta={"category": "news", "priority": 3}),
]
document_store.write_documents(docs)
filters = {"operator": "AND", "conditions": [{"field": "meta.category", "operator": "==", "value": "news"}]}
results = document_store.filter_documents(filters)
assert len(results) == 2
assert {doc.id for doc in results} == {"f1", "f3"}
def test_filter_documents_by_numeric_range(self, document_store):
docs = [
Document(id="n1", content="doc 1", meta={"priority": 1, "score": 0.8}),
Document(id="n2", content="doc 2", meta={"priority": 5, "score": 0.9}),
Document(id="n3", content="doc 3", meta={"priority": 10, "score": 0.7}),
]
document_store.write_documents(docs)
filters = {
"operator": "AND",
"conditions": [
{"field": "meta.priority", "operator": ">=", "value": 5},
{"field": "meta.score", "operator": ">=", "value": 0.8},
],
}
results = document_store.filter_documents(filters)
assert len(results) == 1
assert results[0].id == "n2"
def test_filter_documents_with_or_condition(self, document_store):
docs = [
Document(id="o1", content="doc 1", meta={"status": "active", "category": "news"}),
Document(id="o2", content="doc 2", meta={"status": "pending", "category": "sports"}),
Document(id="o3", content="doc 3", meta={"status": "inactive", "category": "news"}),
]
document_store.write_documents(docs)
filters = {
"operator": "OR",
"conditions": [
{"field": "meta.status", "operator": "==", "value": "active"},
{"field": "meta.category", "operator": "==", "value": "sports"},
],
}
results = document_store.filter_documents(filters)
assert len(results) == 2
assert {doc.id for doc in results} == {"o1", "o2"}
def test_filter_documents_with_in_operator(self, document_store):
docs = [
Document(id="i1", content="doc 1", meta={"status": "active"}),
Document(id="i2", content="doc 2", meta={"status": "pending"}),
Document(id="i3", content="doc 3", meta={"status": "inactive"}),
Document(id="i4", content="doc 4", meta={"status": "archived"}),
]
document_store.write_documents(docs)
filters = {
"operator": "AND",
"conditions": [{"field": "meta.status", "operator": "in", "value": ["active", "pending"]}],
}
results = document_store.filter_documents(filters)
assert len(results) == 2
assert {doc.id for doc in results} == {"i1", "i2"}
def test_filter_documents_with_not_equal(self, document_store):
docs = [
Document(id="ne1", content="doc 1", meta={"category": "news"}),
Document(id="ne2", content="doc 2", meta={"category": "sports"}),
Document(id="ne3", content="doc 3", meta={"category": "spam"}),
]
document_store.write_documents(docs)
filters = {"operator": "AND", "conditions": [{"field": "meta.category", "operator": "!=", "value": "spam"}]}
results = document_store.filter_documents(filters)
assert len(results) == 2
assert {doc.id for doc in results} == {"ne1", "ne2"}
def test_filter_documents_no_matches(self, document_store):
docs = [
Document(id="nm1", content="doc 1", meta={"category": "news"}),
Document(id="nm2", content="doc 2", meta={"category": "sports"}),
]
document_store.write_documents(docs)
filters = {
"operator": "AND",
"conditions": [{"field": "meta.category", "operator": "==", "value": "nonexistent"}],
}
results = document_store.filter_documents(filters)
assert len(results) == 0
def test_filter_documents_no_filters(self, document_store):
docs = [
Document(id="nf1", content="doc 1", meta={"category": "news"}),
Document(id="nf2", content="doc 2", meta={"category": "sports"}),
]
document_store.write_documents(docs)
results = document_store.filter_documents(None)
assert len(results) == 2
assert {doc.id for doc in results} == {"nf1", "nf2"}
def test_filter_documents_complex_nested(self, document_store):
docs = [
Document(id="c1", content="doc 1", meta={"category": "news", "priority": 1, "status": "active"}),
Document(id="c2", content="doc 2", meta={"category": "news", "priority": 5, "status": "pending"}),
Document(id="c3", content="doc 3", meta={"category": "sports", "priority": 3, "status": "active"}),
Document(id="c4", content="doc 4", meta={"category": "sports", "priority": 8, "status": "inactive"}),
]
document_store.write_documents(docs)
filters = {
"operator": "AND",
"conditions": [
{"field": "meta.category", "operator": "==", "value": "news"},
{
"operator": "OR",
"conditions": [
{"field": "meta.priority", "operator": ">", "value": 3},
{"field": "meta.status", "operator": "==", "value": "active"},
],
},
],
}
results = document_store.filter_documents(filters)
assert len(results) == 2
assert {doc.id for doc in results} == {"c1", "c2"}
def test_similarity_scores_are_set_correctly(self, document_store):
"""Test that similarity scores are properly computed and set for all returned documents."""
docs = [
Document(id="sim1", content="identical vector", embedding=[1.0, 0.0, 0.0]),
Document(id="sim2", content="similar vector", embedding=[0.9, 0.1, 0.0]),
Document(id="sim3", content="different vector", embedding=[0.0, 1.0, 0.0]),
Document(id="sim4", content="opposite vector", embedding=[-1.0, 0.0, 0.0]),
]
document_store.write_documents(docs)
# Search with query identical to first document
query_embedding = [1.0, 0.0, 0.0]
results = document_store._embedding_retrieval(query_embedding, limit=10)
# All documents should have similarity scores set
assert len(results) == 4
for doc in results:
assert doc.score is not None, f"Document {doc.id} has no similarity score"
assert isinstance(doc.score, float), f"Document {doc.id} score is not a float: {type(doc.score)}"
# Results should be ordered by similarity (highest first for cosine similarity)
assert results[0].id == "sim1" # Identical vector should have highest score
assert results[1].id == "sim2" # Similar vector should be second
# Verify scores are properly computed (not just dummy values)
scores = [doc.score for doc in results]
assert len(set(scores)) > 1, "All similarity scores are identical, suggesting they're not properly computed"
# Verify all results are sorted by similarity score (lower is better for distance metrics)
for i in range(len(results) - 1):
assert results[i].score <= results[i + 1].score, (
f"Results not sorted by score: {results[i].score} > {results[i + 1].score} at positions {i} and {i + 1}"
)
# The identical vector should have the lowest (best) similarity score
assert results[0].score <= results[1].score, (
f"Expected identical vector to have best score, got {results[0].score} vs {results[1].score}"
)
def test_filter_by_meta_score(self, document_store):
"""Test filtering by user-provided meta.score values."""
docs = [
Document(id="ms1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"score": 0.9, "category": "high"}),
Document(id="ms2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"score": 0.5, "category": "medium"}),
Document(id="ms3", content="doc 3", embedding=[0.3, 0.4, 0.5], meta={"score": 0.2, "category": "low"}),
Document(id="ms4", content="doc 4", embedding=[0.4, 0.5, 0.6], meta={"score": 0.8, "category": "high"}),
]
document_store.write_documents(docs)
# Filter by meta.score >= 0.7
filters = {"operator": "AND", "conditions": [{"field": "meta.score", "operator": ">=", "value": 0.7}]}
results = document_store.filter_documents(filters)
assert len(results) == 2
assert {doc.id for doc in results} == {"ms1", "ms4"}
# Verify meta.score values are preserved
for doc in results:
assert "score" in doc.meta
assert doc.meta["score"] >= 0.7
def test_search_with_meta_score_filter(self, document_store):
"""Test vector search combined with meta.score filtering."""
docs = [
Document(
id="sms1", content="doc 1", embedding=[1.0, 0.0, 0.0], meta={"score": 0.9, "quality": "excellent"}
),
Document(id="sms2", content="doc 2", embedding=[0.9, 0.1, 0.0], meta={"score": 0.3, "quality": "poor"}),
Document(id="sms3", content="doc 3", embedding=[0.8, 0.2, 0.0], meta={"score": 0.8, "quality": "good"}),
Document(
id="sms4", content="doc 4", embedding=[0.0, 1.0, 0.0], meta={"score": 0.95, "quality": "excellent"}
),
]
document_store.write_documents(docs)
# Search with query similar to first document, but filter by meta.score
query_embedding = [1.0, 0.0, 0.0]
filters = {"operator": "AND", "conditions": [{"field": "meta.score", "operator": ">=", "value": 0.7}]}
results = document_store._embedding_retrieval(query_embedding, filters, limit=10)
# Should return documents with meta.score >= 0.7, ordered by vector similarity
assert len(results) == 3
result_ids = [doc.id for doc in results]
assert set(result_ids) == {"sms1", "sms3", "sms4"}
# Verify ordering by vector similarity (sms1 should be first as it's most similar)
assert results[0].id == "sms1"
# Verify both similarity scores and meta scores are preserved
for doc in results:
assert doc.score is not None # Vector similarity score
assert "score" in doc.meta # User metadata score
assert doc.meta["score"] >= 0.7
def test_count_documents_by_filter(self, document_store):
"""Test counting documents that match a filter."""
docs = [
Document(id="cbf1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"category": "a", "priority": 1}),
Document(id="cbf2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"category": "b", "priority": 2}),
Document(id="cbf3", content="doc 3", embedding=[0.3, 0.4, 0.5], meta={"category": "a", "priority": 3}),
]
document_store.write_documents(docs)
filters_a = {"operator": "AND", "conditions": [{"field": "meta.category", "operator": "==", "value": "a"}]}
assert document_store.count_documents_by_filter(filters_a) == 2
filters_b = {"operator": "AND", "conditions": [{"field": "meta.category", "operator": "==", "value": "b"}]}
assert document_store.count_documents_by_filter(filters_b) == 1
filters_none = {"operator": "AND", "conditions": [{"field": "meta.category", "operator": "==", "value": "z"}]}
assert document_store.count_documents_by_filter(filters_none) == 0
def test_count_unique_metadata_by_filter(self, document_store):
"""Test counting unique values per metadata field for documents matching a filter."""
docs = [
Document(id="cumb1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"category": "tech", "priority": 1}),
Document(id="cumb2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"category": "tech", "priority": 2}),
Document(id="cumb3", content="doc 3", embedding=[0.3, 0.4, 0.5], meta={"category": "news", "priority": 2}),
]
document_store.write_documents(docs)
filters = {"operator": "AND", "conditions": [{"field": "meta.priority", "operator": ">=", "value": 1}]}
counts = document_store.count_unique_metadata_by_filter(filters, metadata_fields=["category", "priority"])
assert counts["category"] == 2
assert counts["priority"] == 2
def test_count_unique_metadata_by_filter_empty_result(self, document_store):
"""Test count_unique_metadata_by_filter when filter matches no documents."""
docs = [
Document(id="cumb_e1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"category": "x"}),
]
document_store.write_documents(docs)
filters = {"operator": "AND", "conditions": [{"field": "meta.category", "operator": "==", "value": "y"}]}
counts = document_store.count_unique_metadata_by_filter(filters, metadata_fields=["category"])
assert counts["category"] == 0
def test_get_metadata_fields_info(self, document_store):
"""Test get_metadata_fields_info returns configured field names and types."""
info = document_store.get_metadata_fields_info()
assert "category" in info
assert info["category"]["type"] == "keyword"
assert "priority" in info
assert info["priority"]["type"] == "long"
assert "status" in info
assert "score" in info
assert "timestamp" in info
assert "quality" in info
def test_get_metadata_field_min_max(self, document_store):
"""Test get_metadata_field_min_max for a numeric field."""
docs = [
Document(id="gmm1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"priority": 10, "category": "a"}),
Document(id="gmm2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"priority": 5, "category": "b"}),
Document(id="gmm3", content="doc 3", embedding=[0.3, 0.4, 0.5], meta={"priority": 20, "category": "c"}),
]
document_store.write_documents(docs)
result = document_store.get_metadata_field_min_max("priority")
assert result["min"] == 5
assert result["max"] == 20
def test_get_metadata_field_min_max_empty_store(self, document_store):
"""Test get_metadata_field_min_max when store has no documents."""
result = document_store.get_metadata_field_min_max("priority")
assert result["min"] is None
assert result["max"] is None
def test_get_metadata_field_min_max_non_numeric_raises(self, document_store):
"""Test get_metadata_field_min_max raises for tag (non-numeric) field."""
with pytest.raises(ValueError, match="not a numeric metadata field"):
document_store.get_metadata_field_min_max("category")
def test_get_metadata_field_min_max_unknown_field_raises(self, document_store):
"""Test get_metadata_field_min_max raises for unconfigured field."""
with pytest.raises(ValueError, match="not configured for filtering"):
document_store.get_metadata_field_min_max("unknown_field")
def test_get_metadata_field_unique_values(self, document_store):
"""Test get_metadata_field_unique_values returns distinct values and total count."""
docs = [
Document(id="gmv1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"category": "apple", "priority": 1}),
Document(id="gmv2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"category": "banana", "priority": 2}),
Document(id="gmv3", content="doc 3", embedding=[0.3, 0.4, 0.5], meta={"category": "apple", "priority": 3}),
]
document_store.write_documents(docs)
values, total = document_store.get_metadata_field_unique_values("category", from_=0, size=10)
assert total == 2
assert set(values) == {"apple", "banana"}
assert len(values) == 2
def test_get_metadata_field_unique_values_pagination(self, document_store):
"""Test get_metadata_field_unique_values with from_ and size."""
docs = [
Document(id=f"gmvp{i}", content=f"doc {i}", embedding=[0.1, 0.2, 0.3], meta={"category": f"cat_{i}"})
for i in range(5)
]
document_store.write_documents(docs)
values, total = document_store.get_metadata_field_unique_values("category", from_=1, size=2)
assert total == 5
assert len(values) == 2
assert sorted(values)[0] >= "cat_0"
def test_get_metadata_field_unique_values_with_search_term(self, document_store):
"""Test get_metadata_field_unique_values with search_term filter."""
docs = [
Document(id="gmvs1", content="doc 1", embedding=[0.1, 0.2, 0.3], meta={"category": "apple_pie"}),
Document(id="gmvs2", content="doc 2", embedding=[0.2, 0.3, 0.4], meta={"category": "banana"}),
Document(id="gmvs3", content="doc 3", embedding=[0.3, 0.4, 0.5], meta={"category": "apple_jam"}),
]
document_store.write_documents(docs)
values, total = document_store.get_metadata_field_unique_values(
"category", search_term="apple", from_=0, size=10
)
assert total == 2
assert set(values) == {"apple_pie", "apple_jam"}
def test_get_metadata_field_unique_values_unknown_field_raises(self, document_store):
"""Test get_metadata_field_unique_values raises for unconfigured field."""
with pytest.raises(ValueError, match="not configured for filtering"):
document_store.get_metadata_field_unique_values("unknown_field")
def test_count_unique_metadata_by_filter_invalid_field_raises(self, document_store):
"""Test count_unique_metadata_by_filter raises for unconfigured field."""
document_store.write_documents(
[Document(id="x", content="doc", embedding=[0.1, 0.2, 0.3], meta={"category": "a"})]
)
filters = {"operator": "AND", "conditions": [{"field": "meta.category", "operator": "==", "value": "a"}]}
with pytest.raises(ValueError, match="not configured for filtering"):
document_store.count_unique_metadata_by_filter(filters, metadata_fields=["unknown_field"])
class TestValkeyDocumentStoreStaticMethods:
"""Test static methods that were refactored from instance methods."""
def test_parse_metric_valid_metrics(self):
"""Test _parse_metric static method with valid metrics."""
assert ValkeyDocumentStore._parse_metric("l2") == DistanceMetricType.L2
assert ValkeyDocumentStore._parse_metric("cosine") == DistanceMetricType.COSINE
assert ValkeyDocumentStore._parse_metric("ip") == DistanceMetricType.IP
def test_parse_metric_invalid_metric(self):
"""Test _parse_metric static method with invalid metric."""
with pytest.raises(ValueError, match="Unsupported metric: invalid"):
ValkeyDocumentStore._parse_metric("invalid")
def test_to_float32_bytes(self):
"""Test _to_float32_bytes static method."""
vec = [1.0, 2.5, -3.7]
result = ValkeyDocumentStore._to_float32_bytes(vec)
# Verify it's bytes
assert isinstance(result, bytes)
# Verify correct length (4 bytes per float)
assert len(result) == len(vec) * 4
# Verify correct values by unpacking
unpacked = [struct.unpack("<f", result[i : i + 4])[0] for i in range(0, len(result), 4)]
assert unpacked == pytest.approx(vec, rel=1e-6)
def test_verify_node_list_valid(self):
"""Test _verify_node_list static method with valid node list."""
# Should not raise any exception
ValkeyDocumentStore._verify_node_list([("localhost", 6379)])
ValkeyDocumentStore._verify_node_list([("host1", 6379), ("host2", 6380)])
def test_verify_node_list_empty(self):
"""Test _verify_node_list static method with empty node list."""
with pytest.raises(Exception, match="Node list is empty"):
ValkeyDocumentStore._verify_node_list([])
with pytest.raises(Exception, match="Node list is empty"):
ValkeyDocumentStore._verify_node_list(None)
def test_build_credentials_with_username_and_password(self):
"""Test _build_credentials static method with both username and password."""
creds = ValkeyDocumentStore._build_credentials(Secret.from_token("user"), Secret.from_token("pass"))
assert creds is not None
assert creds.username == "user"
assert creds.password == "pass"
def test_build_credentials_with_username_only(self):
"""Test _build_credentials static method with username only."""
# ServerCredentials requires password, so username-only should return None
creds = ValkeyDocumentStore._build_credentials(Secret.from_token("user"), None)
assert creds is None
def test_build_credentials_with_password_only(self):
"""Test _build_credentials static method with password only."""
creds = ValkeyDocumentStore._build_credentials(None, Secret.from_token("pass"))
assert creds is not None
# Username should default to None (ServerCredentials will use "default")
assert creds.password == "pass"
def test_build_credentials_with_neither(self):
"""Test _build_credentials static method with neither username nor password."""
creds = ValkeyDocumentStore._build_credentials(None, None)
assert creds is None
def test_validate_documents_valid(self):
"""Test _validate_documents static method with valid documents."""
docs = [
Document(id="1", content="test"),
Document(id="2", content="test2"),
]
# Should not raise any exception
ValkeyDocumentStore._validate_documents(docs)
def test_validate_documents_invalid_type(self):
"""Test _validate_documents static method with invalid document type."""
with pytest.raises(ValueError, match="expects a list of Documents"):
ValkeyDocumentStore._validate_documents([Document(id="1", content="test"), "not_a_document"])
def test_validate_policy_valid(self):
"""Test _validate_policy static method with valid policies."""
# Should not raise any exception, but may log warnings
ValkeyDocumentStore._validate_policy(DuplicatePolicy.NONE)
ValkeyDocumentStore._validate_policy(DuplicatePolicy.OVERWRITE)
def test_build_search_query_and_options_basic(self):
"""Test _build_search_query_and_options static method with basic parameters."""
embedding = [0.1, 0.2, 0.3]
filters = None
limit = 10
with_embedding = True
supported_fields = {"meta_category": "tag", "meta_priority": "numeric"}
query, options = ValkeyDocumentStore._build_search_query_and_options(
embedding, filters, limit, with_embedding=with_embedding, supported_fields=supported_fields
)
assert isinstance(query, str)
assert isinstance(options, FtSearchOptions)
assert "KNN 10" in query
assert "query_vector" in query
assert "query_vector" in options.params
def test_build_search_query_and_options_with_filters(self):
"""Test _build_search_query_and_options static method with filters."""
embedding = [0.1, 0.2, 0.3]
filters = {"operator": "AND", "conditions": [{"field": "meta.category", "operator": "==", "value": "news"}]}
limit = 5
with_embedding = False
supported_fields = {"meta_category": "tag", "meta_priority": "numeric"}
query, options = ValkeyDocumentStore._build_search_query_and_options(
embedding, filters, limit, with_embedding=with_embedding, supported_fields=supported_fields
)
assert "meta_category:{news}" in query
assert "KNN 5" in query
# Should not include vector field when with_embedding=False
vector_fields = [
field for field in options.return_fields if hasattr(field, "alias") and field.alias == "vector"
]
assert len(vector_fields) == 0
def test_build_search_query_and_options_with_embedding_return(self):
"""Test _build_search_query_and_options static method with embedding return."""
embedding = [0.1, 0.2, 0.3]
filters = None
limit = 10
supported_fields = {"meta_category": "tag", "meta_priority": "numeric"}
_, options = ValkeyDocumentStore._build_search_query_and_options(
embedding, filters, limit, with_embedding=True, supported_fields=supported_fields
)
# Should have vector field when with_embedding=True
vector_fields = [
field for field in options.return_fields if hasattr(field, "alias") and field.alias == "vector"
]
assert len(vector_fields) == 1, "Should have exactly one vector field when with_embedding=True"
# Should have more return fields when with_embedding=True vs False
_, options_no_embed = ValkeyDocumentStore._build_search_query_and_options(
embedding, filters, limit, with_embedding=False, supported_fields=supported_fields
)
vector_fields = [
field for field in options_no_embed.return_fields if hasattr(field, "alias") and field.alias == "vector"
]
assert len(vector_fields) == 0, "Should have no vector field with_embedding=False"
def test_parse_documents_from_ft_empty_results(self):
"""Test _parse_documents_from_ft static method with empty results."""
raw_results = [0, {}] # Empty results format
with_embedding = True
docs = ValkeyDocumentStore._parse_documents_from_ft(raw_results, with_embedding=with_embedding)
assert docs == []
def test_parse_documents_from_ft_no_results(self):
"""Test _parse_documents_from_ft static method with no results."""
raw_results = None
with_embedding = True
docs = ValkeyDocumentStore._parse_documents_from_ft(raw_results, with_embedding=with_embedding)
assert docs == []
def test_parse_documents_from_ft_with_embeddings(self):
"""Test _parse_documents_from_ft correctly parses embeddings when with_embedding=True."""
raw_results = [
2,
{
b"doc:1": {
b"payload": b'{"id": "1", "content": "test doc 1"}',
b"vector": b"[0.1, 0.2, 0.3]",
b"__vector_score": b"0.95",
},
b"doc:2": {
b"payload": b'{"id": "2", "content": "test doc 2"}',
b"vector": b"[0.4, 0.5, 0.6]",
b"__vector_score": b"0.85",
},
},
]
docs = ValkeyDocumentStore._parse_documents_from_ft(raw_results, with_embedding=True)
assert len(docs) == 2
assert docs[0].id == "1"
assert docs[0].content == "test doc 1"
assert docs[0].embedding == [0.1, 0.2, 0.3]
assert docs[0].score == 0.95
assert docs[1].id == "2"
assert docs[1].embedding == [0.4, 0.5, 0.6]
assert docs[1].score == 0.85
def test_parse_documents_from_ft_without_embeddings(self):
"""Test _parse_documents_from_ft excludes embeddings when with_embedding=False."""
raw_results = [
2,
{
b"doc:1": {
b"payload": b'{"id": "1", "content": "test doc 1"}',
b"vector": b"[0.1, 0.2, 0.3]",
b"__vector_score": b"0.95",
},
b"doc:2": {
b"payload": b'{"id": "2", "content": "test doc 2"}',
b"vector": b"[0.4, 0.5, 0.6]",
b"__vector_score": b"0.85",
},
},
]