-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathindex.py
More file actions
executable file
·1562 lines (1328 loc) · 53.6 KB
/
Copy pathindex.py
File metadata and controls
executable file
·1562 lines (1328 loc) · 53.6 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-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The Lance Authors
import logging
import math
import uuid
from collections.abc import Callable
from typing import Any, Literal, Optional, TypeAlias, Union
import lance
import pyarrow as pa
import ray
from lance.dataset import Index, IndexConfig, LanceDataset
from lance.indices import IndicesBuilder
from packaging import version
from ray.util.multiprocessing import Pool
from .field_path import resolve_arrow_field_path, resolve_dataset_field_path
from .utils import (
get_namespace_kwargs,
has_namespace_params,
resolve_namespace_table,
validate_uri_or_namespace,
)
logger = logging.getLogger(__name__)
_VectorIndexArtifact: TypeAlias = (
pa.Array | pa.FixedSizeListArray | pa.FixedShapeTensorArray | None
)
_VectorIndexArtifactRef: TypeAlias = _VectorIndexArtifact | ray.ObjectRef
_VectorIndexArtifactRefs: TypeAlias = tuple[
_VectorIndexArtifactRef, _VectorIndexArtifactRef
]
def _dataset_load_kwargs(
storage_options: Optional[dict[str, Any]],
namespace_kwargs: dict[str, Any],
block_size: Optional[int],
) -> dict[str, Any]:
kwargs: dict[str, Any] = {
"storage_options": storage_options,
**namespace_kwargs,
}
if block_size is not None:
kwargs["block_size"] = block_size
return kwargs
def _index_exists(dataset: LanceDataset, name: str) -> bool:
return any(index.name == name for index in dataset.describe_indices())
def _distribute_fragments_balanced(
fragments: list[Any], num_workers: int, logger: logging.Logger
) -> list[list[int]]:
"""Distribute fragments across workers using a balanced algorithm.
This function implements a greedy algorithm that assigns fragments to the
worker with the currently smallest total workload, helping to balance the
processing time across workers.
Parameters
----------
fragments : list
List of Lance fragment objects.
num_workers : int
Number of workers to distribute fragments across.
logger : logging.Logger
Logger instance for debugging information.
Returns
-------
list[list[int]]
Each inner list contains fragment IDs for one worker.
"""
if not fragments:
return [[] for _ in range(num_workers)]
fragment_info: list[dict[str, int]] = []
for fragment in fragments:
try:
# Try to get fragment size information
# fragment.count_rows() gives us the number of rows in the fragment
row_count = fragment.count_rows()
fragment_info.append({"id": fragment.fragment_id, "size": row_count})
except Exception as exc: # pragma: no cover - defensive
logger.warning(
"Could not get size for fragment %s: %s. Using fragment_id as size estimate.",
fragment.fragment_id,
exc,
)
fragment_info.append(
{"id": fragment.fragment_id, "size": fragment.fragment_id}
)
# Sort fragments by size in descending order (largest first)
# This helps with better load balancing using the greedy algorithm
fragment_info.sort(key=lambda x: x["size"], reverse=True)
worker_batches: list[list[int]] = [[] for _ in range(num_workers)]
worker_workloads = [0] * num_workers
# Greedy assignment: assign each fragment to the worker with minimum workload
for frag_info in fragment_info:
# Find the worker with the minimum current workload
min_workload_idx = min(range(num_workers), key=lambda i: worker_workloads[i])
worker_batches[min_workload_idx].append(frag_info["id"])
worker_workloads[min_workload_idx] += frag_info["size"]
total_size = sum(info["size"] for info in fragment_info)
logger.info("Fragment distribution statistics:")
logger.info(" Total fragments: %d", len(fragment_info))
logger.info(" Total size: %d", total_size)
logger.info(" Workers: %d", num_workers)
for i, (batch, workload) in enumerate(
zip(worker_batches, worker_workloads, strict=False)
):
percentage = (workload / total_size * 100) if total_size > 0 else 0
logger.info(
" Worker %d: %d fragments, workload: %d (%.1f%%)",
i,
len(batch),
workload,
percentage,
)
non_empty_batches = [batch for batch in worker_batches if batch]
return non_empty_batches
def _map_async_with_pool(
create_fragment_handler: Callable[[], Any],
fragment_batches: list[list[int]],
*,
num_workers: int,
ray_remote_args: Optional[dict[str, Any]],
error_prefix: str,
) -> list[dict[str, Any]]:
"""Run fragment tasks in a Ray-backed multiprocessing Pool.
This helper encapsulates the common Pool.map_async + get + error wrapping
logic so that both scalar and vector distributed index builders can share
the same implementation.
"""
pool = Pool(processes=num_workers, ray_remote_args=ray_remote_args)
try:
fragment_handler = create_fragment_handler()
rst_futures = pool.map_async(
fragment_handler,
fragment_batches,
chunksize=1,
)
results = rst_futures.get()
except Exception as exc: # pragma: no cover - exercised via integration tests
raise RuntimeError(f"{error_prefix}: {exc}") from exc
finally:
pool.close()
pool.join()
return results
def _is_ray_object_ref(value: Any) -> bool:
object_ref_type = getattr(ray, "ObjectRef", None)
return object_ref_type is not None and isinstance(value, object_ref_type)
def _ray_put_index_artifact(value: Any) -> _VectorIndexArtifactRef:
if value is None or _is_ray_object_ref(value):
return value
return ray.put(value)
def _ray_get_index_artifact(value: Any) -> _VectorIndexArtifact:
if _is_ray_object_ref(value):
return ray.get(value)
return value
def _put_vector_index_artifacts_in_object_store(
ivf_centroids: pa.Array | pa.FixedSizeListArray | pa.FixedShapeTensorArray | None,
pq_codebook: pa.Array | pa.FixedSizeListArray | pa.FixedShapeTensorArray | None,
) -> _VectorIndexArtifactRefs:
return (
_ray_put_index_artifact(ivf_centroids),
_ray_put_index_artifact(pq_codebook),
)
_SCALAR_SEGMENT_INDEX_TYPES = {"BTREE", "BITMAP", "INVERTED", "FTS"}
def _scalar_index_type_name(index_type: str | IndexConfig) -> str | None:
if isinstance(index_type, str):
return index_type.upper()
if isinstance(index_type, IndexConfig):
return index_type.index_type.upper()
return None
def _handle_scalar_segment_index(
dataset_uri: str,
column: str,
index_type: str | IndexConfig,
name: str,
train: bool,
storage_options: Optional[dict[str, str]] = None,
block_size: Optional[int] = None,
namespace_impl: Optional[str] = None,
namespace_properties: Optional[dict[str, str]] = None,
table_id: Optional[list[str]] = None,
**kwargs: Any,
):
"""Create a fragment handler closure for scalar segment index builds."""
def func(fragment_ids: list[int]) -> dict[str, Any]:
try:
if not fragment_ids:
raise ValueError("fragment_ids cannot be empty")
for fragment_id in fragment_ids:
if fragment_id < 0 or fragment_id > 0xFFFFFFFF:
raise ValueError(f"Invalid fragment_id: {fragment_id}")
namespace_kwargs = get_namespace_kwargs(
namespace_impl, namespace_properties, table_id
)
dataset = LanceDataset(
dataset_uri,
**_dataset_load_kwargs(storage_options, namespace_kwargs, block_size),
)
available_fragments = {f.fragment_id for f in dataset.get_fragments()}
invalid_fragments = set(fragment_ids) - available_fragments
if invalid_fragments:
raise ValueError(f"Fragment IDs {invalid_fragments} do not exist")
logger.info(
"Building distributed scalar segment index for fragments %s using "
"create_index_uncommitted",
fragment_ids,
)
segment_index = dataset.create_index_uncommitted(
column=column,
index_type=index_type,
name=name,
replace=False,
train=train,
storage_options=storage_options,
fragment_ids=fragment_ids,
**kwargs,
)
logger.info(
"Fragment scalar segment index created successfully for fragments %s",
fragment_ids,
)
return {
"status": "success",
"fragment_ids": fragment_ids,
"segment_index": segment_index,
}
except Exception as exc: # pragma: no cover - exercised via integration tests
logger.error(
"Fragment scalar segment index task failed for fragments %s: %s",
fragment_ids,
exc,
)
return {
"status": "error",
"fragment_ids": fragment_ids,
"error": str(exc),
}
return func
def _handle_fragment_index(
dataset_uri: str,
column: str,
index_type: str | IndexConfig,
name: str,
index_uuid: str,
replace: bool,
train: bool,
storage_options: Optional[dict[str, str]] = None,
block_size: Optional[int] = None,
namespace_impl: Optional[str] = None,
namespace_properties: Optional[dict[str, str]] = None,
table_id: Optional[list[str]] = None,
**kwargs: Any,
):
"""Create a fragment handler closure for scalar index builds.
The returned callable can be used with :func:`Pool.map_async` to build
indices for specific fragments.
"""
def func(fragment_ids: list[int]) -> dict[str, Any]:
try:
if not fragment_ids:
raise ValueError("fragment_ids cannot be empty")
for fragment_id in fragment_ids:
if fragment_id < 0 or fragment_id > 0xFFFFFFFF:
raise ValueError(f"Invalid fragment_id: {fragment_id}")
namespace_kwargs = get_namespace_kwargs(
namespace_impl, namespace_properties, table_id
)
# Load dataset
dataset = LanceDataset(
dataset_uri,
**_dataset_load_kwargs(storage_options, namespace_kwargs, block_size),
)
available_fragments = {f.fragment_id for f in dataset.get_fragments()}
invalid_fragments = set(fragment_ids) - available_fragments
if invalid_fragments:
raise ValueError(f"Fragment IDs {invalid_fragments} do not exist")
logger.info(
"Building distributed scalar index for fragments %s using create_scalar_index",
fragment_ids,
)
dataset.create_scalar_index(
column=column,
index_type=index_type,
name=name,
replace=replace,
train=train,
index_uuid=index_uuid,
fragment_ids=fragment_ids,
**kwargs,
)
field_id = resolve_dataset_field_path(dataset, column).field_id
logger.info(
"Fragment scalar index created successfully for fragments %s",
fragment_ids,
)
return {
"status": "success",
"fragment_ids": fragment_ids,
"fields": [field_id],
"uuid": index_uuid,
}
except Exception as exc: # pragma: no cover - exercised via integration tests
logger.error(
"Fragment scalar index task failed for fragments %s: %s",
fragment_ids,
exc,
)
return {
"status": "error",
"fragment_ids": fragment_ids,
"error": str(exc),
}
return func
def merge_index_metadata_compat(dataset, index_id, index_type, **kwargs):
"""Call ``merge_index_metadata`` with backwards compatible signature."""
try:
return dataset.merge_index_metadata(
index_id, index_type, batch_readhead=kwargs.get("batch_readhead")
)
except TypeError:
return dataset.merge_index_metadata(index_id)
def create_scalar_index(
uri: Optional[str] = None,
*,
column: str,
index_type: Literal["BTREE"]
| Literal["BITMAP"]
| Literal["LABEL_LIST"]
| Literal["INVERTED"]
| Literal["FTS"]
| Literal["NGRAM"]
| Literal["ZONEMAP"]
| IndexConfig,
table_id: Optional[list[str]] = None,
name: Optional[str] = None,
replace: bool = True,
train: bool = True,
fragment_ids: Optional[list[int]] = None,
index_uuid: Optional[str] = None,
num_workers: int = 4,
storage_options: Optional[dict[str, str]] = None,
block_size: Optional[int] = None,
namespace_impl: Optional[str] = None,
namespace_properties: Optional[dict[str, str]] = None,
ray_remote_args: Optional[dict[str, Any]] = None,
**kwargs: Any,
) -> "lance.LanceDataset":
"""Build scalar indices with Ray in a distributed workflow.
Args:
uri: The URI of the Lance dataset to build index on. Either uri OR
(namespace_impl + table_id) must be provided.
column: Column name to index.
index_type: Type of index to build ("BTREE", "BITMAP", "LABEL_LIST",
"INVERTED", "FTS", "NGRAM", "ZONEMAP") or IndexConfig object.
table_id: The table identifier as a list of strings. Must be provided
together with namespace_impl.
name: Name of the index (generated if None).
replace: Whether to replace existing index with the same name (default: True).
train: Whether to train the index (default: True).
fragment_ids: Optional list of fragment IDs to build index on.
index_uuid: Optional fragment UUID for distributed indexing.
num_workers: Number of Ray workers to use (keyword-only).
storage_options: Storage options for the dataset (keyword-only).
block_size: Block size in bytes to use when loading the dataset (keyword-only).
namespace_impl: The namespace implementation type (e.g., "rest", "dir").
Used together with table_id for resolving the dataset location and
credentials vending in distributed workers.
namespace_properties: Properties for connecting to the namespace.
Used together with namespace_impl and table_id.
ray_remote_args: Options for Ray tasks (e.g., num_cpus, resources) (keyword-only).
**kwargs: Additional arguments to pass to create_scalar_index.
Returns:
Updated Lance dataset with the index created.
Raises:
ValueError: If input parameters are invalid.
TypeError: If column type is not string.
RuntimeError: If index building fails or pylance version is incompatible.
"""
# Check pylance version compatibility
try:
lance_version = version.parse(lance.__version__)
min_required_version = version.parse("0.36.0")
if lance_version < min_required_version:
raise RuntimeError(
"Distributed indexing requires pylance >= 0.36.0, but found "
f"{lance.__version__}. The distribute-related interfaces are "
"not available in older versions. Please upgrade pylance by "
"running: pip install --upgrade pylance"
)
logger.info("Pylance version check passed: %s >= 0.36.0", lance.__version__)
except AttributeError as err: # pragma: no cover - defensive
raise RuntimeError(
"Cannot determine pylance version. Distributed indexing requires "
"pylance >= 0.36.0. Please upgrade pylance by running: "
"pip install --upgrade pylance"
) from err
index_id = str(uuid.uuid4())
logger.info("Starting distributed scalar index build with ID: %s", index_id)
# Validate uri or namespace params
validate_uri_or_namespace(uri, namespace_impl, table_id)
if not column:
raise ValueError("Column name cannot be empty")
if num_workers <= 0:
raise ValueError(f"num_workers must be positive, got {num_workers}")
if block_size is not None and block_size <= 0:
raise ValueError(f"block_size must be positive, got {block_size}")
if isinstance(index_type, str):
valid_index_types = [
"BTREE",
"BITMAP",
"LABEL_LIST",
"INVERTED",
"FTS",
"NGRAM",
"ZONEMAP",
]
if index_type not in valid_index_types:
raise ValueError(
f"Index type must be one of {valid_index_types}, not '{index_type}'"
)
supported_distributed_types = {"INVERTED", "FTS", "BTREE", "BITMAP"}
if index_type not in supported_distributed_types:
raise ValueError(
"Distributed indexing currently supports "
f"{sorted(supported_distributed_types)} index types, "
f"not '{index_type}'"
)
elif not isinstance(index_type, IndexConfig):
raise ValueError(
"index_type must be a string literal or IndexConfig object, got "
f"{type(index_type)}"
)
# Note: Ray initialization is now handled by the Pool, following the pattern from io.py
# This removes the need for explicit ray.init() calls
# Resolve URI and get storage options from namespace if provided
uri, merged_storage_options = resolve_namespace_table(
uri, storage_options, namespace_impl, namespace_properties, table_id
)
namespace_kwargs = get_namespace_kwargs(
namespace_impl, namespace_properties, table_id
)
# Load dataset
dataset = LanceDataset(
uri,
**_dataset_load_kwargs(merged_storage_options, namespace_kwargs, block_size),
)
try:
resolved_column = resolve_dataset_field_path(dataset, column)
except KeyError as exc:
available_columns = [field.name for field in dataset.schema]
raise ValueError(
f"Column '{column}' not found. Available: {available_columns}"
) from exc
column = resolved_column.path
field = resolved_column.field
# Check column type according to index type
value_type = field.type
if pa.types.is_list(field.type) or pa.types.is_large_list(field.type):
value_type = field.type.value_type
if isinstance(index_type, str):
match index_type:
case "INVERTED" | "FTS":
if not (
pa.types.is_string(value_type)
or pa.types.is_large_string(value_type)
):
raise TypeError(
f"Column {column} must be string type for {index_type} "
f"index, got {value_type}"
)
case "BTREE":
is_supported = (
pa.types.is_integer(value_type)
or pa.types.is_floating(value_type)
or pa.types.is_string(value_type)
)
if not is_supported:
raise TypeError(
f"Column {column} must be numeric or string type for BTREE "
f"index, got {value_type}"
)
case _:
# For other index types, skip strict validation to maintain compatibility
pass
use_segment_workflow = (
_scalar_index_type_name(index_type) in _SCALAR_SEGMENT_INDEX_TYPES
)
if name is None:
name = f"{column}_idx"
if replace:
if _index_exists(dataset, name):
# Lance 4.0.0: fragment_ids + replace=True may hit an unimplemented path.
# Implement replace semantics at the driver by dropping the index first.
dataset.drop_index(name)
dataset = LanceDataset(
uri,
**_dataset_load_kwargs(
merged_storage_options, namespace_kwargs, block_size
),
)
else:
if _index_exists(dataset, name):
raise ValueError(
f"Index with name '{name}' already exists. Set replace=True "
"to replace it."
)
fragments = dataset.get_fragments()
if not fragments:
raise ValueError("Dataset contains no fragments")
if fragment_ids is not None:
available_fragment_ids = {f.fragment_id for f in fragments}
invalid_fragments = set(fragment_ids) - available_fragment_ids
if invalid_fragments:
raise ValueError(
f"Fragment IDs {invalid_fragments} do not exist in dataset"
)
fragments = [f for f in fragments if f.fragment_id in fragment_ids]
fragment_ids_to_use = fragment_ids
else:
fragment_ids_to_use = [fragment.fragment_id for fragment in fragments]
if num_workers > len(fragment_ids_to_use):
num_workers = len(fragment_ids_to_use)
logger.info("Adjusted num_workers to %d to match fragment count", num_workers)
fragment_batches = _distribute_fragments_balanced(fragments, num_workers, logger)
def create_fragment_handler() -> Any:
if use_segment_workflow:
return _handle_scalar_segment_index(
dataset_uri=uri,
column=column,
index_type=index_type,
name=name,
train=train,
storage_options=merged_storage_options,
block_size=block_size,
namespace_impl=namespace_impl,
namespace_properties=namespace_properties,
table_id=table_id,
**kwargs,
)
return _handle_fragment_index(
dataset_uri=uri,
column=column,
index_type=index_type,
name=name,
index_uuid=index_id,
replace=False,
train=train,
storage_options=merged_storage_options,
block_size=block_size,
namespace_impl=namespace_impl,
namespace_properties=namespace_properties,
table_id=table_id,
**kwargs,
)
logger.info(
"Phase 1: Distributing scalar index build across %d workers for %d fragments",
len(fragment_batches),
len(fragment_ids_to_use),
)
results = _map_async_with_pool(
create_fragment_handler=create_fragment_handler,
fragment_batches=fragment_batches,
num_workers=num_workers,
ray_remote_args=ray_remote_args,
error_prefix="Failed to complete distributed index building",
)
failed_results = [r for r in results if r["status"] == "error"]
if failed_results:
error_messages = [r["error"] for r in failed_results]
raise RuntimeError(f"Index building failed: {'; '.join(error_messages)}")
# Reload dataset to get the latest state after fragment index creation
dataset = LanceDataset(
uri,
**_dataset_load_kwargs(merged_storage_options, namespace_kwargs, block_size),
)
successful_results = [r for r in results if r["status"] == "success"]
if not successful_results:
raise RuntimeError("No successful index creation results found")
if use_segment_workflow:
logger.info(
"Phase 2: Committing scalar distributed index segments for index '%s'",
name,
)
updated_dataset = dataset.commit_existing_index_segments(
index_name=name,
column=column,
segments=[r["segment_index"] for r in successful_results],
)
logger.info(
"Successfully created distributed scalar segment index '%s'",
name,
)
logger.info(
"Fragments: %d, Workers: %d",
len(fragment_ids_to_use),
len(fragment_batches),
)
return updated_dataset
logger.info("Phase 2: Merging index metadata for index ID: %s", index_id)
# Convert IndexConfig to string for merge_index_metadata which expects a string
# (lance's create_scalar_index converts IndexConfig to "scalar" internally)
index_type_str = "scalar" if isinstance(index_type, IndexConfig) else index_type
merge_index_metadata_compat(dataset, index_id, index_type=index_type_str, **kwargs)
logger.info("Phase 3: Creating and committing scalar index '%s'", name)
fields = successful_results[0]["fields"]
index = Index(
uuid=index_id,
name=name,
fields=fields,
dataset_version=dataset.version,
fragment_ids=set(fragment_ids_to_use),
index_version=0,
)
create_index_op = lance.LanceOperation.CreateIndex(
new_indices=[index],
removed_indices=[],
)
updated_dataset = lance.LanceDataset.commit(
uri,
create_index_op,
read_version=dataset.version,
storage_options=merged_storage_options,
**namespace_kwargs,
)
logger.info(
"Successfully created distributed scalar index '%s' with three-phase workflow",
name,
)
logger.info(
"Index ID: %s, Fragments: %d, Workers: %d",
index_id,
len(fragment_ids_to_use),
len(fragment_batches),
)
return updated_dataset
# ---------------------------------------------------------------------------
# Distributed vector index support (IVF_* and IVF_HNSW_* families)
# ---------------------------------------------------------------------------
# Vector index types supported by the distributed merge pipeline.
_VECTOR_INDEX_TYPES = {
"IVF_FLAT",
"IVF_PQ",
"IVF_SQ",
"IVF_HNSW_FLAT",
"IVF_HNSW_PQ",
"IVF_HNSW_SQ",
}
def _vector_dimension(field: pa.Field) -> int:
if pa.types.is_fixed_size_list(field.type):
return field.type.list_size
if isinstance(field.type, pa.FixedShapeTensorType) and len(field.type.shape) == 1:
return field.type.shape[0]
raise TypeError(
f"Vector column must be FixedSizeListArray or 1-dimensional "
f"FixedShapeTensorArray, got {field.type}"
)
def _validate_vector_value_type(field: pa.Field) -> None:
value_type = field.type.value_type
if not (
pa.types.is_floating(value_type) or pa.types.is_unsigned_integer(value_type)
):
raise TypeError(
"Vector column must have floating or unsigned integer value type, "
f"got {value_type}"
)
def _schema_names(schema: pa.Schema) -> list[str]:
names = getattr(schema, "names", None)
if names is not None:
return list(names)
return [field.name for field in schema]
class _NestedVectorIndicesBuilder:
def __init__(self, dataset: LanceDataset, column: str, field: pa.Field):
self.dataset = dataset
self.column = column
self.dimension = _vector_dimension(field)
_validate_vector_value_type(field)
def train_ivf(
self,
num_partitions: Optional[int] = None,
*,
distance_type: str = "l2",
sample_rate: int = 256,
max_iters: int = 50,
fragment_ids: Optional[list[int]] = None,
**kwargs: Any,
) -> Any:
if kwargs.get("accelerator") is not None:
raise NotImplementedError(
"Nested vector IVF training does not support accelerator training"
)
from lance.indices.ivf import IvfModel
from lance.lance import indices
num_rows = _count_rows_for_fragments(self.dataset, fragment_ids)
partition_count = _determine_num_partitions(num_partitions, num_rows)
_verify_ivf_sample_rate(sample_rate, partition_count, num_rows)
distance_type = _normalize_distance_type(distance_type)
_verify_num_partitions(partition_count)
centroids = indices.train_ivf_model(
self.dataset._ds,
self.column,
self.dimension,
partition_count,
distance_type,
sample_rate,
max_iters,
fragment_ids,
)
return IvfModel(centroids, distance_type)
def train_pq(
self,
ivf_model: Any,
num_subvectors: Optional[int] = None,
*,
sample_rate: int = 256,
max_iters: int = 50,
fragment_ids: Optional[list[int]] = None,
) -> Any:
from lance.indices.pq import PqModel
from lance.lance import indices
num_rows = _count_rows_for_fragments(self.dataset, fragment_ids)
num_subvectors = _normalize_pq_params(num_subvectors, self.dimension)
_verify_pq_sample_rate(num_rows, sample_rate)
codebook = indices.train_pq_model(
self.dataset._ds,
self.column,
self.dimension,
num_subvectors,
ivf_model.distance_type,
sample_rate,
max_iters,
ivf_model.centroids,
fragment_ids,
)
return PqModel(num_subvectors, codebook)
def _count_rows_for_fragments(
dataset: LanceDataset,
fragment_ids: Optional[list[int]],
) -> int:
if fragment_ids is None:
return dataset.count_rows()
row_count = 0
for fragment_id in fragment_ids:
fragment = dataset.get_fragment(fragment_id)
if fragment is None:
raise ValueError(f"Fragment id does not exist: {fragment_id}")
row_count += fragment.count_rows()
return row_count
def _determine_num_partitions(num_partitions: Optional[int], num_rows: int) -> int:
if num_partitions is None:
return round(math.sqrt(num_rows))
return num_partitions
def _verify_base_sample_rate(sample_rate: int) -> None:
if not isinstance(sample_rate, int) or sample_rate < 2:
raise ValueError(
f"The sample_rate must be an int greater than 1, got {sample_rate}"
)
def _verify_ivf_sample_rate(
sample_rate: int,
num_partitions: int,
num_rows: int,
) -> None:
_verify_base_sample_rate(sample_rate)
if num_partitions * sample_rate > num_rows:
raise ValueError(
"There are not enough rows in the dataset to create IVF centroids with"
f" {num_partitions} partitions and a sample rate of {sample_rate}."
f" {sample_rate * num_partitions} rows needed and there are {num_rows}"
)
def _verify_num_partitions(num_partitions: int) -> None:
if not isinstance(num_partitions, int):
raise TypeError(f"num_partitions must be int, got {type(num_partitions)}")
def _normalize_distance_type(distance_type: str) -> str:
if not isinstance(distance_type, str) or distance_type.lower() not in [
"l2",
"cosine",
"euclidean",
"dot",
"hamming",
]:
raise ValueError(f"Distance type {distance_type} not supported.")
return distance_type.lower()
def _normalize_pq_params(num_subvectors: Optional[int], dimension: int) -> int:
if num_subvectors is None:
if dimension % 16 == 0:
return dimension // 16
if dimension % 8 == 0:
return dimension // 8
raise ValueError(
f"vector dimension {dimension} is not divisible by 16 or 8."
" PQ performance will be poor. Please specify num_subvectors manually."
)
if not isinstance(num_subvectors, int):
raise ValueError("num_subvectors must be an int")
if num_subvectors < 1:
raise ValueError("num_subvectors must be greater than 0")
if num_subvectors > dimension:
raise ValueError(
"num_subvectors must be less than or equal to the dimension of the vectors"
)
if dimension % num_subvectors != 0:
raise ValueError(
f"dimension ({dimension}) must be divisible by num_subvectors "
f"({num_subvectors}) without remainder"
)
return num_subvectors
def _verify_pq_sample_rate(num_rows: int, sample_rate: int) -> None:
_verify_base_sample_rate(sample_rate)
if 256 * sample_rate > num_rows:
raise ValueError(
"There are not enough rows in the dataset to create PQ codebook with "
f"a sample rate of {sample_rate}. {sample_rate * 256} rows needed and "
f"there are {num_rows}"
)
def _indices_builder_for_field_path(
dataset: LanceDataset,
column: str,
field: pa.Field,
) -> IndicesBuilder | _NestedVectorIndicesBuilder:
if column in _schema_names(dataset.schema):
return IndicesBuilder(dataset, column)
return _NestedVectorIndicesBuilder(dataset, column, field)
def _train_pq_for_field_path(
builder: IndicesBuilder | _NestedVectorIndicesBuilder,
ivf_model: Any,
*,
num_subvectors: Optional[int],
sample_rate: int,
) -> Any:
return builder.train_pq(
ivf_model,
num_subvectors=num_subvectors,
sample_rate=sample_rate,
)
def _normalize_index_type(index_type: Any) -> str:
"""Normalize index type to upper-case string and validate support.
Parameters
----------
index_type : str or enum-like
Vector index type. Must be one of the precise distributed vector
types supported by Lance.
"""
if hasattr(index_type, "value") and isinstance(index_type.value, str):
index_type_name = index_type.value.upper()
elif isinstance(index_type, str):
index_type_name = index_type.upper()
else:
raise TypeError(
"index_type must be a string or an enum-like object with a string 'value' "
f"attribute, got {type(index_type)}"