-
Notifications
You must be signed in to change notification settings - Fork 245
/
Copy pathdataset.rs
2025 lines (1816 loc) · 73.2 KB
/
dataset.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 Lance Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::str;
use std::sync::Arc;
use arrow::array::AsArray;
use arrow::datatypes::UInt8Type;
use arrow::ffi_stream::ArrowArrayStreamReader;
use arrow::pyarrow::*;
use arrow_array::{make_array, RecordBatch, RecordBatchReader};
use arrow_data::ArrayData;
use arrow_schema::{DataType, Schema as ArrowSchema};
use async_trait::async_trait;
use blob::LanceBlobFile;
use chrono::Duration;
use arrow_array::Array;
use futures::{StreamExt, TryFutureExt};
use lance::dataset::builder::DatasetBuilder;
use lance::dataset::refs::{Ref, TagContents};
use lance::dataset::scanner::MaterializationStyle;
use lance::dataset::statistics::{DataStatistics, DatasetStatisticsExt};
use lance::dataset::{
fragment::FileFragment as LanceFileFragment,
progress::WriteFragmentProgress,
scanner::Scanner as LanceScanner,
transaction::{Operation, Transaction},
Dataset as LanceDataset, MergeInsertBuilder as LanceMergeInsertBuilder, ReadParams,
UpdateBuilder, Version, WhenMatched, WhenNotMatched, WhenNotMatchedBySource, WriteMode,
WriteParams,
};
use lance::dataset::{
BatchInfo, BatchUDF, CommitBuilder, MergeStats, NewColumnTransform, UDFCheckpointStore,
WriteDestination,
};
use lance::dataset::{ColumnAlteration, ProjectionRequest};
use lance::index::vector::utils::get_vector_type;
use lance::index::{vector::VectorIndexParams, DatasetIndexInternalExt};
use lance_arrow::as_fixed_size_list_array;
use lance_index::scalar::InvertedIndexParams;
use lance_index::{
optimize::OptimizeOptions,
scalar::{FullTextSearchQuery, ScalarIndexParams, ScalarIndexType},
vector::{
hnsw::builder::HnswBuildParams, ivf::IvfBuildParams, pq::PQBuildParams,
sq::builder::SQBuildParams,
},
DatasetIndexExt, IndexParams, IndexType,
};
use lance_io::object_store::ObjectStoreParams;
use lance_linalg::distance::MetricType;
use lance_table::format::Fragment;
use lance_table::io::commit::CommitHandler;
use object_store::path::Path;
use pyo3::exceptions::{PyStopIteration, PyTypeError};
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyInt, PyList, PySet, PyString};
use pyo3::{
exceptions::{PyIOError, PyKeyError, PyValueError},
pyclass,
types::{IntoPyDict, PyDict},
PyObject, PyResult,
};
use snafu::{location, Location};
use crate::error::PythonErrorExt;
use crate::file::object_store_from_uri_or_path;
use crate::fragment::FileFragment;
use crate::schema::LanceSchema;
use crate::session::Session;
use crate::utils::PyLance;
use crate::RT;
use crate::{LanceReader, Scanner};
use self::cleanup::CleanupStats;
use self::commit::PyCommitLock;
pub mod blob;
pub mod cleanup;
pub mod commit;
pub mod optimize;
pub mod stats;
const DEFAULT_NPROBS: usize = 1;
const DEFAULT_INDEX_CACHE_SIZE: usize = 256;
const DEFAULT_METADATA_CACHE_SIZE: usize = 256;
fn convert_reader(reader: &Bound<PyAny>) -> PyResult<Box<dyn RecordBatchReader + Send>> {
let py = reader.py();
if reader.is_instance_of::<Scanner>() {
let scanner: Scanner = reader.extract()?;
Ok(Box::new(
RT.spawn(Some(py), async move { scanner.to_reader().await })?
.map_err(|err| PyValueError::new_err(err.to_string()))?,
))
} else {
Ok(Box::new(ArrowArrayStreamReader::from_pyarrow_bound(
reader,
)?))
}
}
#[pyclass(name = "_MergeInsertBuilder", module = "_lib", subclass)]
pub struct MergeInsertBuilder {
builder: LanceMergeInsertBuilder,
dataset: Py<Dataset>,
}
#[pymethods]
impl MergeInsertBuilder {
#[new]
pub fn new(dataset: &Bound<'_, PyAny>, on: &Bound<'_, PyAny>) -> PyResult<Self> {
let dataset: Py<Dataset> = dataset.extract()?;
let ds = dataset.borrow(on.py()).ds.clone();
// Either a single string, which we put in a vector or an iterator
// of strings, which we collect into a vector
let on = on
.downcast::<PyString>()
.map(|val| vec![val.to_string()])
.or_else(|_| {
let iterator = on.iter().map_err(|_| {
PyTypeError::new_err(
"The `on` argument to merge_insert must be a str or iterable of str",
)
})?;
let mut keys = Vec::new();
for key in iterator {
keys.push(key?.downcast::<PyString>()?.to_string());
}
PyResult::Ok(keys)
})?;
let mut builder = LanceMergeInsertBuilder::try_new(ds, on)
.map_err(|err| PyValueError::new_err(err.to_string()))?;
// We don't have do_nothing methods in python so we start with a blank slate
builder
.when_matched(WhenMatched::DoNothing)
.when_not_matched(WhenNotMatched::DoNothing);
Ok(Self { builder, dataset })
}
#[pyo3(signature=(condition=None))]
pub fn when_matched_update_all<'a>(
mut slf: PyRefMut<'a, Self>,
condition: Option<&str>,
) -> PyResult<PyRefMut<'a, Self>> {
let new_val = if let Some(expr) = condition {
let dataset = slf.dataset.borrow(slf.py());
WhenMatched::update_if(&dataset.ds, expr)
.map_err(|err| PyValueError::new_err(err.to_string()))?
} else {
WhenMatched::UpdateAll
};
slf.builder.when_matched(new_val);
Ok(slf)
}
pub fn when_not_matched_insert_all(mut slf: PyRefMut<Self>) -> PyResult<PyRefMut<Self>> {
slf.builder.when_not_matched(WhenNotMatched::InsertAll);
Ok(slf)
}
#[pyo3(signature=(expr=None))]
pub fn when_not_matched_by_source_delete<'a>(
mut slf: PyRefMut<'a, Self>,
expr: Option<&str>,
) -> PyResult<PyRefMut<'a, Self>> {
let new_val = if let Some(expr) = expr {
let dataset = slf.dataset.borrow(slf.py());
WhenNotMatchedBySource::delete_if(&dataset.ds, expr)
.map_err(|err| PyValueError::new_err(err.to_string()))?
} else {
WhenNotMatchedBySource::Delete
};
slf.builder.when_not_matched_by_source(new_val);
Ok(slf)
}
pub fn execute(&mut self, new_data: &Bound<PyAny>) -> PyResult<PyObject> {
let py = new_data.py();
let new_data = convert_reader(new_data)?;
let job = self
.builder
.try_build()
.map_err(|err| PyValueError::new_err(err.to_string()))?;
let (new_dataset, stats) = RT
.spawn(Some(py), job.execute_reader(new_data))?
.map_err(|err| PyIOError::new_err(err.to_string()))?;
let dataset = self.dataset.bind(py);
dataset.borrow_mut().ds = new_dataset;
Ok(Self::build_stats(&stats, py)?.into())
}
pub fn execute_uncommitted<'a>(
&mut self,
new_data: &Bound<'a, PyAny>,
) -> PyResult<(PyLance<Transaction>, Bound<'a, PyDict>)> {
let py = new_data.py();
let new_data = convert_reader(new_data)?;
let job = self
.builder
.try_build()
.map_err(|err| PyValueError::new_err(err.to_string()))?;
let (transaction, stats) = RT
.spawn(Some(py), job.execute_uncommitted(new_data))?
.map_err(|err| PyIOError::new_err(err.to_string()))?;
let stats = Self::build_stats(&stats, py)?;
Ok((PyLance(transaction), stats))
}
}
impl MergeInsertBuilder {
fn build_stats<'a>(stats: &MergeStats, py: Python<'a>) -> PyResult<Bound<'a, PyDict>> {
let dict = PyDict::new_bound(py);
dict.set_item("num_inserted_rows", stats.num_inserted_rows)?;
dict.set_item("num_updated_rows", stats.num_updated_rows)?;
dict.set_item("num_deleted_rows", stats.num_deleted_rows)?;
Ok(dict)
}
}
pub fn transforms_from_python(transforms: &Bound<'_, PyAny>) -> PyResult<NewColumnTransform> {
if let Ok(transforms) = transforms.extract::<&PyDict>() {
let expressions = transforms
.iter()
.map(|(k, v)| {
let col = k.extract::<String>()?;
let expr = v.extract::<String>()?;
Ok((col, expr))
})
.collect::<PyResult<Vec<_>>>()?;
Ok(NewColumnTransform::SqlExpressions(expressions))
} else {
let append_schema: PyArrowType<ArrowSchema> =
transforms.getattr("output_schema")?.extract()?;
let output_schema = Arc::new(append_schema.0);
let result_checkpoint: Option<PyObject> = transforms.getattr("cache")?.extract()?;
let result_checkpoint = result_checkpoint.map(|c| PyBatchUDFCheckpointWrapper { inner: c });
let udf_obj = transforms.to_object(transforms.py());
let mapper = move |batch: &RecordBatch| -> lance::Result<RecordBatch> {
Python::with_gil(|py| {
let py_batch: PyArrowType<RecordBatch> = PyArrowType(batch.clone());
let result = udf_obj
.call_method1(py, "_call", (py_batch,))
.map_err(|err| {
lance::Error::io(format_python_error(err, py).unwrap(), location!())
})?;
let result_batch: PyArrowType<RecordBatch> = result
.extract(py)
.map_err(|err| lance::Error::io(err.to_string(), location!()))?;
Ok(result_batch.0)
})
};
Ok(NewColumnTransform::BatchUDF(BatchUDF {
mapper: Box::new(mapper),
output_schema,
result_checkpoint: result_checkpoint
.map(|c| Arc::new(c) as Arc<dyn UDFCheckpointStore>),
}))
}
}
/// Lance Dataset that will be wrapped by another class in Python
#[pyclass(name = "_Dataset", module = "_lib")]
#[derive(Clone)]
pub struct Dataset {
#[pyo3(get)]
uri: String,
pub(crate) ds: Arc<LanceDataset>,
}
#[pymethods]
impl Dataset {
#[allow(clippy::too_many_arguments)]
#[new]
#[pyo3(signature=(uri, version=None, block_size=None, index_cache_size=None, metadata_cache_size=None, commit_handler=None, storage_options=None, manifest=None))]
fn new(
py: Python,
uri: String,
version: Option<PyObject>,
block_size: Option<usize>,
index_cache_size: Option<usize>,
metadata_cache_size: Option<usize>,
commit_handler: Option<PyObject>,
storage_options: Option<HashMap<String, String>>,
manifest: Option<&[u8]>,
) -> PyResult<Self> {
let mut params = ReadParams {
index_cache_size: index_cache_size.unwrap_or(DEFAULT_INDEX_CACHE_SIZE),
metadata_cache_size: metadata_cache_size.unwrap_or(DEFAULT_METADATA_CACHE_SIZE),
store_options: Some(ObjectStoreParams {
block_size,
..Default::default()
}),
..Default::default()
};
if let Some(commit_handler) = commit_handler {
let py_commit_lock = PyCommitLock::new(commit_handler);
params.set_commit_lock(Arc::new(py_commit_lock));
}
let mut builder = DatasetBuilder::from_uri(&uri).with_read_params(params);
if let Some(ver) = version {
if let Ok(i) = ver.downcast_bound::<PyInt>(py) {
let v: u64 = i.extract()?;
builder = builder.with_version(v);
} else if let Ok(v) = ver.downcast_bound::<PyString>(py) {
let t: &str = v.extract()?;
builder = builder.with_tag(t);
} else {
return Err(PyIOError::new_err(
"version must be an integer or a string.",
));
};
}
if let Some(storage_options) = storage_options {
builder = builder.with_storage_options(storage_options);
}
if let Some(manifest) = manifest {
builder = builder.with_serialized_manifest(manifest).infer_error()?;
}
let dataset = RT.runtime.block_on(builder.load());
match dataset {
Ok(ds) => Ok(Self {
uri,
ds: Arc::new(ds),
}),
// TODO: return an appropriate error type, such as IOError or NotFound.
Err(err) => Err(PyValueError::new_err(err.to_string())),
}
}
pub fn __copy__(&self) -> Self {
self.clone()
}
#[getter(max_field_id)]
fn max_field_id(self_: PyRef<'_, Self>) -> PyResult<i32> {
Ok(self_.ds.manifest().max_field_id())
}
#[getter(schema)]
fn schema(self_: PyRef<'_, Self>) -> PyResult<PyObject> {
let arrow_schema = ArrowSchema::from(self_.ds.schema());
arrow_schema.to_pyarrow(self_.py())
}
#[getter(lance_schema)]
fn lance_schema(self_: PyRef<'_, Self>) -> LanceSchema {
LanceSchema(self_.ds.schema().clone())
}
fn replace_schema_metadata(&mut self, metadata: HashMap<String, String>) -> PyResult<()> {
let mut new_self = self.ds.as_ref().clone();
RT.block_on(None, new_self.replace_schema_metadata(metadata))?
.map_err(|err| PyIOError::new_err(err.to_string()))?;
self.ds = Arc::new(new_self);
Ok(())
}
fn replace_field_metadata(
&mut self,
field_name: &str,
metadata: HashMap<String, String>,
) -> PyResult<()> {
let mut new_self = self.ds.as_ref().clone();
let field = new_self
.schema()
.field(field_name)
.ok_or_else(|| PyKeyError::new_err(format!("Field \"{}\" not found", field_name)))?;
let new_field_meta: HashMap<u32, HashMap<String, String>> =
HashMap::from_iter(vec![(field.id as u32, metadata)]);
RT.block_on(None, new_self.replace_field_metadata(new_field_meta))?
.map_err(|err| PyIOError::new_err(err.to_string()))?;
self.ds = Arc::new(new_self);
Ok(())
}
#[getter(data_storage_version)]
fn data_storage_version(&self) -> PyResult<String> {
Ok(self.ds.manifest().data_storage_format.version.clone())
}
/// Get index statistics
fn index_statistics(&self, index_name: String) -> PyResult<String> {
RT.runtime
.block_on(self.ds.index_statistics(&index_name))
.map_err(|err| match err {
lance::Error::IndexNotFound { .. } => {
PyKeyError::new_err(format!("Index \"{}\" not found", index_name))
}
_ => PyIOError::new_err(format!(
"Failed to get index statistics for index {}: {}",
index_name, err
)),
})
}
fn serialized_manifest(&self, py: Python) -> PyObject {
let manifest_bytes = self.ds.manifest().serialized();
PyBytes::new_bound(py, &manifest_bytes).into()
}
/// Load index metadata.
///
/// This call will open the index and return its concrete index type.
fn load_indices(self_: PyRef<'_, Self>) -> PyResult<Vec<PyObject>> {
let index_metadata = RT
.block_on(Some(self_.py()), self_.ds.load_indices())?
.map_err(|err| PyValueError::new_err(err.to_string()))?;
let py = self_.py();
index_metadata
.iter()
.map(|idx| {
let dict = PyDict::new_bound(py);
let schema = self_.ds.schema();
let idx_schema = schema.project_by_ids(idx.fields.as_slice(), true);
let ds = self_.ds.clone();
let idx_type = RT
.block_on(Some(self_.py()), async {
let idx = ds
.open_generic_index(&idx_schema.fields[0].name, &idx.uuid.to_string())
.await?;
Ok::<_, lance::Error>(idx.index_type())
})?
.map_err(|e| PyIOError::new_err(e.to_string()))?;
let field_names = idx_schema
.fields
.iter()
.map(|f| f.name.clone())
.collect::<Vec<_>>();
let fragment_set = PySet::empty_bound(py).unwrap();
if let Some(bitmap) = &idx.fragment_bitmap {
for fragment_id in bitmap.iter() {
fragment_set.add(fragment_id).unwrap();
}
}
dict.set_item("name", idx.name.clone()).unwrap();
// TODO: once we add more than vector indices, we need to:
// 1. Change protos and write path to persist index type
// 2. Use the new field from idx instead of hard coding it to Vector
dict.set_item("type", idx_type.to_string()).unwrap();
dict.set_item("uuid", idx.uuid.to_string()).unwrap();
dict.set_item("fields", field_names).unwrap();
dict.set_item("version", idx.dataset_version).unwrap();
dict.set_item("fragment_ids", fragment_set).unwrap();
Ok(dict.to_object(py))
})
.collect::<PyResult<Vec<_>>>()
}
#[allow(clippy::too_many_arguments)]
#[pyo3(signature=(columns=None, columns_with_transform=None, filter=None, prefilter=None, limit=None, offset=None, nearest=None, batch_size=None, io_buffer_size=None, batch_readahead=None, fragment_readahead=None, scan_in_order=None, fragments=None, with_row_id=None, with_row_address=None, use_stats=None, substrait_filter=None, fast_search=None, full_text_query=None, late_materialization=None, use_scalar_index=None))]
fn scanner(
self_: PyRef<'_, Self>,
columns: Option<Vec<String>>,
columns_with_transform: Option<Vec<(String, String)>>,
filter: Option<String>,
prefilter: Option<bool>,
limit: Option<i64>,
offset: Option<i64>,
nearest: Option<&Bound<PyDict>>,
batch_size: Option<usize>,
io_buffer_size: Option<u64>,
batch_readahead: Option<usize>,
fragment_readahead: Option<usize>,
scan_in_order: Option<bool>,
fragments: Option<Vec<FileFragment>>,
with_row_id: Option<bool>,
with_row_address: Option<bool>,
use_stats: Option<bool>,
substrait_filter: Option<Vec<u8>>,
fast_search: Option<bool>,
full_text_query: Option<&Bound<'_, PyDict>>,
late_materialization: Option<PyObject>,
use_scalar_index: Option<bool>,
) -> PyResult<Scanner> {
let mut scanner: LanceScanner = self_.ds.scan();
match (columns, columns_with_transform) {
(Some(_), Some(_)) => {
return Err(PyValueError::new_err(
"Cannot specify both columns and columns_with_transform",
))
}
(Some(c), None) => {
scanner
.project(&c)
.map_err(|err| PyValueError::new_err(err.to_string()))?;
}
(None, Some(ct)) => {
scanner
.project_with_transform(&ct)
.map_err(|err| PyValueError::new_err(err.to_string()))?;
}
(None, None) => {}
}
if let Some(f) = filter {
if substrait_filter.is_some() {
return Err(PyValueError::new_err(
"cannot specify both a string filter and a substrait filter",
));
}
scanner
.filter(f.as_str())
.map_err(|err| PyValueError::new_err(err.to_string()))?;
}
if let Some(full_text_query) = full_text_query {
let query = full_text_query
.get_item("query")?
.ok_or_else(|| PyKeyError::new_err("Need column for full text search"))?
.to_string();
let columns = if let Some(columns) = full_text_query.get_item("columns")? {
if columns.is_none() {
None
} else {
Some(
columns
.downcast::<PyList>()?
.iter()
.map(|c| c.extract::<String>())
.collect::<PyResult<Vec<String>>>()?,
)
}
} else {
None
};
let full_text_query = FullTextSearchQuery::new(query).columns(columns);
scanner
.full_text_search(full_text_query)
.map_err(|err| PyValueError::new_err(err.to_string()))?;
}
if let Some(f) = substrait_filter {
scanner.filter_substrait(f.as_slice()).infer_error()?;
}
if let Some(prefilter) = prefilter {
scanner.prefilter(prefilter);
}
scanner
.limit(limit, offset)
.map_err(|err| PyValueError::new_err(err.to_string()))?;
if let Some(batch_size) = batch_size {
scanner.batch_size(batch_size);
}
if let Some(io_buffer_size) = io_buffer_size {
scanner.io_buffer_size(io_buffer_size);
}
if let Some(batch_readahead) = batch_readahead {
scanner.batch_readahead(batch_readahead);
}
if let Some(fragment_readahead) = fragment_readahead {
scanner.fragment_readahead(fragment_readahead);
}
scanner.scan_in_order(scan_in_order.unwrap_or(true));
if with_row_id.unwrap_or(false) {
scanner.with_row_id();
}
if with_row_address.unwrap_or(false) {
scanner.with_row_address();
}
if let Some(use_stats) = use_stats {
scanner.use_stats(use_stats);
}
if let Some(true) = fast_search {
scanner.fast_search();
}
if let Some(fragments) = fragments {
let fragments = fragments
.into_iter()
.map(|f| {
let file_fragment = LanceFileFragment::from(f);
file_fragment.into()
})
.collect();
scanner.with_fragments(fragments);
}
if let Some(late_materialization) = late_materialization {
if let Ok(style_as_bool) = late_materialization.extract::<bool>(self_.py()) {
if style_as_bool {
scanner.materialization_style(MaterializationStyle::AllLate);
} else {
scanner.materialization_style(MaterializationStyle::AllEarly);
}
} else if let Ok(columns) = late_materialization.extract::<Vec<String>>(self_.py()) {
scanner.materialization_style(
MaterializationStyle::all_early_except(&columns, self_.ds.schema())
.infer_error()?,
);
} else {
return Err(PyValueError::new_err(
"late_materialization must be a bool or a list of strings",
));
}
}
if let Some(use_scalar_index) = use_scalar_index {
scanner.use_scalar_index(use_scalar_index);
}
if let Some(nearest) = nearest {
let column = nearest
.get_item("column")?
.ok_or_else(|| PyKeyError::new_err("Need column for nearest"))?
.to_string();
let qval = nearest
.get_item("q")?
.ok_or_else(|| PyKeyError::new_err("Need q for nearest"))?;
let data = ArrayData::from_pyarrow_bound(&qval)?;
let q = make_array(data);
let k: usize = if let Some(k) = nearest.get_item("k")? {
if k.is_none() {
// Use limit if k is not specified, default to 10.
limit.unwrap_or(10) as usize
} else {
k.extract()?
}
} else {
10
};
let nprobes: usize = if let Some(nprobes) = nearest.get_item("nprobes")? {
if nprobes.is_none() {
DEFAULT_NPROBS
} else {
nprobes.extract()?
}
} else {
DEFAULT_NPROBS
};
let metric_type: Option<MetricType> =
if let Some(metric) = nearest.get_item("metric")? {
if metric.is_none() {
None
} else {
Some(
MetricType::try_from(metric.to_string().to_lowercase().as_str())
.map_err(|err| PyValueError::new_err(err.to_string()))?,
)
}
} else {
None
};
// When refine factor is specified, a final Refine stage will be added to the I/O plan,
// and use Flat index over the raw vectors to refine the results.
// By default, `refine_factor` is None to not involve extra I/O exec node and random access.
let refine_factor: Option<u32> = if let Some(rf) = nearest.get_item("refine_factor")? {
if rf.is_none() {
None
} else {
rf.extract()?
}
} else {
None
};
let use_index: bool = if let Some(idx) = nearest.get_item("use_index")? {
idx.extract()?
} else {
true
};
let ef: Option<usize> = if let Some(ef) = nearest.get_item("ef")? {
if ef.is_none() {
None
} else {
ef.extract()?
}
} else {
None
};
let (_, element_type) = get_vector_type(self_.ds.schema(), &column)
.map_err(|e| PyValueError::new_err(e.to_string()))?;
let scanner = match element_type {
DataType::UInt8 => {
let q = arrow::compute::cast(&q, &DataType::UInt8).map_err(|e| {
PyValueError::new_err(format!("Failed to cast q to binary vector: {}", e))
})?;
let q = q.as_primitive::<UInt8Type>();
scanner.nearest(&column, q, k)
}
_ => scanner.nearest(&column, &q, k),
};
scanner
.map(|s| {
let mut s = s.nprobs(nprobes);
if let Some(factor) = refine_factor {
s = s.refine(factor);
}
if let Some(m) = metric_type {
s = s.distance_metric(m);
}
if let Some(ef) = ef {
s = s.ef(ef);
}
s.use_index(use_index);
s
})
.map_err(|err| PyValueError::new_err(err.to_string()))?;
}
let scan = Arc::new(scanner);
Ok(Scanner::new(scan))
}
#[pyo3(signature=(filter=None))]
fn count_rows(&self, filter: Option<String>) -> PyResult<usize> {
RT.runtime
.block_on(self.ds.count_rows(filter))
.map_err(|err| PyIOError::new_err(err.to_string()))
}
#[pyo3(signature=(row_indices, columns = None, columns_with_transform = None))]
fn take(
self_: PyRef<'_, Self>,
row_indices: Vec<u64>,
columns: Option<Vec<String>>,
columns_with_transform: Option<Vec<(String, String)>>,
) -> PyResult<PyObject> {
let projection = match (columns, columns_with_transform) {
(Some(_), Some(_)) => {
return Err(PyValueError::new_err(
"Cannot specify both columns and columns_with_transform",
))
}
(Some(columns), None) => {
Ok(ProjectionRequest::from_columns(columns, self_.ds.schema()))
}
(None, Some(sql_exprs)) => Ok(ProjectionRequest::from_sql(sql_exprs)),
(None, None) => Ok(ProjectionRequest::from_schema(self_.ds.schema().clone())),
}
.infer_error()?;
let batch = RT
.block_on(Some(self_.py()), self_.ds.take(&row_indices, projection))?
.map_err(|err| PyIOError::new_err(err.to_string()))?;
batch.to_pyarrow(self_.py())
}
#[pyo3(signature=(row_indices, columns = None, columns_with_transform = None))]
fn take_rows(
self_: PyRef<'_, Self>,
row_indices: Vec<u64>,
columns: Option<Vec<String>>,
columns_with_transform: Option<Vec<(String, String)>>,
) -> PyResult<PyObject> {
let projection = match (columns, columns_with_transform) {
(Some(_), Some(_)) => {
return Err(PyValueError::new_err(
"Cannot specify both columns and columns_with_transform",
))
}
(Some(columns), None) => {
Ok(ProjectionRequest::from_columns(columns, self_.ds.schema()))
}
(None, Some(sql_exprs)) => Ok(ProjectionRequest::from_sql(sql_exprs)),
(None, None) => Ok(ProjectionRequest::from_schema(self_.ds.schema().clone())),
}
.infer_error()?;
let batch = RT
.block_on(
Some(self_.py()),
self_.ds.take_rows(&row_indices, projection),
)?
.map_err(|err| PyIOError::new_err(err.to_string()))?;
batch.to_pyarrow(self_.py())
}
fn take_blobs(
self_: PyRef<'_, Self>,
row_indices: Vec<u64>,
blob_column: &str,
) -> PyResult<Vec<LanceBlobFile>> {
let blobs = RT
.block_on(
Some(self_.py()),
self_.ds.take_blobs(&row_indices, blob_column),
)?
.infer_error()?;
Ok(blobs.into_iter().map(LanceBlobFile::from).collect())
}
#[pyo3(signature = (row_slices, columns = None, batch_readahead = 10))]
fn take_scan(
&self,
row_slices: PyObject,
columns: Option<Vec<String>>,
batch_readahead: usize,
) -> PyResult<PyArrowType<Box<dyn RecordBatchReader + Send>>> {
let projection = if let Some(columns) = columns {
Arc::new(
self.ds
.schema()
.project(&columns)
.map_err(|err| PyValueError::new_err(err.to_string()))?,
)
} else {
Arc::new(self.ds.schema().clone())
};
// Call into the Python iterable, only holding the GIL as necessary.
let py_iter = Python::with_gil(|py| row_slices.call_method0(py, "__iter__"))?;
let slice_iter = std::iter::from_fn(move || {
Python::with_gil(|py| {
match py_iter
.call_method0(py, "__next__")
.and_then(|range| range.extract::<(u64, u64)>(py))
{
Ok((start, end)) => Some(Ok(start..end)),
Err(err) if err.is_instance_of::<PyStopIteration>(py) => None,
Err(err) => Some(Err(lance::Error::InvalidInput {
source: Box::new(err),
location: location!(),
})),
}
})
});
let slice_stream = futures::stream::iter(slice_iter).boxed();
let stream = self.ds.take_scan(slice_stream, projection, batch_readahead);
Ok(PyArrowType(Box::new(LanceReader::from_stream(stream))))
}
fn alter_columns(&mut self, alterations: &Bound<'_, PyList>) -> PyResult<()> {
let alterations = alterations
.iter()
.map(|obj| {
let obj = obj.downcast::<PyDict>()?;
let path: String = obj
.get_item("path")?
.ok_or_else(|| PyValueError::new_err("path is required"))?
.extract()?;
let name: Option<String> =
obj.get_item("name")?.map(|n| n.extract()).transpose()?;
let nullable: Option<bool> =
obj.get_item("nullable")?.map(|n| n.extract()).transpose()?;
let data_type: Option<PyArrowType<DataType>> = obj
.get_item("data_type")?
.map(|n| n.extract())
.transpose()?;
for key in obj.keys().iter().map(|k| k.extract::<String>()) {
let k = key?;
if k != "path" && k != "name" && k != "nullable" && k != "data_type" {
return Err(PyValueError::new_err(format!(
"Unknown key: {}. Valid keys are name, nullable, and data_type.",
k
)));
}
}
if name.is_none() && nullable.is_none() && data_type.is_none() {
return Err(PyValueError::new_err(
"At least one of name, nullable, or data_type must be specified",
));
}
let mut alteration = ColumnAlteration::new(path);
if let Some(name) = name {
alteration = alteration.rename(name);
}
if let Some(nullable) = nullable {
alteration = alteration.set_nullable(nullable);
}
if let Some(data_type) = data_type {
alteration = alteration.cast_to(data_type.0);
}
Ok(alteration)
})
.collect::<PyResult<Vec<_>>>()?;
let mut new_self = self.ds.as_ref().clone();
new_self = RT
.spawn(None, async move {
new_self.alter_columns(&alterations).await.map(|_| new_self)
})?
.map_err(|err| PyIOError::new_err(err.to_string()))?;
self.ds = Arc::new(new_self);
Ok(())
}
fn merge(
&mut self,
reader: PyArrowType<ArrowArrayStreamReader>,
left_on: String,
right_on: String,
) -> PyResult<()> {
let mut new_self = self.ds.as_ref().clone();
let new_self = RT
.spawn(None, async move {
new_self
.merge(reader.0, &left_on, &right_on)
.await
.map(|_| new_self)
})?
.map_err(|err| PyIOError::new_err(err.to_string()))?;
self.ds = Arc::new(new_self);
Ok(())
}
fn delete(&mut self, predicate: String) -> PyResult<()> {
let mut new_self = self.ds.as_ref().clone();
RT.block_on(None, new_self.delete(&predicate))?
.map_err(|err| PyIOError::new_err(err.to_string()))?;
self.ds = Arc::new(new_self);
Ok(())
}
#[pyo3(signature=(updates, predicate=None))]
fn update(
&mut self,
updates: &Bound<'_, PyDict>,
predicate: Option<&str>,
) -> PyResult<PyObject> {
let mut builder = UpdateBuilder::new(self.ds.clone());
if let Some(predicate) = predicate {
builder = builder
.update_where(predicate)
.map_err(|err| PyValueError::new_err(err.to_string()))?;
}
for (key, value) in updates {
let column: &str = key.extract()?;
let expr: &str = value.extract()?;
builder = builder
.set(column, expr)
.map_err(|err| PyValueError::new_err(err.to_string()))?;
}
let operation = builder
.build()
.map_err(|err| PyValueError::new_err(err.to_string()))?;
let new_self = RT
.block_on(None, operation.execute())?
.map_err(|err| PyIOError::new_err(err.to_string()))?;
self.ds = new_self.new_dataset;
let update_dict = PyDict::new_bound(updates.py());
let num_rows_updated = new_self.rows_updated;
update_dict.set_item("num_rows_updated", num_rows_updated)?;
Ok(update_dict.into())
}
fn count_deleted_rows(&self) -> PyResult<usize> {
RT.block_on(None, self.ds.count_deleted_rows())?
.map_err(|err| PyIOError::new_err(err.to_string()))