-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathfile.py
More file actions
258 lines (217 loc) · 8.68 KB
/
file.py
File metadata and controls
258 lines (217 loc) · 8.68 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
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright the Vortex contributors
from __future__ import annotations
from collections.abc import Iterator
from typing import TYPE_CHECKING, final
import pyarrow as pa
from ._lib import file as _file # pyright: ignore[reportMissingModuleSource]
from ._lib.arrays import Array # pyright: ignore[reportMissingModuleSource]
from ._lib.dtype import DType # pyright: ignore[reportMissingModuleSource]
from ._lib.expr import Expr # pyright: ignore[reportMissingModuleSource]
from ._lib.iter import ArrayIterator # pyright: ignore[reportMissingModuleSource]
from .dataset import VortexDataset
from .scan import RepeatedScan
from .store import (
AzureStore,
GCSStore,
HTTPStore,
LocalStore,
MemoryStore,
S3Store,
)
from .type_aliases import IntoProjection, RecordBatchReader
if TYPE_CHECKING:
import polars
def open(
path: str,
*,
store: AzureStore | GCSStore | HTTPStore | LocalStore | MemoryStore | S3Store | None = None,
without_segment_cache: bool = False,
) -> VortexFile:
"""
Lazily open a Vortex file located at the given path or URL.
Parameters
----------
path : :class:`str`
A local path or URL to the Vortex file.
store :
An object store created from the `vortex.store` package. By default
the store is inferred based on the path
without_segment_cache : :class:`bool`
If true, disable the segment cache for this file, useful when memory is constrained.
Examples
--------
Open a Vortex file and perform a scan operation:
>>> import vortex as vx
>>> vxf = vx.open("data.vortex") # doctest: +SKIP
>>> array_iterator = vxf.scan() # doctest: +SKIP
See also: :class:`vortex.dataset.VortexDataset`
"""
return VortexFile(_file.open(path, store=store, without_segment_cache=without_segment_cache))
@final
class VortexFile:
def __init__(self, file: _file.VortexFile):
self._file = file
def __len__(self) -> int:
return self._file.__len__()
@property
def dtype(self) -> DType:
"""The dtype of the file."""
return self._file.dtype
def splits(self) -> list[tuple[int, int]]:
return self._file.splits()
def scan(
self,
projection: IntoProjection = None,
*,
expr: Expr | None = None,
limit: int | None = None,
indices: Array | None = None,
batch_size: int | None = None,
) -> ArrayIterator:
"""Scan the Vortex file returning a :class:`vortex.ArrayIterator`.
Parameters
----------
projection : :class:`vortex.Expr` | list[str] | None
The projection expression to read, or else read all columns.
expr : :class:`vortex.Expr` | None
The predicate used to filter rows. The filter columns do not need to be in the projection.
limit : :class:`int` | None
The maximum number of rows to read after filtering. If None, read all rows.
indices : :class:`vortex.Array` | None
The indices of the rows to read. Must be sorted and non-null.
batch_size : :class:`int` | None
The number of rows to read per chunk.
Examples
--------
Scan a file with a structured column and nulls at multiple levels and in multiple columns.
>>> import vortex as vx
>>> import vortex.expr as ve
>>> a = vx.array([
... {'name': 'Joseph', 'age': 25},
... {'name': None, 'age': 31},
... {'name': 'Angela', 'age': None},
... {'name': 'Mikhail', 'age': 57},
... {'name': None, 'age': None},
... ])
>>> vx.io.write(a, "a.vortex")
>>> vxf = vx.open("a.vortex")
>>> vxf.scan().read_all().to_arrow_array()
<pyarrow.lib.StructArray object at ...>
-- is_valid: all not null
-- child 0 type: int64
[
25,
31,
null,
57,
null
]
-- child 1 type: string_view
[
"Joseph",
null,
"Angela",
"Mikhail",
null
]
Read just the age column:
>>> vxf.scan(['age']).read_all().to_arrow_array()
<pyarrow.lib.StructArray object at ...>
-- is_valid: all not null
-- child 0 type: int64
[
25,
31,
null,
57,
null
]
Keep rows with an age above 35. This will read O(N_KEPT) rows, when the file format allows.
>>> vxf.scan(expr=ve.column("age") > 35).read_all().to_arrow_array()
<pyarrow.lib.StructArray object at ...>
-- is_valid: all not null
-- child 0 type: int64
[
57
]
-- child 1 type: string_view
[
"Mikhail"
]
"""
return self._file.scan(projection, expr=expr, limit=limit, indices=indices, batch_size=batch_size)
def to_repeated_scan(
self,
projection: IntoProjection = None,
*,
expr: Expr | None = None,
limit: int | None = None,
indices: Array | None = None,
batch_size: int | None = None,
) -> RepeatedScan:
"""Prepare a scan of the Vortex file for repeated reads, returning a :class:`vortex.RepeatedScan`.
Parameters
----------
projection : :class:`vortex.Expr` | list[str] | None
The projection expression to read, or else read all columns.
expr : :class:`vortex.Expr` | None
The predicate used to filter rows. The filter columns do not need to be in the projection.
indices : :class:`vortex.Array` | None
The indices of the rows to read. Must be sorted and non-null.
batch_size : :class:`int` | None
The number of rows to read per chunk.
"""
return RepeatedScan(
self._file.prepare(projection, expr=expr, limit=limit, indices=indices, batch_size=batch_size)
)
def to_arrow(
self,
projection: IntoProjection = None,
*,
limit: int | None = None,
expr: Expr | None = None,
batch_size: int | None = None,
) -> RecordBatchReader:
"""Scan the Vortex file as a :class:`pyarrow.RecordBatchReader`.
Parameters
----------
projection : :class:`vortex.Expr` | list[str] | None
Either an expression over the columns of the file (only referenced columns will be read
from the file) or an explicit list of desired columns.
expr : :class:`vortex.Expr` | None
The predicate used to filter rows. The filter columns need not appear in the projection.
batch_size : :class:`int` | None
The number of rows to read per chunk.
"""
return self._file.to_arrow(projection, expr=expr, limit=limit, batch_size=batch_size)
def to_dataset(self) -> VortexDataset:
"""Scan the Vortex file using the :class:`pyarrow.dataset.Dataset` API."""
return VortexDataset(self._file.to_dataset())
def to_polars(self) -> polars.LazyFrame:
"""Read the Vortex file as a pl.LazyFrame, supporting column pruning and predicate pushdown."""
import polars as pl
from polars.io.plugins import register_io_source
from vortex.polars_ import polars_to_vortex
schema = self.dtype.to_arrow_schema()
def _io_source(
with_columns: list[str] | None,
predicate: pl.Expr | None,
n_rows: int | None,
_batch_size: int | None,
) -> Iterator[pl.DataFrame]:
vx_predicate: Expr | None = None if predicate is None else polars_to_vortex(predicate)
reader = self.to_arrow(projection=with_columns, expr=vx_predicate, limit=n_rows)
for batch in reader:
batch = pl.DataFrame._from_arrow(batch, rechunk=False) # pyright: ignore[reportPrivateUsage]
# TODO(ngates): set sortedness on DataFrame based on stats?
yield batch
# Make sure we always yield at least one empty DataFrame
yield pl.DataFrame._from_arrow( # pyright: ignore[reportPrivateUsage]
data=pa.RecordBatch.from_arrays( # pyright: ignore[reportUnknownMemberType]
[pa.array([], type=field.type) for field in reader.schema], # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType, reportUnknownVariableType]
schema=reader.schema,
),
)
# https://github.com/pola-rs/polars/pull/24125
return register_io_source(_io_source, schema=schema) # pyright: ignore[reportArgumentType]