-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathtest_distributed_indexing.py
More file actions
executable file
·1860 lines (1603 loc) · 65.4 KB
/
Copy pathtest_distributed_indexing.py
File metadata and controls
executable file
·1860 lines (1603 loc) · 65.4 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
"""Test cases for lance_ray.indexing module."""
import random
import tempfile
from pathlib import Path
import lance
import lance_ray as lr
import numpy as np
import pyarrow as pa
import pytest
import ray
from lance_ray.search import _scanner_accepts_index_segments
from packaging import version
import pandas as pd
def check_lance_version_compatibility():
"""Check if lance version supports distributed indexing."""
try:
lance_version = version.parse(lance.__version__)
min_required_version = version.parse("0.36.0")
return lance_version >= min_required_version
except (AttributeError, Exception):
return False
# Skip all distributed indexing tests if lance version is incompatible
pytestmark = pytest.mark.skipif(
not check_lance_version_compatibility(),
reason="Distributed indexing requires pylance >= 0.36.0. Current version: {}".format(
getattr(lance, "__version__", "unknown")
),
)
@pytest.fixture
def text_data():
"""Create sample text data for indexing tests."""
return pd.DataFrame(
{
"id": [1, 2, 3, 4, 5, 6, 7, 8],
"text": [
"The quick brown fox jumps over the lazy dog",
"Python is a powerful programming language",
"Machine learning algorithms are fascinating",
"Data science requires statistical knowledge",
"Natural language processing uses text analysis",
"Distributed computing scales horizontally",
"Ray framework enables parallel processing",
"Lance format provides efficient storage",
],
"category": [
"animals",
"tech",
"ml",
"data",
"nlp",
"distributed",
"ray",
"storage",
],
}
)
@pytest.fixture
def temp_dir():
"""Create a temporary directory for testing."""
with tempfile.TemporaryDirectory() as temp_dir:
yield temp_dir
@pytest.fixture
def text_dataset(text_data):
"""Create a Ray Dataset from text data."""
return ray.data.from_pandas(text_data)
@pytest.fixture
def multi_fragment_lance_dataset(text_dataset, temp_dir):
"""Create a Lance dataset with multiple fragments for testing."""
path = Path(temp_dir) / "multi_fragment_text.lance"
# Create dataset with multiple fragments (2 rows per fragment)
lr.write_lance(text_dataset, str(path), min_rows_per_file=2, max_rows_per_file=2)
return str(path)
def generate_multi_fragment_dataset(tmp_path, num_fragments=4, rows_per_fragment=250):
"""Generate a test dataset with multiple fragments."""
all_data = []
for frag_idx in range(num_fragments):
for row_idx in range(rows_per_fragment):
row_id = frag_idx * rows_per_fragment + row_idx
all_data.append(
{
"id": row_id,
"text": f"This is test document {row_id} with some sample text content for fragment {frag_idx}",
"fragment_id": frag_idx,
}
)
df = pd.DataFrame(all_data)
dataset = ray.data.from_pandas(df)
path = Path(tmp_path) / "large_multi_fragment.lance"
lr.write_lance(
dataset,
str(path),
min_rows_per_file=rows_per_fragment,
max_rows_per_file=rows_per_fragment,
)
return lance.dataset(str(path))
def generate_mixed_schema_dataset(
tmp_path,
num_rows: int = 200,
vector_dim: int = 8,
rows_per_fragment: int = 50,
):
"""Generate a Lance dataset with both scalar and vector columns.
Schema: id (int64), vector (fixed-size list float32), label (int64), score (float64).
Used to test creating a scalar index on a dataset that also has a vector column.
"""
ids = pa.array(range(num_rows), type=pa.int64())
vectors = np.random.randn(num_rows, vector_dim).astype(np.float32)
vector_values = pa.array(vectors.ravel(), type=pa.float32())
vector_array = pa.FixedSizeListArray.from_arrays(vector_values, vector_dim)
labels = pa.array(
np.random.randint(0, 10, size=num_rows),
type=pa.int64(),
)
scores = pa.array(
np.random.uniform(0, 100, size=num_rows),
type=pa.float64(),
)
tbl = pa.table(
{
"id": ids,
"vector": vector_array,
"label": labels,
"score": scores,
}
)
dataset = ray.data.from_arrow(tbl)
path = Path(tmp_path) / "mixed_schema.lance"
lr.write_lance(
dataset,
str(path),
min_rows_per_file=rows_per_fragment,
max_rows_per_file=rows_per_fragment,
)
return str(path)
def generate_nested_contract_dataset(tmp_path, rows_per_fragment: int = 2):
"""Generate a multi-fragment dataset with nested field-path edge cases."""
schema = pa.schema(
[
pa.field("id", pa.int64()),
pa.field(
"meta",
pa.struct(
[
pa.field("text", pa.string()),
pa.field("a.b", pa.string()),
]
),
),
pa.field(
"meta-data",
pa.struct([pa.field("user-id", pa.int64())]),
),
pa.field("outer", pa.struct([pa.field("leaf", pa.int64())])),
pa.field("other", pa.struct([pa.field("leaf", pa.int64())])),
]
)
table = pa.Table.from_arrays(
[
pa.array([1, 2, 3, 4], type=pa.int64()),
pa.array(
[
{"text": "nestedone", "a.b": "literalone"},
{"text": "nestedtwo", "a.b": "literaltwo"},
{"text": "nestedthree", "a.b": "literalthree"},
{"text": "nestedfour", "a.b": "literalfour"},
],
type=schema.field("meta").type,
),
pa.array(
[
{"user-id": 101},
{"user-id": 102},
{"user-id": 103},
{"user-id": 104},
],
type=schema.field("meta-data").type,
),
pa.array(
[{"leaf": 10}, {"leaf": 20}, {"leaf": 30}, {"leaf": 40}],
type=schema.field("outer").type,
),
pa.array(
[{"leaf": 40}, {"leaf": 30}, {"leaf": 20}, {"leaf": 10}],
type=schema.field("other").type,
),
],
schema=schema,
)
path = Path(tmp_path) / "nested_contract.lance"
lr.write_lance(
ray.data.from_arrow(table),
str(path),
min_rows_per_file=rows_per_fragment,
max_rows_per_file=rows_per_fragment,
)
return str(path)
class TestDistributedIndexing:
"""Test cases for distributed indexing functionality."""
def test_build_distributed_fts_index_basic(self, multi_fragment_lance_dataset):
"""Test basic distributed FTS index building."""
dataset_uri = multi_fragment_lance_dataset
# Build distributed index
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
num_workers=2,
)
# Verify the index was created
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after building"
# Find our index
text_index = None
for idx in indices:
if "text" in idx.name:
text_index = idx
break
assert text_index is not None, "Text index not found"
assert text_index.index_type == "Inverted", (
f"Expected Inverted index, got {text_index.index_type}"
)
def test_build_distributed_fts_index_with_name(self, multi_fragment_lance_dataset):
"""Test building distributed index with custom name."""
dataset_uri = multi_fragment_lance_dataset
custom_name = "custom_text_index"
# Build distributed index with custom name
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
name=custom_name,
num_workers=2,
)
# Verify the index was created with correct name
indices = updated_dataset.describe_indices()
index_names = [idx.name for idx in indices]
assert custom_name in index_names, (
f"Custom index name '{custom_name}' not found in {index_names}"
)
def test_build_distributed_fts_index_search_functionality(
self, multi_fragment_lance_dataset
):
"""Test that the built index actually works for searching."""
dataset_uri = multi_fragment_lance_dataset
# Build distributed index
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
num_workers=2,
)
# Test full-text search functionality
search_term = "Python"
results = updated_dataset.scanner(
full_text_query=search_term,
columns=["id", "text"],
).to_table()
# Should find at least one result containing "Python"
assert results.num_rows > 0, f"No results found for search term '{search_term}'"
# Verify results contain the search term
text_results = results.column("text").to_pylist()
assert any(search_term in text for text in text_results), (
"Search results don't contain the search term"
)
def test_build_distributed_fts_index_fts_type(self, multi_fragment_lance_dataset):
"""Test building distributed FTS index."""
dataset_uri = multi_fragment_lance_dataset
# Build distributed FTS index
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
num_workers=2,
)
# Verify the index was created
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after building"
def test_build_distributed_fts_index_list_large_utf8(self, temp_dir):
"""Test distributed FTS index building on list<large_utf8> columns."""
search_term = "needlelarge"
table = pa.table(
{
"id": pa.array([1, 2, 3, 4], type=pa.int64()),
"tags": pa.array(
[
["alpha", "beta"],
["distributed", search_term],
["search", "fts"],
["other", "tokens"],
],
type=pa.list_(pa.large_string()),
),
}
)
dataset = ray.data.from_arrow(table)
path = Path(temp_dir) / "list_large_utf8_text.lance"
lr.write_lance(dataset, str(path), min_rows_per_file=2, max_rows_per_file=2)
updated_dataset = lr.create_scalar_index(
uri=str(path),
column="tags",
index_type="INVERTED",
num_workers=2,
)
results = updated_dataset.scanner(
full_text_query=search_term,
columns=["id", "tags"],
).to_table()
assert results.num_rows == 1
assert results.column("id").to_pylist() == [2]
def test_build_distributed_index_large_dataset(self, temp_dir):
"""Test distributed indexing on a larger dataset with multiple fragments."""
# Generate larger dataset
dataset = generate_multi_fragment_dataset(
temp_dir, num_fragments=4, rows_per_fragment=50
)
# Build distributed index
updated_dataset = lr.create_scalar_index(
uri=dataset.uri,
column="text",
index_type="INVERTED",
num_workers=4,
)
# Verify the index was created
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after building"
# Test search functionality
search_term = "test"
results = updated_dataset.scanner(
full_text_query=search_term,
columns=["id", "text"],
).to_table()
assert results.num_rows > 0, f"No results found for search term '{search_term}'"
def test_build_distributed_index_invalid_column(self, multi_fragment_lance_dataset):
"""Test error handling for invalid column."""
dataset_uri = multi_fragment_lance_dataset
with pytest.raises(ValueError, match="Column 'nonexistent' not found"):
lr.create_scalar_index(
uri=dataset_uri,
column="nonexistent",
index_type="INVERTED",
num_workers=2,
)
def test_build_distributed_index_invalid_index_type(
self, multi_fragment_lance_dataset
):
"""Test error handling for invalid index type."""
dataset_uri = multi_fragment_lance_dataset
with pytest.raises(
ValueError,
match="Distributed indexing does not support index type 'INVALID'",
):
lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVALID",
num_workers=2,
)
def test_build_distributed_index_invalid_num_workers(
self, multi_fragment_lance_dataset
):
"""Test error handling for invalid num_workers."""
dataset_uri = multi_fragment_lance_dataset
with pytest.raises(ValueError, match="num_workers must be positive"):
lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
num_workers=0,
)
def test_build_distributed_index_empty_column(self, multi_fragment_lance_dataset):
"""Test error handling for empty column name."""
dataset_uri = multi_fragment_lance_dataset
with pytest.raises(ValueError, match="Column name cannot be empty"):
lr.create_scalar_index(
uri=dataset_uri,
column="",
index_type="INVERTED",
num_workers=2,
)
def test_build_distributed_index_non_string_column(self, temp_dir):
"""Test error handling for non-string column."""
# Create dataset with non-string column
data = pd.DataFrame(
{
"id": [1, 2, 3, 4],
"numeric_col": [10, 20, 30, 40],
"text": ["text1", "text2", "text3", "text4"],
}
)
dataset = ray.data.from_pandas(data)
path = Path(temp_dir) / "non_string_test.lance"
lr.write_lance(dataset, str(path), min_rows_per_file=2, max_rows_per_file=2)
with pytest.raises(
TypeError,
match="must be string, large string, list of strings, or json",
):
lr.create_scalar_index(
uri=str(path),
column="numeric_col",
index_type="INVERTED",
num_workers=2,
)
def test_build_distributed_index_with_ray_remote_args(
self, multi_fragment_lance_dataset
):
"""Test building distributed index with Ray options."""
dataset_uri = multi_fragment_lance_dataset
# Build distributed index with Ray options
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
num_workers=2,
ray_remote_args={"num_cpus": 1},
)
# Verify the index was created
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after building"
def test_build_distributed_index_with_storage_options(
self, multi_fragment_lance_dataset
):
"""Test building distributed index with storage options."""
dataset_uri = multi_fragment_lance_dataset
# Build distributed index with storage options
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
num_workers=2,
storage_options={}, # Empty storage options should work
)
# Verify the index was created
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after building"
def test_build_distributed_index_with_kwargs(self, multi_fragment_lance_dataset):
"""Test building distributed index with additional kwargs."""
dataset_uri = multi_fragment_lance_dataset
# Build distributed index with additional kwargs
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
num_workers=2,
remove_stop_words=False, # Additional kwarg for create_scalar_index
)
# Verify the index was created
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after building"
def test_build_distributed_index_dataset_object(self, multi_fragment_lance_dataset):
"""Test building distributed index with Lance dataset object instead of URI."""
dataset = lance.dataset(multi_fragment_lance_dataset)
# Build distributed index using dataset object
updated_dataset = lr.create_scalar_index(
uri=dataset.uri,
column="text",
index_type="INVERTED",
num_workers=2,
)
# Verify the index was created
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after building"
def test_build_distributed_nested_scalar_indexes(self, temp_dir):
"""Nested field paths should pass driver validation and reach workers."""
dataset_uri = generate_nested_contract_dataset(temp_dir)
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="`meta`.`text`",
index_type="INVERTED",
name="nested_text_idx",
num_workers=2,
)
updated_dataset = lr.create_scalar_index(
uri=updated_dataset.uri,
column="meta.`a.b`",
index_type="INVERTED",
name="literal_dot_text_idx",
num_workers=2,
)
updated_dataset = lr.create_scalar_index(
uri=updated_dataset.uri,
column="`meta-data`.`user-id`",
index_type="BTREE",
name="hyphen_user_id_idx",
num_workers=2,
)
indices = {idx.name: idx for idx in updated_dataset.describe_indices()}
assert indices["nested_text_idx"].field_names == ["meta.text"]
assert indices["literal_dot_text_idx"].field_names == ["meta.`a.b`"]
assert indices["hyphen_user_id_idx"].field_names == ["`meta-data`.`user-id`"]
nested_results = updated_dataset.scanner(
full_text_query="nestedthree",
columns=["id", "meta.text"],
).to_table()
literal_dot_results = updated_dataset.scanner(
full_text_query="literaltwo",
columns=["id", "meta.`a.b`"],
).to_table()
assert nested_results.column("id").to_pylist() == [3]
assert literal_dot_results.column("id").to_pylist() == [2]
def test_build_distributed_nested_same_leaf_scalar_indexes(self, temp_dir):
"""Same leaf names must resolve through their full nested paths."""
dataset_uri = generate_nested_contract_dataset(temp_dir)
with pytest.raises(ValueError, match="Column 'leaf' not found"):
lr.create_scalar_index(
uri=dataset_uri,
column="leaf",
index_type="BTREE",
name="ambiguous_leaf_idx",
num_workers=2,
)
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="outer.leaf",
index_type="BTREE",
name="outer_leaf_idx",
num_workers=2,
)
updated_dataset = lr.create_scalar_index(
uri=updated_dataset.uri,
column="other.leaf",
index_type="BTREE",
name="other_leaf_idx",
num_workers=2,
)
indices = {idx.name: idx for idx in updated_dataset.describe_indices()}
assert indices["outer_leaf_idx"].field_names == ["outer.leaf"]
assert indices["other_leaf_idx"].field_names == ["other.leaf"]
outer_results = updated_dataset.scanner(
filter="outer.leaf = 20",
columns=["id", "outer.leaf"],
).to_table()
other_results = updated_dataset.scanner(
filter="other.leaf = 20",
columns=["id", "other.leaf"],
).to_table()
assert outer_results.column("id").to_pylist() == [2]
assert other_results.column("id").to_pylist() == [3]
def test_scalar_index_on_mixed_schema_describe_indices(self, temp_dir):
"""Create scalar index on schema with both scalar and vector columns; verify describe_indices."""
dataset_uri = generate_mixed_schema_dataset(
temp_dir,
num_rows=200,
vector_dim=8,
rows_per_fragment=50,
)
index_name = "label_btree_idx"
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="label",
index_type="BTREE",
name=index_name,
num_workers=2,
)
indices = updated_dataset.describe_indices()
assert len(indices) >= 1, (
"describe_indices should return at least the new scalar index"
)
names = [idx.name for idx in indices]
assert index_name in names, (
f"Expected index name {index_name!r} in describe_indices: {names}"
)
label_index = next(idx for idx in indices if idx.name == index_name)
assert label_index.index_type == "BTree", (
f"Expected BTree type for scalar index, got {label_index.index_type!r}"
)
# Schema should still have both scalar and vector columns
schema = updated_dataset.schema
assert schema.field("id") is not None
assert schema.field("vector") is not None
assert schema.field("label") is not None
assert schema.field("score") is not None
def test_build_distributed_index_replace_false_existing_index(
self, multi_fragment_lance_dataset
):
"""Test that replace=False raises error when trying to create index with existing name."""
dataset_uri = multi_fragment_lance_dataset
index_name = "test_replace_false_index"
# First, create an index
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
name=index_name,
num_workers=2,
)
# Verify the index was created
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "Initial index creation failed"
# Now try to create another index with the same name but replace=False
# The error might be raised as RuntimeError during distributed processing
with pytest.raises((ValueError, RuntimeError)) as exc_info:
lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
name=index_name,
replace=False,
num_workers=2,
)
# Verify the error message contains information about existing index
error_msg = str(exc_info.value)
assert "already exists" in error_msg and index_name in error_msg
def test_build_distributed_index_replace_true_overwrite_existing(
self, multi_fragment_lance_dataset
):
"""Test that replace=True successfully overwrites existing index."""
dataset_uri = multi_fragment_lance_dataset
index_name = "test_replace_true_index"
# First, create an index
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
name=index_name,
num_workers=2,
)
# Verify the index was created
initial_indices = updated_dataset.describe_indices()
assert len(initial_indices) > 0, "Initial index creation failed"
# Find our initial index
initial_index = None
for idx in initial_indices:
if idx.name == index_name:
initial_index = idx
break
assert initial_index is not None, "Initial index not found"
# Now create another index with the same name but replace=True
updated_dataset = lr.create_scalar_index(
uri=dataset_uri,
column="text",
index_type="INVERTED",
name=index_name,
replace=True,
num_workers=2,
)
# Verify the index still exists (should have been replaced)
final_indices = updated_dataset.describe_indices()
final_index = None
for idx in final_indices:
if idx.name == index_name:
final_index = idx
break
assert final_index is not None, "Index should still exist after replacement"
assert final_index.index_type == "Inverted", "Index type should remain Inverted"
# Test that the replaced index still works for searching
search_term = "Python"
results = updated_dataset.scanner(
full_text_query=search_term,
columns=["id", "text"],
).to_table()
assert results.num_rows > 0, (
f"No results found for search term '{search_term}' after index replacement"
)
def test_failed_replace_keeps_existing_index(
self, multi_fragment_lance_dataset, monkeypatch
):
"""A failed replacement must not remove the previously committed index."""
index_name = "test_replace_failure_keeps_existing_index"
lr.create_scalar_index(
uri=multi_fragment_lance_dataset,
column="text",
index_type="INVERTED",
name=index_name,
num_workers=2,
)
monkeypatch.setattr(
"lance_ray.index._map_async_with_pool",
lambda **_: [
{
"status": "error",
"fragment_ids": [0],
"error": "injected worker failure",
}
],
)
with pytest.raises(RuntimeError, match="injected worker failure"):
lr.create_scalar_index(
uri=multi_fragment_lance_dataset,
column="text",
index_type="INVERTED",
name=index_name,
replace=True,
num_workers=2,
)
indices = lance.dataset(multi_fragment_lance_dataset).describe_indices()
assert index_name in [index.name for index in indices]
def test_build_distributed_index_auto_adjust_workers(self, temp_dir):
"""Test that num_workers is automatically adjusted if it exceeds fragment count."""
# Create dataset with only 2 fragments
data = pd.DataFrame(
{
"id": [1, 2, 3, 4],
"text": ["text1", "text2", "text3", "text4"],
}
)
dataset = ray.data.from_pandas(data)
path = Path(temp_dir) / "small_dataset.lance"
lr.write_lance(dataset, str(path), min_rows_per_file=2, max_rows_per_file=2)
# Request more workers than fragments
updated_dataset = lr.create_scalar_index(
uri=str(path),
column="text",
index_type="INVERTED",
num_workers=10, # More than the 2 fragments
)
# Should still work and create the index
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after building"
def test_distributed_fts_index_new_api(self, temp_dir):
"""
Test distributed FTS index building with the segment workflow.
"""
# Generate test dataset with multiple fragments
ds = generate_multi_fragment_dataset(
temp_dir, num_fragments=4, rows_per_fragment=250
)
# Test with the new distributed index building function
updated_dataset = lr.create_scalar_index(
uri=ds.uri,
column="text",
index_type="INVERTED",
name="new_api_test_idx",
num_workers=2,
num_segments=4,
remove_stop_words=False,
)
# Verify the index was created
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after distributed index creation"
# Find our index
our_index = None
for idx in indices:
if idx.name == "new_api_test_idx":
our_index = idx
break
assert our_index is not None, (
"Index 'new_api_test_idx' not found in indices list"
)
assert our_index.index_type == "Inverted", (
f"Expected Inverted index, got {our_index.index_type}"
)
assert len(our_index.segments) == 4
# Test that the index works for searching
sample_data = updated_dataset.take([0], columns=["text"])
sample_text = sample_data.column(0)[0].as_py()
search_word = sample_text.split()[0] if sample_text.split() else "test"
# Perform a full-text search to verify the index works
results = updated_dataset.scanner(
full_text_query=search_word,
columns=["id", "text"],
).to_table()
print(f"Search for '{search_word}' returned {results.num_rows} results")
assert results.num_rows > 0, f"No results found for search term '{search_word}'"
def test_distributed_index_with_index_uuid(self, temp_dir):
"""
Test distributed FTS index creation records the requested index name.
"""
# Generate test dataset
ds = generate_multi_fragment_dataset(
temp_dir, num_fragments=3, rows_per_fragment=100
)
# Test with explicit fragment UUID handling
updated_dataset = lr.create_scalar_index(
uri=ds.uri,
column="text",
index_type="INVERTED",
name="index_uuid_test_idx",
num_workers=2,
)
# Verify the index was created
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after index creation"
# Find our index
our_index = None
for idx in indices:
if idx.name == "index_uuid_test_idx":
our_index = idx
break
assert our_index is not None, "Index 'index_uuid_test_idx' not found"
assert our_index.index_type == "Inverted", (
f"Expected Inverted index, got {our_index.index_type}"
)
def test_distributed_index_error_handling_new_api(self, temp_dir):
"""
Test error handling in the distributed indexing API.
"""
# Generate test dataset
ds = generate_multi_fragment_dataset(
temp_dir, num_fragments=2, rows_per_fragment=50
)
# Test with invalid parameters that should be caught by the new API
with pytest.raises(ValueError, match="Column name cannot be empty"):
lr.create_scalar_index(
uri=ds.uri,
column="",
index_type="INVERTED",
num_workers=2,
)
# Test with invalid index type
with pytest.raises(
ValueError,
match="Distributed indexing does not support index type 'INVALID_TYPE'",
):
lr.create_scalar_index(
uri=ds.uri,
column="text",
index_type="INVALID_TYPE",
num_workers=2,
)
def check_btree_version_compatibility():
"""Check if lance version supports distributed B-tree indexing (>= 0.37.0)."""
try:
lance_version = version.parse(lance.__version__)
btree_min_version = version.parse("0.37.0")
return lance_version >= btree_min_version
except (AttributeError, Exception):
return False
@pytest.mark.skipif(
not check_btree_version_compatibility(),
reason="B-tree indexing requires pylance >= 0.37.0. Current version: {}".format(
getattr(lance, "__version__", "unknown")
),
)
class TestDistributedBTreeIndexing:
"""Distributed BTREE indexing tests using the unified lr.create_scalar_index entrypoint."""
def test_distributed_btree_index_basic(self, temp_dir):
"""Build a distributed BTREE index and verify search works and type is BTree."""
ds = generate_multi_fragment_dataset(
temp_dir, num_fragments=3, rows_per_fragment=500
)
updated_dataset = lr.create_scalar_index(
uri=ds.uri,
column="id",
index_type="BTREE",
name="btree_multiple_fragment_idx",
replace=False,
num_workers=3,
)
# Verify index
indices = updated_dataset.describe_indices()
assert len(indices) > 0, "No indices found after distributed BTREE build"
our_index = None
for idx in indices:
if idx.name == "btree_multiple_fragment_idx":
our_index = idx
break
assert our_index is not None, "BTREE index not found by name"
assert our_index.index_type == "BTree", (
f"Expected BTree index, got {our_index.index_type}"
)
# Spot-check equality and range queries
eq_id = 100
eq_tbl = updated_dataset.scanner(
filter=f"id = {eq_id}", columns=["id", "text"]
).to_table()
assert eq_tbl.num_rows == 1
eq_plan = updated_dataset.scanner(
filter=f"id = {eq_id}",
columns=["id"],
use_scalar_index=True,
).explain_plan()
assert "ScalarIndexQuery" in eq_plan